aboutsummaryrefslogtreecommitdiff
path: root/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java
blob: 338fbeb9555aebb9b9e1c47edd1614c567f8d79f (plain) (blame)
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
/*
 * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.internal.module;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.module.InvalidModuleDescriptorException;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Builder;
import java.lang.module.ModuleDescriptor.Requires;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.nio.ByteBuffer;
import java.nio.BufferUnderflowException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

import jdk.internal.access.JavaLangModuleAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.misc.VM;

import static jdk.internal.module.ClassFileConstants.*;


/**
 * Read module information from a {@code module-info} class file.
 *
 * @implNote The rationale for the hand-coded reader is startup performance
 * and fine control over the throwing of InvalidModuleDescriptorException.
 */

public final class ModuleInfo {

    private static final JavaLangModuleAccess JLMA
        = SharedSecrets.getJavaLangModuleAccess();

    // supplies the set of packages when ModulePackages attribute not present
    private final Supplier<Set<String>> packageFinder;

    // indicates if the ModuleHashes attribute should be parsed
    private final boolean parseHashes;

    private ModuleInfo(Supplier<Set<String>> pf, boolean ph) {
        packageFinder = pf;
        parseHashes = ph;
    }

    private ModuleInfo(Supplier<Set<String>> pf) {
        this(pf, true);
    }

    /**
     * A holder class for the ModuleDescriptor that is created by reading the
     * Module and other standard class file attributes. It also holds the objects
     * that represent the non-standard class file attributes that are read from
     * the class file.
     */
    public static final class Attributes {
        private final ModuleDescriptor descriptor;
        private final ModuleTarget target;
        private final ModuleHashes recordedHashes;
        private final ModuleResolution moduleResolution;
        Attributes(ModuleDescriptor descriptor,
                   ModuleTarget target,
                   ModuleHashes recordedHashes,
                   ModuleResolution moduleResolution) {
            this.descriptor = descriptor;
            this.target = target;
            this.recordedHashes = recordedHashes;
            this.moduleResolution = moduleResolution;
        }
        public ModuleDescriptor descriptor() {
            return descriptor;
        }
        public ModuleTarget target() {
            return target;
        }
        public ModuleHashes recordedHashes() {
            return recordedHashes;
        }
        public ModuleResolution moduleResolution() {
            return moduleResolution;
        }
    }


    /**
     * Reads a {@code module-info.class} from the given input stream.
     *
     * @throws InvalidModuleDescriptorException
     * @throws IOException
     */
    public static Attributes read(InputStream in, Supplier<Set<String>> pf)
        throws IOException
    {
        try {
            return new ModuleInfo(pf).doRead(new DataInputStream(in));
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw invalidModuleDescriptor(e.getMessage());
        } catch (EOFException x) {
            throw truncatedModuleDescriptor();
        }
    }

    /**
     * Reads a {@code module-info.class} from the given byte buffer.
     *
     * @throws InvalidModuleDescriptorException
     * @throws UncheckedIOException
     */
    public static Attributes read(ByteBuffer bb, Supplier<Set<String>> pf) {
        try {
            return new ModuleInfo(pf).doRead(new DataInputWrapper(bb));
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw invalidModuleDescriptor(e.getMessage());
        } catch (EOFException x) {
            throw truncatedModuleDescriptor();
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }

    /**
     * Reads a {@code module-info.class} from the given byte buffer
     * but ignore the {@code ModuleHashes} attribute.
     *
     * @throws InvalidModuleDescriptorException
     * @throws UncheckedIOException
     */
    public static Attributes readIgnoringHashes(ByteBuffer bb, Supplier<Set<String>> pf) {
        try {
            return new ModuleInfo(pf, false).doRead(new DataInputWrapper(bb));
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw invalidModuleDescriptor(e.getMessage());
        } catch (EOFException x) {
            throw truncatedModuleDescriptor();
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }

    /**
     * Reads the input as a module-info class file.
     *
     * @throws IOException
     * @throws InvalidModuleDescriptorException
     * @throws IllegalArgumentException if thrown by the ModuleDescriptor.Builder
     *         because an identifier is not a legal Java identifier, duplicate
     *         exports, and many other reasons
     */
    private Attributes doRead(DataInput input) throws IOException {
        var in = new CountingDataInput(input);

        int magic = in.readInt();
        if (magic != 0xCAFEBABE)
            throw invalidModuleDescriptor("Bad magic number");

        int minor_version = in.readUnsignedShort();
        int major_version = in.readUnsignedShort();
        if (!VM.isSupportedModuleDescriptorVersion(major_version, minor_version)) {
            throw invalidModuleDescriptor("Unsupported major.minor version "
                                          + major_version + "." + minor_version);
        }

        ConstantPool cpool = new ConstantPool(in);

        int access_flags = in.readUnsignedShort();
        if (access_flags != ACC_MODULE)
            throw invalidModuleDescriptor("access_flags should be ACC_MODULE");

        int this_class = in.readUnsignedShort();
        String mn = cpool.getClassName(this_class);
        if (!"module-info".equals(mn))
            throw invalidModuleDescriptor("this_class should be module-info");

        int super_class = in.readUnsignedShort();
        if (super_class > 0)
            throw invalidModuleDescriptor("bad #super_class");

        int interfaces_count = in.readUnsignedShort();
        if (interfaces_count > 0)
            throw invalidModuleDescriptor("Bad #interfaces");

        int fields_count = in.readUnsignedShort();
        if (fields_count > 0)
            throw invalidModuleDescriptor("Bad #fields");

        int methods_count = in.readUnsignedShort();
        if (methods_count > 0)
            throw invalidModuleDescriptor("Bad #methods");

        int attributes_count = in.readUnsignedShort();

        // the names of the attributes found in the class file
        Set<String> attributes = new HashSet<>();

        Builder builder = null;
        Set<String> allPackages = null;
        String mainClass = null;
        ModuleTarget moduleTarget = null;
        ModuleHashes moduleHashes = null;
        ModuleResolution moduleResolution = null;

        for (int i = 0; i < attributes_count ; i++) {
            int name_index = in.readUnsignedShort();
            String attribute_name = cpool.getUtf8(name_index);
            int length = in.readInt();

            boolean added = attributes.add(attribute_name);
            if (!added && isAttributeAtMostOnce(attribute_name)) {
                throw invalidModuleDescriptor("More than one "
                                              + attribute_name + " attribute");
            }

            long initialPosition = in.count();

            switch (attribute_name) {
                case MODULE :
                    builder = readModuleAttribute(in, cpool, major_version);
                    break;

                case MODULE_PACKAGES :
                    allPackages = readModulePackagesAttribute(in, cpool);
                    break;

                case MODULE_MAIN_CLASS :
                    mainClass = readModuleMainClassAttribute(in, cpool);
                    break;

                case MODULE_TARGET :
                    moduleTarget = readModuleTargetAttribute(in, cpool);
                    break;

                case MODULE_HASHES :
                    if (parseHashes) {
                        moduleHashes = readModuleHashesAttribute(in, cpool);
                    } else {
                        in.skipBytes(length);
                    }
                    break;

                case MODULE_RESOLUTION :
                    moduleResolution = readModuleResolution(in, cpool);
                    break;

                default:
                    if (isAttributeDisallowed(attribute_name)) {
                        throw invalidModuleDescriptor(attribute_name
                                                      + " attribute not allowed");
                    } else {
                        in.skipBytes(length);
                    }
            }

            long newPosition = in.count();
            if ((newPosition - initialPosition) != length) {
                // attribute length does not match actual attribute size
                throw invalidModuleDescriptor("Attribute " + attribute_name
                        + " does not match its expected length");
            }

        }

        // the Module attribute is required
        if (builder == null) {
            throw invalidModuleDescriptor(MODULE + " attribute not found");
        }

        // ModuleMainClass  attribute
        if (mainClass != null) {
            builder.mainClass(mainClass);
        }

        // If the ModulePackages attribute is not present then the packageFinder
        // is used to find the set of packages
        boolean usedPackageFinder = false;
        if (allPackages == null && packageFinder != null) {
            try {
                allPackages = packageFinder.get();
            } catch (UncheckedIOException x) {
                throw x.getCause();
            }
            usedPackageFinder = true;
        }
        if (allPackages != null) {
            Set<String> knownPackages = JLMA.packages(builder);
            if (!allPackages.containsAll(knownPackages)) {
                Set<String> missingPackages = new HashSet<>(knownPackages);
                missingPackages.removeAll(allPackages);
                assert !missingPackages.isEmpty();
                String missingPackage = missingPackages.iterator().next();
                String tail;
                if (usedPackageFinder) {
                    tail = " not found in module";
                } else {
                    tail = " missing from ModulePackages class file attribute";
                }
                throw invalidModuleDescriptor("Package " + missingPackage + tail);

            }
            builder.packages(allPackages);
        }

        ModuleDescriptor descriptor = builder.build();
        return new Attributes(descriptor,
                              moduleTarget,
                              moduleHashes,
                              moduleResolution);
    }

    /**
     * Reads the Module attribute, returning the ModuleDescriptor.Builder to
     * build the corresponding ModuleDescriptor.
     */
    private Builder readModuleAttribute(DataInput in, ConstantPool cpool, int major)
        throws IOException
    {
        // module_name
        int module_name_index = in.readUnsignedShort();
        String mn = cpool.getModuleName(module_name_index);

        int module_flags = in.readUnsignedShort();

        Set<ModuleDescriptor.Modifier> modifiers = new HashSet<>();
        boolean open = ((module_flags & ACC_OPEN) != 0);
        if (open)
            modifiers.add(ModuleDescriptor.Modifier.OPEN);
        if ((module_flags & ACC_SYNTHETIC) != 0)
            modifiers.add(ModuleDescriptor.Modifier.SYNTHETIC);
        if ((module_flags & ACC_MANDATED) != 0)
            modifiers.add(ModuleDescriptor.Modifier.MANDATED);

        Builder builder = JLMA.newModuleBuilder(mn, false, modifiers);

        int module_version_index = in.readUnsignedShort();
        if (module_version_index != 0) {
            String vs = cpool.getUtf8(module_version_index);
            builder.version(vs);
        }

        int requires_count = in.readUnsignedShort();
        boolean requiresJavaBase = false;
        for (int i=0; i<requires_count; i++) {
            int requires_index = in.readUnsignedShort();
            String dn = cpool.getModuleName(requires_index);

            int requires_flags = in.readUnsignedShort();
            Set<Requires.Modifier> mods;
            if (requires_flags == 0) {
                mods = Set.of();
            } else {
                mods = new HashSet<>();
                if ((requires_flags & ACC_TRANSITIVE) != 0)
                    mods.add(Requires.Modifier.TRANSITIVE);
                if ((requires_flags & ACC_STATIC_PHASE) != 0)
                    mods.add(Requires.Modifier.STATIC);
                if ((requires_flags & ACC_SYNTHETIC) != 0)
                    mods.add(Requires.Modifier.SYNTHETIC);
                if ((requires_flags & ACC_MANDATED) != 0)
                    mods.add(Requires.Modifier.MANDATED);
            }

            int requires_version_index = in.readUnsignedShort();
            if (requires_version_index == 0) {
                builder.requires(mods, dn);
            } else {
                String vs = cpool.getUtf8(requires_version_index);
                JLMA.requires(builder, mods, dn, vs);
            }

            if (dn.equals("java.base")) {
                if (major >= 54
                    && (mods.contains(Requires.Modifier.TRANSITIVE)
                        || mods.contains(Requires.Modifier.STATIC))) {
                    String flagName;
                    if (mods.contains(Requires.Modifier.TRANSITIVE)) {
                        flagName = "ACC_TRANSITIVE";
                    } else {
                        flagName = "ACC_STATIC_PHASE";
                    }
                    throw invalidModuleDescriptor("The requires entry for java.base"
                                                  + " has " + flagName + " set");
                }
                requiresJavaBase = true;
            }
        }
        if (mn.equals("java.base")) {
            if (requires_count > 0) {
                throw invalidModuleDescriptor("The requires table for java.base"
                                              + " must be 0 length");
            }
        } else if (!requiresJavaBase) {
            throw invalidModuleDescriptor("The requires table must have"
                                          + " an entry for java.base");
        }

        int exports_count = in.readUnsignedShort();
        if (exports_count > 0) {
            for (int i=0; i<exports_count; i++) {
                int exports_index = in.readUnsignedShort();
                String pkg = cpool.getPackageName(exports_index);

                Set<Exports.Modifier> mods;
                int exports_flags = in.readUnsignedShort();
                if (exports_flags == 0) {
                    mods = Set.of();
                } else {
                    mods = new HashSet<>();
                    if ((exports_flags & ACC_SYNTHETIC) != 0)
                        mods.add(Exports.Modifier.SYNTHETIC);
                    if ((exports_flags & ACC_MANDATED) != 0)
                        mods.add(Exports.Modifier.MANDATED);
                }

                int exports_to_count = in.readUnsignedShort();
                if (exports_to_count > 0) {
                    Set<String> targets = new HashSet<>(exports_to_count);
                    for (int j=0; j<exports_to_count; j++) {
                        int exports_to_index = in.readUnsignedShort();
                        String target = cpool.getModuleName(exports_to_index);
                        if (!targets.add(target)) {
                            throw invalidModuleDescriptor(pkg + " exported to "
                                                          + target + " more than once");
                        }
                    }
                    builder.exports(mods, pkg, targets);
                } else {
                    builder.exports(mods, pkg);
                }
            }
        }

        int opens_count = in.readUnsignedShort();
        if (opens_count > 0) {
            if (open) {
                throw invalidModuleDescriptor("The opens table for an open"
                                              + " module must be 0 length");
            }
            for (int i=0; i<opens_count; i++) {
                int opens_index = in.readUnsignedShort();
                String pkg = cpool.getPackageName(opens_index);

                Set<Opens.Modifier> mods;
                int opens_flags = in.readUnsignedShort();
                if (opens_flags == 0) {
                    mods = Set.of();
                } else {
                    mods = new HashSet<>();
                    if ((opens_flags & ACC_SYNTHETIC) != 0)
                        mods.add(Opens.Modifier.SYNTHETIC);
                    if ((opens_flags & ACC_MANDATED) != 0)
                        mods.add(Opens.Modifier.MANDATED);
                }

                int open_to_count = in.readUnsignedShort();
                if (open_to_count > 0) {
                    Set<String> targets = new HashSet<>(open_to_count);
                    for (int j=0; j<open_to_count; j++) {
                        int opens_to_index = in.readUnsignedShort();
                        String target = cpool.getModuleName(opens_to_index);
                        if (!targets.add(target)) {
                            throw invalidModuleDescriptor(pkg + " opened to "
                                                          + target + " more than once");
                        }
                    }
                    builder.opens(mods, pkg, targets);
                } else {
                    builder.opens(mods, pkg);
                }
            }
        }

        int uses_count = in.readUnsignedShort();
        if (uses_count > 0) {
            for (int i=0; i<uses_count; i++) {
                int index = in.readUnsignedShort();
                String sn = cpool.getClassName(index);
                builder.uses(sn);
            }
        }

        int provides_count = in.readUnsignedShort();
        if (provides_count > 0) {
            for (int i=0; i<provides_count; i++) {
                int index = in.readUnsignedShort();
                String sn = cpool.getClassName(index);
                int with_count = in.readUnsignedShort();
                List<String> providers = new ArrayList<>(with_count);
                for (int j=0; j<with_count; j++) {
                    index = in.readUnsignedShort();
                    String pn = cpool.getClassName(index);
                    if (!providers.add(pn)) {
                        throw invalidModuleDescriptor(sn + " provides " + pn
                                                      + " more than once");
                    }
                }
                builder.provides(sn, providers);
            }
        }

        return builder;
    }

    /**
     * Reads the ModulePackages attribute
     */
    private Set<String> readModulePackagesAttribute(DataInput in, ConstantPool cpool)
        throws IOException
    {
        int package_count = in.readUnsignedShort();
        Set<String> packages = new HashSet<>(package_count);
        for (int i=0; i<package_count; i++) {
            int index = in.readUnsignedShort();
            String pn = cpool.getPackageName(index);
            boolean added = packages.add(pn);
            if (!added) {
                throw invalidModuleDescriptor("Package " + pn + " in ModulePackages"
                                              + "attribute more than once");
            }
        }
        return packages;
    }

    /**
     * Reads the ModuleMainClass attribute
     */
    private String readModuleMainClassAttribute(DataInput in, ConstantPool cpool)
        throws IOException
    {
        int index = in.readUnsignedShort();
        return cpool.getClassName(index);
    }

    /**
     * Reads the ModuleTarget attribute
     */
    private ModuleTarget readModuleTargetAttribute(DataInput in, ConstantPool cpool)
        throws IOException
    {
        String targetPlatform = null;

        int index = in.readUnsignedShort();
        if (index != 0)
            targetPlatform = cpool.getUtf8(index);

        return new ModuleTarget(targetPlatform);
    }

    /**
     * Reads the ModuleHashes attribute
     */
    private ModuleHashes readModuleHashesAttribute(DataInput in, ConstantPool cpool)
        throws IOException
    {
        int algorithm_index = in.readUnsignedShort();
        String algorithm = cpool.getUtf8(algorithm_index);

        int hash_count = in.readUnsignedShort();
        Map<String, byte[]> map = new HashMap<>(hash_count);
        for (int i=0; i<hash_count; i++) {
            int module_name_index = in.readUnsignedShort();
            String mn = cpool.getModuleName(module_name_index);
            int hash_length = in.readUnsignedShort();
            if (hash_length == 0) {
                throw invalidModuleDescriptor("hash_length == 0");
            }
            byte[] hash = new byte[hash_length];
            in.readFully(hash);
            map.put(mn, hash);
        }

        return new ModuleHashes(algorithm, map);
    }

    /**
     * Reads the ModuleResolution attribute.
     */
    private ModuleResolution readModuleResolution(DataInput in,
                                                  ConstantPool cpool)
        throws IOException
    {
        int flags = in.readUnsignedShort();

        int reason = 0;
        if ((flags & WARN_DEPRECATED) != 0)
            reason = WARN_DEPRECATED;
        if ((flags & WARN_DEPRECATED_FOR_REMOVAL) != 0) {
            if (reason != 0)
                throw invalidModuleDescriptor("Bad module resolution flags:" + flags);
            reason = WARN_DEPRECATED_FOR_REMOVAL;
        }
        if ((flags & WARN_INCUBATING) != 0) {
            if (reason != 0)
                throw invalidModuleDescriptor("Bad module resolution flags:" + flags);
        }

        return new ModuleResolution(flags);
    }

    /**
     * Returns true if the given attribute can be present at most once
     * in the class file. Returns false otherwise.
     */
    private static boolean isAttributeAtMostOnce(String name) {

        if (name.equals(MODULE) ||
                name.equals(SOURCE_FILE) ||
                name.equals(SDE) ||
                name.equals(MODULE_PACKAGES) ||
                name.equals(MODULE_MAIN_CLASS) ||
                name.equals(MODULE_TARGET) ||
                name.equals(MODULE_HASHES) ||
                name.equals(MODULE_RESOLUTION))
            return true;

        return false;
    }

    /**
     * Return true if the given attribute name is the name of a pre-defined
     * attribute in JVMS 4.7 that is not allowed in a module-info class.
     */
    private static boolean isAttributeDisallowed(String name) {
        Set<String> notAllowed = predefinedNotAllowed;
        if (notAllowed == null) {
            notAllowed = Set.of(
                    "ConstantValue",
                    "Code",
                    "Deprecated",
                    "StackMapTable",
                    "Exceptions",
                    "EnclosingMethod",
                    "Signature",
                    "LineNumberTable",
                    "LocalVariableTable",
                    "LocalVariableTypeTable",
                    "RuntimeVisibleParameterAnnotations",
                    "RuntimeInvisibleParameterAnnotations",
                    "RuntimeVisibleTypeAnnotations",
                    "RuntimeInvisibleTypeAnnotations",
                    "Synthetic",
                    "AnnotationDefault",
                    "BootstrapMethods",
                    "MethodParameters");
            predefinedNotAllowed = notAllowed;
        }
        return notAllowed.contains(name);
    }

    // lazily created set the pre-defined attributes that are not allowed
    private static volatile Set<String> predefinedNotAllowed;


    /**
     * The constant pool in a class file.
     */
    private static class ConstantPool {
        static final int CONSTANT_Utf8 = 1;
        static final int CONSTANT_Integer = 3;
        static final int CONSTANT_Float = 4;
        static final int CONSTANT_Long = 5;
        static final int CONSTANT_Double = 6;
        static final int CONSTANT_Class = 7;
        static final int CONSTANT_String = 8;
        static final int CONSTANT_Fieldref = 9;
        static final int CONSTANT_Methodref = 10;
        static final int CONSTANT_InterfaceMethodref = 11;
        static final int CONSTANT_NameAndType = 12;
        static final int CONSTANT_MethodHandle = 15;
        static final int CONSTANT_MethodType = 16;
        static final int CONSTANT_InvokeDynamic = 18;
        static final int CONSTANT_Module = 19;
        static final int CONSTANT_Package = 20;

        private static class Entry {
            protected Entry(int tag) {
                this.tag = tag;
            }
            final int tag;
        }

        private static class IndexEntry extends Entry {
            IndexEntry(int tag, int index) {
                super(tag);
                this.index = index;
            }
            final int index;
        }

        private static class Index2Entry extends Entry {
            Index2Entry(int tag, int index1, int index2) {
                super(tag);
                this.index1 = index1;
                this.index2 = index2;
            }
            final int index1,  index2;
        }

        private static class ValueEntry extends Entry {
            ValueEntry(int tag, Object value) {
                super(tag);
                this.value = value;
            }
            final Object value;
        }

        final Entry[] pool;

        ConstantPool(DataInput in) throws IOException {
            int count = in.readUnsignedShort();
            pool = new Entry[count];

            for (int i = 1; i < count; i++) {
                int tag = in.readUnsignedByte();
                switch (tag) {

                    case CONSTANT_Utf8:
                        String svalue = in.readUTF();
                        pool[i] = new ValueEntry(tag, svalue);
                        break;

                    case CONSTANT_Class:
                    case CONSTANT_Package:
                    case CONSTANT_Module:
                    case CONSTANT_String:
                        int index = in.readUnsignedShort();
                        pool[i] = new IndexEntry(tag, index);
                        break;

                    case CONSTANT_Double:
                        double dvalue = in.readDouble();
                        pool[i] = new ValueEntry(tag, dvalue);
                        i++;
                        break;

                    case CONSTANT_Fieldref:
                    case CONSTANT_InterfaceMethodref:
                    case CONSTANT_Methodref:
                    case CONSTANT_InvokeDynamic:
                    case CONSTANT_NameAndType:
                        int index1 = in.readUnsignedShort();
                        int index2 = in.readUnsignedShort();
                        pool[i] = new Index2Entry(tag, index1, index2);
                        break;

                    case CONSTANT_MethodHandle:
                        int refKind = in.readUnsignedByte();
                        index = in.readUnsignedShort();
                        pool[i] = new Index2Entry(tag, refKind, index);
                        break;

                    case CONSTANT_MethodType:
                        index = in.readUnsignedShort();
                        pool[i] = new IndexEntry(tag, index);
                        break;

                    case CONSTANT_Float:
                        float fvalue = in.readFloat();
                        pool[i] = new ValueEntry(tag, fvalue);
                        break;

                    case CONSTANT_Integer:
                        int ivalue = in.readInt();
                        pool[i] = new ValueEntry(tag, ivalue);
                        break;

                    case CONSTANT_Long:
                        long lvalue = in.readLong();
                        pool[i] = new ValueEntry(tag, lvalue);
                        i++;
                        break;

                    default:
                        throw invalidModuleDescriptor("Bad constant pool entry: "
                                                      + i);
                }
            }
        }

        String getClassName(int index) {
            checkIndex(index);
            Entry e = pool[index];
            if (e.tag != CONSTANT_Class) {
                throw invalidModuleDescriptor("CONSTANT_Class expected at entry: "
                                              + index);
            }
            String value = getUtf8(((IndexEntry) e).index);
            checkUnqualifiedName("CONSTANT_Class", index, value);
            return value.replace('/', '.');  // internal form -> binary name
        }

        String getPackageName(int index) {
            checkIndex(index);
            Entry e = pool[index];
            if (e.tag != CONSTANT_Package) {
                throw invalidModuleDescriptor("CONSTANT_Package expected at entry: "
                                              + index);
            }
            String value = getUtf8(((IndexEntry) e).index);
            checkUnqualifiedName("CONSTANT_Package", index, value);
            return value.replace('/', '.');  // internal form -> binary name
        }

        String getModuleName(int index) {
            checkIndex(index);
            Entry e = pool[index];
            if (e.tag != CONSTANT_Module) {
                throw invalidModuleDescriptor("CONSTANT_Module expected at entry: "
                                              + index);
            }
            String value = getUtf8(((IndexEntry) e).index);
            return decodeModuleName(index, value);
        }

        String getUtf8(int index) {
            checkIndex(index);
            Entry e = pool[index];
            if (e.tag != CONSTANT_Utf8) {
                throw invalidModuleDescriptor("CONSTANT_Utf8 expected at entry: "
                                              + index);
            }
            return (String) (((ValueEntry) e).value);
        }

        void checkIndex(int index) {
            if (index < 1 || index >= pool.length)
                throw invalidModuleDescriptor("Index into constant pool out of range");
        }

        void checkUnqualifiedName(String what, int index, String value) {
            int len = value.length();
            if (len == 0) {
                throw invalidModuleDescriptor(what + " at entry " + index
                                              + " has zero length");
            }
            for (int i=0; i<len; i++) {
                char c = value.charAt(i);
                if (c == '.' || c == ';' || c == '[') {
                    throw invalidModuleDescriptor(what + " at entry " + index
                                                  + " has illegal character: '"
                                                  + c + "'");
                }
            }
        }

        /**
         * "Decode" a module name that has been read from the constant pool.
         */
        String decodeModuleName(int index, String value) {
            int len = value.length();
            if (len == 0) {
                throw invalidModuleDescriptor("CONSTANT_Module at entry "
                                              + index + " is zero length");
            }
            int i = 0;
            while (i < len) {
                int cp = value.codePointAt(i);
                if (cp == ':' || cp == '@' || cp < 0x20) {
                    throw invalidModuleDescriptor("CONSTANT_Module at entry "
                                                  + index + " has illegal character: "
                                                  + Character.getName(cp));
                }

                // blackslash is the escape character
                if (cp == '\\')
                    return decodeModuleName(index, i, value);

                i += Character.charCount(cp);
            }
            return value;
        }

        /**
         * "Decode" a module name that has been read from the constant pool and
         * partly checked for illegal characters (up to position {@code i}).
         */
        String decodeModuleName(int index, int i, String value) {
            StringBuilder sb = new StringBuilder();

            // copy the code points that have been checked
            int j = 0;
            while (j < i) {
                int cp = value.codePointAt(j);
                sb.appendCodePoint(cp);
                j += Character.charCount(cp);
            }

            // decode from position {@code i} to end
            int len = value.length();
            while (i < len) {
                int cp = value.codePointAt(i);
                if (cp == ':' || cp == '@' || cp < 0x20) {
                    throw invalidModuleDescriptor("CONSTANT_Module at entry "
                                                  + index + " has illegal character: "
                                                  + Character.getName(cp));
                }

                // blackslash is the escape character
                if (cp == '\\') {
                    j = i + Character.charCount(cp);
                    if (j >= len) {
                        throw invalidModuleDescriptor("CONSTANT_Module at entry "
                                                       + index + " has illegal "
                                                       + "escape sequence");
                    }
                    int next = value.codePointAt(j);
                    if (next != '\\' && next != ':' && next != '@') {
                        throw invalidModuleDescriptor("CONSTANT_Module at entry "
                                                      + index + " has illegal "
                                                      + "escape sequence");
                    }
                    sb.appendCodePoint(next);
                    i += Character.charCount(next);
                } else {
                    sb.appendCodePoint(cp);
                }

                i += Character.charCount(cp);
            }
            return sb.toString();
        }
    }

    /**
     * A DataInput implementation that reads from a ByteBuffer.
     */
    private static class DataInputWrapper implements DataInput {
        private final ByteBuffer bb;

        DataInputWrapper(ByteBuffer bb) {
            this.bb = bb;
        }

        @Override
        public void readFully(byte b[]) throws IOException {
            readFully(b, 0, b.length);
        }

        @Override
        public void readFully(byte b[], int off, int len) throws IOException {
            try {
                bb.get(b, off, len);
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public int skipBytes(int n) {
            int skip = Math.min(n, bb.remaining());
            bb.position(bb.position() + skip);
            return skip;
        }

        @Override
        public boolean readBoolean() throws IOException {
            try {
                int ch = bb.get();
                return (ch != 0);
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public byte readByte() throws IOException {
            try {
                return bb.get();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public int readUnsignedByte() throws IOException {
            try {
                return ((int) bb.get()) & 0xff;
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public short readShort() throws IOException {
            try {
                return bb.getShort();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public int readUnsignedShort() throws IOException {
            try {
                return ((int) bb.getShort()) & 0xffff;
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public char readChar() throws IOException {
            try {
                return bb.getChar();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public int readInt() throws IOException {
            try {
                return bb.getInt();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public long readLong() throws IOException {
            try {
                return bb.getLong();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public float readFloat() throws IOException {
            try {
                return bb.getFloat();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public double readDouble() throws IOException {
            try {
                return bb.getDouble();
            } catch (BufferUnderflowException e) {
                throw new EOFException(e.getMessage());
            }
        }

        @Override
        public String readLine() {
            throw new RuntimeException("not implemented");
        }

        @Override
        public String readUTF() throws IOException {
            // ### Need to measure the performance and feasibility of using
            // the UTF-8 decoder instead.
            return DataInputStream.readUTF(this);
        }
    }

    /**
     * A DataInput implementation that reads from another DataInput and counts
     * the number of bytes read.
     */
    private static class CountingDataInput implements DataInput {
        private final DataInput delegate;
        private long count;

        CountingDataInput(DataInput delegate) {
            this.delegate = delegate;
        }

        long count() {
            return count;
        }

        @Override
        public void readFully(byte b[]) throws IOException {
            delegate.readFully(b, 0, b.length);
            count += b.length;
        }

        @Override
        public void readFully(byte b[], int off, int len) throws IOException {
            delegate.readFully(b, off, len);
            count += len;
        }

        @Override
        public int skipBytes(int n) throws IOException {
            int skip = delegate.skipBytes(n);
            count += skip;
            return skip;
        }

        @Override
        public boolean readBoolean() throws IOException {
            boolean b = delegate.readBoolean();
            count++;
            return b;
        }

        @Override
        public byte readByte() throws IOException {
            byte b = delegate.readByte();
            count++;
            return b;
        }

        @Override
        public int readUnsignedByte() throws IOException {
            int i = delegate.readUnsignedByte();
            count++;
            return i;
        }

        @Override
        public short readShort() throws IOException {
            short s = delegate.readShort();
            count += 2;
            return s;
        }

        @Override
        public int readUnsignedShort() throws IOException {
            int s = delegate.readUnsignedShort();
            count += 2;
            return s;
        }

        @Override
        public char readChar() throws IOException {
            char c = delegate.readChar();
            count += 2;
            return c;
        }

        @Override
        public int readInt() throws IOException {
            int i = delegate.readInt();
            count += 4;
            return i;
        }

        @Override
        public long readLong() throws IOException {
            long l = delegate.readLong();
            count += 8;
            return l;
        }

        @Override
        public float readFloat() throws IOException {
            float f = delegate.readFloat();
            count += 4;
            return f;
        }

        @Override
        public double readDouble() throws IOException {
            double d = delegate.readDouble();
            count += 8;
            return d;
        }

        @Override
        public String readLine() {
            throw new RuntimeException("not implemented");
        }

        @Override
        public String readUTF() throws IOException {
            return DataInputStream.readUTF(this);
        }
    }

    /**
     * Returns an InvalidModuleDescriptorException with the given detail
     * message
     */
    private static InvalidModuleDescriptorException invalidModuleDescriptor(String msg) {
        return new InvalidModuleDescriptorException(msg);
    }

    /**
     * Returns an InvalidModuleDescriptorException with a detail message to
     * indicate that the class file is truncated.
     */
    private static InvalidModuleDescriptorException truncatedModuleDescriptor() {
        return invalidModuleDescriptor("Truncated module-info.class");
    }

}