-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVulnAttribute.java
1616 lines (1530 loc) · 61.6 KB
/
VulnAttribute.java
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
/*
* Copyright (c) 2003, 2010, 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 com.sun.java.util.jar.pack;
import com.sun.java.util.jar.pack.ConstantPool.Entry;
import com.sun.java.util.jar.pack.ConstantPool.Index;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents an attribute in a class-file.
* Takes care to remember where constant pool indexes occur.
* Implements the "little language" of Pack200 for describing
* attribute layouts.
* @author John Rose
*/
class Attribute implements Comparable, Constants {
// Attribute instance fields.
Layout def; // the name and format of this attr
byte[] bytes; // the actual bytes
Object fixups; // reference relocations, if any are required
public String name() { return def.name(); }
public Layout layout() { return def; }
public byte[] bytes() { return bytes; }
public int size() { return bytes.length; }
public Entry getNameRef() { return def.getNameRef(); }
private Attribute(Attribute old) {
this.def = old.def;
this.bytes = old.bytes;
this.fixups = old.fixups;
}
public Attribute(Layout def, byte[] bytes, Object fixups) {
this.def = def;
this.bytes = bytes;
this.fixups = fixups;
Fixups.setBytes(fixups, bytes);
}
public Attribute(Layout def, byte[] bytes) {
this(def, bytes, null);
}
public Attribute addContent(byte[] bytes, Object fixups) {
assert(isCanonical());
if (bytes.length == 0 && fixups == null)
return this;
Attribute res = new Attribute(this);
res.bytes = bytes;
res.fixups = fixups;
Fixups.setBytes(fixups, bytes);
return res;
}
public Attribute addContent(byte[] bytes) {
return addContent(bytes, null);
}
public void finishRefs(Index ix) {
if (fixups != null) {
Fixups.finishRefs(fixups, bytes, ix);
fixups = null;
}
}
public boolean isCanonical() {
return this == def.canon;
}
public int compareTo(Object o) {
Attribute that = (Attribute) o;
return this.def.compareTo(that.def);
}
private static final byte[] noBytes = {};
private static final Map<List<Attribute>, List<Attribute>> canonLists = new HashMap<>();
private static final Map<Layout, Attribute> attributes = new HashMap<>();
private static final Map<Layout, Attribute> standardDefs = new HashMap<>();
// Canonicalized lists of trivial attrs (Deprecated, etc.)
// are used by trimToSize, in order to reduce footprint
// of some common cases. (Note that Code attributes are
// always zero size.)
public static List getCanonList(List<Attribute> al) {
synchronized (canonLists) {
List<Attribute> cl = canonLists.get(al);
if (cl == null) {
cl = new ArrayList<>(al.size());
cl.addAll(al);
cl = Collections.unmodifiableList(cl);
canonLists.put(al, cl);
}
return cl;
}
}
// Find the canonical empty attribute with the given ctype, name, layout.
public static Attribute find(int ctype, String name, String layout) {
Layout key = Layout.makeKey(ctype, name, layout);
synchronized (attributes) {
Attribute a = attributes.get(key);
if (a == null) {
a = new Layout(ctype, name, layout).canonicalInstance();
attributes.put(key, a);
}
return a;
}
}
public static Layout keyForLookup(int ctype, String name) {
return Layout.makeKey(ctype, name);
}
// Find canonical empty attribute with given ctype and name,
// and with the standard layout.
public static Attribute lookup(Map<Layout, Attribute> defs, int ctype,
String name) {
if (defs == null) {
defs = standardDefs;
}
return defs.get(Layout.makeKey(ctype, name));
}
public static Attribute define(Map<Layout, Attribute> defs, int ctype,
String name, String layout) {
Attribute a = find(ctype, name, layout);
defs.put(Layout.makeKey(ctype, name), a);
return a;
}
static {
Map<Layout, Attribute> sd = standardDefs;
define(sd, ATTR_CONTEXT_CLASS, "Signature", "RSH");
define(sd, ATTR_CONTEXT_CLASS, "Synthetic", "");
define(sd, ATTR_CONTEXT_CLASS, "Deprecated", "");
define(sd, ATTR_CONTEXT_CLASS, "SourceFile", "RUH");
define(sd, ATTR_CONTEXT_CLASS, "EnclosingMethod", "RCHRDNH");
define(sd, ATTR_CONTEXT_CLASS, "InnerClasses", "NH[RCHRCNHRUNHFH]");
define(sd, ATTR_CONTEXT_FIELD, "Signature", "RSH");
define(sd, ATTR_CONTEXT_FIELD, "Synthetic", "");
define(sd, ATTR_CONTEXT_FIELD, "Deprecated", "");
define(sd, ATTR_CONTEXT_FIELD, "ConstantValue", "KQH");
define(sd, ATTR_CONTEXT_METHOD, "Signature", "RSH");
define(sd, ATTR_CONTEXT_METHOD, "Synthetic", "");
define(sd, ATTR_CONTEXT_METHOD, "Deprecated", "");
define(sd, ATTR_CONTEXT_METHOD, "Exceptions", "NH[RCH]");
//define(sd, ATTR_CONTEXT_METHOD, "Code", "HHNI[B]NH[PHPOHPOHRCNH]NH[RUHNI[B]]");
define(sd, ATTR_CONTEXT_CODE, "StackMapTable",
("[NH[(1)]]" +
"[TB" +
"(64-127)[(2)]" +
"(247)[(1)(2)]" +
"(248-251)[(1)]" +
"(252)[(1)(2)]" +
"(253)[(1)(2)(2)]" +
"(254)[(1)(2)(2)(2)]" +
"(255)[(1)NH[(2)]NH[(2)]]" +
"()[]" +
"]" +
"[H]" +
"[TB(7)[RCH](8)[PH]()[]]"));
define(sd, ATTR_CONTEXT_CODE, "LineNumberTable", "NH[PHH]");
define(sd, ATTR_CONTEXT_CODE, "LocalVariableTable", "NH[PHOHRUHRSHH]");
define(sd, ATTR_CONTEXT_CODE, "LocalVariableTypeTable", "NH[PHOHRUHRSHH]");
//define(sd, ATTR_CONTEXT_CODE, "CharacterRangeTable", "NH[PHPOHIIH]");
//define(sd, ATTR_CONTEXT_CODE, "CoverageTable", "NH[PHHII]");
// Note: Code and InnerClasses are special-cased elsewhere.
// Their layout specs. are given here for completeness.
// The Code spec is incomplete, in that it does not distinguish
// bytecode bytes or locate CP references.
}
// Metadata.
//
// We define metadata using similar layouts
// for all five kinds of metadata attributes.
//
// Regular annotations are a counted list of [RSHNH[RUH(1)]][...]
// pack.method.attribute.RuntimeVisibleAnnotations=[NH[(1)]][RSHNH[RUH(1)]][TB...]
//
// Parameter annotations are a counted list of regular annotations.
// pack.method.attribute.RuntimeVisibleParameterAnnotations=[NH[(1)]][NH[(1)]][RSHNH[RUH(1)]][TB...]
//
// RuntimeInvisible annotations are defined similarly...
// Non-method annotations are defined similarly...
//
// Annotation are a simple tagged value [TB...]
// pack.attribute.method.AnnotationDefault=[TB...]
//
static {
String mdLayouts[] = {
Attribute.normalizeLayoutString
(""
+"\n # parameter_annotations :="
+"\n [ NB[(1)] ] # forward call to annotations"
),
Attribute.normalizeLayoutString
(""
+"\n # annotations :="
+"\n [ NH[(1)] ] # forward call to annotation"
+"\n "
+"\n # annotation :="
+"\n [RSH"
+"\n NH[RUH (1)] # forward call to value"
+"\n ]"
),
Attribute.normalizeLayoutString
(""
+"\n # value :="
+"\n [TB # Callable 2 encodes one tagged value."
+"\n (\\B,\\C,\\I,\\S,\\Z)[KIH]"
+"\n (\\D)[KDH]"
+"\n (\\F)[KFH]"
+"\n (\\J)[KJH]"
+"\n (\\c)[RSH]"
+"\n (\\e)[RSH RUH]"
+"\n (\\s)[RUH]"
+"\n (\\[)[NH[(0)]] # backward self-call to value"
+"\n (\\@)[RSH NH[RUH (0)]] # backward self-call to value"
+"\n ()[] ]"
)
};
Map<Layout, Attribute> sd = standardDefs;
String defaultLayout = mdLayouts[2];
String annotationsLayout = mdLayouts[1] + mdLayouts[2];
String paramsLayout = mdLayouts[0] + annotationsLayout;
for (int ctype = 0; ctype < ATTR_CONTEXT_LIMIT; ctype++) {
if (ctype == ATTR_CONTEXT_CODE) continue;
define(sd, ctype,
"RuntimeVisibleAnnotations", annotationsLayout);
define(sd, ctype,
"RuntimeInvisibleAnnotations", annotationsLayout);
if (ctype == ATTR_CONTEXT_METHOD) {
define(sd, ctype,
"RuntimeVisibleParameterAnnotations", paramsLayout);
define(sd, ctype,
"RuntimeInvisibleParameterAnnotations", paramsLayout);
define(sd, ctype,
"AnnotationDefault", defaultLayout);
}
}
}
public static String contextName(int ctype) {
switch (ctype) {
case ATTR_CONTEXT_CLASS: return "class";
case ATTR_CONTEXT_FIELD: return "field";
case ATTR_CONTEXT_METHOD: return "method";
case ATTR_CONTEXT_CODE: return "code";
}
return null;
}
/** Base class for any attributed object (Class, Field, Method, Code).
* Flags are included because they are used to help transmit the
* presence of attributes. That is, flags are a mix of modifier
* bits and attribute indicators.
*/
public static abstract
class Holder {
// We need this abstract method to interpret embedded CP refs.
protected abstract Entry[] getCPMap();
protected int flags; // defined here for convenience
protected List<Attribute> attributes;
public int attributeSize() {
return (attributes == null) ? 0 : attributes.size();
}
public void trimToSize() {
if (attributes == null) {
return;
}
if (attributes.isEmpty()) {
attributes = null;
return;
}
if (attributes instanceof ArrayList) {
ArrayList<Attribute> al = (ArrayList<Attribute>)attributes;
al.trimToSize();
boolean allCanon = true;
for (Attribute a : al) {
if (!a.isCanonical()) {
allCanon = false;
}
if (a.fixups != null) {
assert(!a.isCanonical());
a.fixups = Fixups.trimToSize(a.fixups);
}
}
if (allCanon) {
// Replace private writable attribute list
// with only trivial entries by public unique
// immutable attribute list with the same entries.
attributes = getCanonList(al);
}
}
}
public void addAttribute(Attribute a) {
if (attributes == null)
attributes = new ArrayList<>(3);
else if (!(attributes instanceof ArrayList))
attributes = new ArrayList<>(attributes); // unfreeze it
attributes.add(a);
}
public Attribute removeAttribute(Attribute a) {
if (attributes == null) return null;
if (!attributes.contains(a)) return null;
if (!(attributes instanceof ArrayList))
attributes = new ArrayList<>(attributes); // unfreeze it
attributes.remove(a);
return a;
}
public Attribute getAttribute(int n) {
return attributes.get(n);
}
protected void visitRefs(int mode, Collection<Entry> refs) {
if (attributes == null) return;
for (Attribute a : attributes) {
a.visitRefs(this, mode, refs);
}
}
static final List<Attribute> noAttributes = Arrays.asList(new Attribute[0]);
public List<Attribute> getAttributes() {
if (attributes == null)
return noAttributes;
return attributes;
}
public void setAttributes(List<Attribute> attrList) {
if (attrList.isEmpty())
attributes = null;
else
attributes = attrList;
}
public Attribute getAttribute(String attrName) {
if (attributes == null) return null;
for (Attribute a : attributes) {
if (a.name().equals(attrName))
return a;
}
return null;
}
public Attribute getAttribute(Layout attrDef) {
if (attributes == null) return null;
for (Attribute a : attributes) {
if (a.layout() == attrDef)
return a;
}
return null;
}
public Attribute removeAttribute(String attrName) {
return removeAttribute(getAttribute(attrName));
}
public Attribute removeAttribute(Layout attrDef) {
return removeAttribute(getAttribute(attrDef));
}
public void strip(String attrName) {
removeAttribute(getAttribute(attrName));
}
}
// Lightweight interface to hide details of band structure.
// Also used for testing.
public static abstract
class ValueStream {
public int getInt(int bandIndex) { throw undef(); }
public void putInt(int bandIndex, int value) { throw undef(); }
public Entry getRef(int bandIndex) { throw undef(); }
public void putRef(int bandIndex, Entry ref) { throw undef(); }
// Note: decodeBCI goes w/ getInt/Ref; encodeBCI goes w/ putInt/Ref
public int decodeBCI(int bciCode) { throw undef(); }
public int encodeBCI(int bci) { throw undef(); }
public void noteBackCall(int whichCallable) { /* ignore by default */ }
private RuntimeException undef() {
return new UnsupportedOperationException("ValueStream method");
}
}
// Element kinds:
static final byte EK_INT = 1; // B H I SH etc.
static final byte EK_BCI = 2; // PH POH etc.
static final byte EK_BCO = 3; // OH etc.
static final byte EK_FLAG = 4; // FH etc.
static final byte EK_REPL = 5; // NH[...] etc.
static final byte EK_REF = 6; // RUH, RUNH, KQH, etc.
static final byte EK_UN = 7; // TB(...)[...] etc.
static final byte EK_CASE = 8; // (...)[...] etc.
static final byte EK_CALL = 9; // (0), (1), etc.
static final byte EK_CBLE = 10; // [...][...] etc.
static final byte EF_SIGN = 1<<0; // INT is signed
static final byte EF_DELTA = 1<<1; // BCI/BCI value is diff'ed w/ previous
static final byte EF_NULL = 1<<2; // null REF is expected/allowed
static final byte EF_BACK = 1<<3; // call, callable, case is backward
static final int NO_BAND_INDEX = -1;
/** A "class" of attributes, characterized by a context-type, name
* and format. The formats are specified in a "little language".
*/
public static
class Layout implements Comparable {
int ctype; // attribute context type, e.g., ATTR_CONTEXT_CODE
String name; // name of attribute
boolean hasRefs; // this kind of attr contains CP refs?
String layout; // layout specification
int bandCount; // total number of elems
Element[] elems; // tokenization of layout
Attribute canon; // canonical instance of this layout
public int ctype() { return ctype; }
public String name() { return name; }
public String layout() { return layout; }
public Attribute canonicalInstance() { return canon; }
public Entry getNameRef() {
return ConstantPool.getUtf8Entry(name());
}
public boolean isEmpty() { return layout == ""; }
public Layout(int ctype, String name, String layout) {
this.ctype = ctype;
this.name = name.intern();
this.layout = layout.intern();
assert(ctype < ATTR_CONTEXT_LIMIT);
boolean hasCallables = layout.startsWith("[");
try {
if (!hasCallables) {
this.elems = tokenizeLayout(this, -1, layout);
} else {
String[] bodies = splitBodies(layout);
// Make the callables now, so they can be linked immediately.
Element[] elems = new Element[bodies.length];
this.elems = elems;
for (int i = 0; i < elems.length; i++) {
Element ce = this.new Element();
ce.kind = EK_CBLE;
ce.removeBand();
ce.bandIndex = NO_BAND_INDEX;
ce.layout = bodies[i];
elems[i] = ce;
}
// Next fill them in.
for (int i = 0; i < elems.length; i++) {
Element ce = elems[i];
ce.body = tokenizeLayout(this, i, bodies[i]);
}
//System.out.println(Arrays.asList(elems));
}
} catch (StringIndexOutOfBoundsException ee) {
// simplest way to catch syntax errors...
throw new RuntimeException("Bad attribute layout: "+layout, ee);
}
// Some uses do not make a fresh one for each occurrence.
// For example, if layout == "", we only need one attr to share.
canon = new Attribute(this, noBytes);
}
private Layout() {}
static Layout makeKey(int ctype, String name, String layout) {
Layout def = new Layout();
def.ctype = ctype;
def.name = name.intern();
def.layout = layout.intern();
assert(ctype < ATTR_CONTEXT_LIMIT);
return def;
}
static Layout makeKey(int ctype, String name) {
return makeKey(ctype, name, "");
}
public Attribute addContent(byte[] bytes, Object fixups) {
return canon.addContent(bytes, fixups);
}
public Attribute addContent(byte[] bytes) {
return canon.addContent(bytes, null);
}
public boolean equals(Object x) {
return x instanceof Layout && equals((Layout)x);
}
public boolean equals(Layout that) {
return this.name == that.name
&& this.layout == that.layout
&& this.ctype == that.ctype;
}
public int hashCode() {
return (((17 + name.hashCode())
* 37 + layout.hashCode())
* 37 + ctype);
}
public int compareTo(Object o) {
Layout that = (Layout) o;
int r;
r = this.name.compareTo(that.name);
if (r != 0) return r;
r = this.layout.compareTo(that.layout);
if (r != 0) return r;
return this.ctype - that.ctype;
}
public String toString() {
String str = contextName(ctype)+"."+name+"["+layout+"]";
// If -ea, print out more informative strings!
assert((str = stringForDebug()) != null);
return str;
}
private String stringForDebug() {
return contextName(ctype)+"."+name+Arrays.asList(elems);
}
public
class Element {
String layout; // spelling in the little language
byte flags; // EF_SIGN, etc.
byte kind; // EK_UINT, etc.
byte len; // scalar length of element
byte refKind; // CONSTANT_String, etc.
int bandIndex; // which band does this element govern?
int value; // extra parameter
Element[] body; // extra data (for replications, unions, calls)
boolean flagTest(byte mask) { return (flags & mask) != 0; }
Element() {
bandIndex = bandCount++;
}
void removeBand() {
--bandCount;
assert(bandIndex == bandCount);
bandIndex = NO_BAND_INDEX;
}
public boolean hasBand() {
return bandIndex >= 0;
}
public String toString() {
String str = layout;
// If -ea, print out more informative strings!
assert((str = stringForDebug()) != null);
return str;
}
private String stringForDebug() {
Element[] body = this.body;
switch (kind) {
case EK_CALL:
body = null;
break;
case EK_CASE:
if (flagTest(EF_BACK))
body = null;
break;
}
return layout
+ (!hasBand()?"":"#"+bandIndex)
+ "<"+ (flags==0?"":""+flags)+kind+len
+ (refKind==0?"":""+refKind) + ">"
+ (value==0?"":"("+value+")")
+ (body==null?"": ""+Arrays.asList(body));
}
}
public boolean hasCallables() {
return (elems.length > 0 && elems[0].kind == EK_CBLE);
}
static private final Element[] noElems = {};
public Element[] getCallables() {
if (hasCallables())
return elems;
else
return noElems; // no callables at all
}
public Element[] getEntryPoint() {
if (hasCallables())
return elems[0].body; // body of first callable
else
return elems; // no callables; whole body
}
/** Return a sequence of tokens from the given attribute bytes.
* Sequence elements will be 1-1 correspondent with my layout tokens.
*/
public void parse(Holder holder,
byte[] bytes, int pos, int len, ValueStream out) {
int end = parseUsing(getEntryPoint(),
holder, bytes, pos, len, out);
if (end != pos + len)
throw new InternalError("layout parsed "+(end-pos)+" out of "+len+" bytes");
}
/** Given a sequence of tokens, return the attribute bytes.
* Sequence elements must be 1-1 correspondent with my layout tokens.
* The returned object is a cookie for Fixups.finishRefs, which
* must be used to harden any references into integer indexes.
*/
public Object unparse(ValueStream in, ByteArrayOutputStream out) {
Object[] fixups = { null };
unparseUsing(getEntryPoint(), fixups, in, out);
return fixups[0]; // return ref-bearing cookie, if any
}
public String layoutForPackageMajver(int majver) {
if (majver <= JAVA5_PACKAGE_MAJOR_VERSION) {
// Disallow layout syntax in the oldest protocol version.
return expandCaseDashNotation(layout);
}
return layout;
}
}
public static
class FormatException extends IOException {
private int ctype;
private String name;
String layout;
public FormatException(String message,
int ctype, String name, String layout) {
super(ATTR_CONTEXT_NAME[ctype]+ " attribute \"" + name + "\"" +
(message == null? "" : (": " + message)));
this.ctype = ctype;
this.name = name;
this.layout = layout;
}
public FormatException(String message,
int ctype, String name) {
this(message, ctype, name, null);
}
}
void visitRefs(Holder holder, int mode, final Collection refs) {
if (mode == VRM_CLASSIC) {
refs.add(getNameRef());
}
// else the name is owned by the layout, and is processed elsewhere
if (bytes.length == 0) return; // quick exit
if (!def.hasRefs) return; // quick exit
if (fixups != null) {
Fixups.visitRefs(fixups, refs);
return;
}
// References (to a local cpMap) are embedded in the bytes.
def.parse(holder, bytes, 0, bytes.length,
new ValueStream() {
public void putInt(int bandIndex, int value) {
}
public void putRef(int bandIndex, Entry ref) {
refs.add(ref);
}
public int encodeBCI(int bci) {
return bci;
}
});
}
public void parse(Holder holder, byte[] bytes, int pos, int len, ValueStream out) {
def.parse(holder, bytes, pos, len, out);
}
public Object unparse(ValueStream in, ByteArrayOutputStream out) {
return def.unparse(in, out);
}
public String toString() {
return def
+"{"+(bytes == null ? -1 : size())+"}"
+(fixups == null? "": fixups.toString());
}
/** Remove any informal "pretty printing" from the layout string.
* Removes blanks and control chars.
* Removes '#' comments (to end of line).
* Replaces '\c' by the decimal code of the character c.
* Replaces '0xNNN' by the decimal code of the hex number NNN.
*/
static public
String normalizeLayoutString(String layout) {
StringBuffer buf = new StringBuffer();
for (int i = 0, len = layout.length(); i < len; ) {
char ch = layout.charAt(i++);
if (ch <= ' ') {
// Skip whitespace and control chars
continue;
} else if (ch == '#') {
// Skip to end of line.
int end1 = layout.indexOf('\n', i);
int end2 = layout.indexOf('\r', i);
if (end1 < 0) end1 = len;
if (end2 < 0) end2 = len;
i = Math.min(end1, end2);
} else if (ch == '\\') {
// Map a character reference to its decimal code.
buf.append((int) layout.charAt(i++));
} else if (ch == '0' && layout.startsWith("0x", i-1)) {
// Map a hex numeral to its decimal code.
int start = i-1;
int end = start+2;
while (end < len) {
int dig = layout.charAt(end);
if ((dig >= '0' && dig <= '9') ||
(dig >= 'a' && dig <= 'f'))
++end;
else
break;
}
if (end > start) {
String num = layout.substring(start, end);
buf.append(Integer.decode(num));
i = end;
} else {
buf.append(ch);
}
} else {
buf.append(ch);
}
}
String result = buf.toString();
if (false && !result.equals(layout)) {
Utils.log.info("Normalizing layout string");
Utils.log.info(" From: "+layout);
Utils.log.info(" To: "+result);
}
return result;
}
/// Subroutines for parsing and unparsing:
/** Parse the attribute layout language.
<pre>
attribute_layout:
( layout_element )* | ( callable )+
layout_element:
( integral | replication | union | call | reference )
callable:
'[' body ']'
body:
( layout_element )+
integral:
( unsigned_int | signed_int | bc_index | bc_offset | flag )
unsigned_int:
uint_type
signed_int:
'S' uint_type
any_int:
( unsigned_int | signed_int )
bc_index:
( 'P' uint_type | 'PO' uint_type )
bc_offset:
'O' any_int
flag:
'F' uint_type
uint_type:
( 'B' | 'H' | 'I' | 'V' )
replication:
'N' uint_type '[' body ']'
union:
'T' any_int (union_case)* '(' ')' '[' (body)? ']'
union_case:
'(' union_case_tag (',' union_case_tag)* ')' '[' (body)? ']'
union_case_tag:
( numeral | numeral '-' numeral )
call:
'(' numeral ')'
reference:
reference_type ( 'N' )? uint_type
reference_type:
( constant_ref | schema_ref | utf8_ref | untyped_ref )
constant_ref:
( 'KI' | 'KJ' | 'KF' | 'KD' | 'KS' | 'KQ' )
schema_ref:
( 'RC' | 'RS' | 'RD' | 'RF' | 'RM' | 'RI' )
utf8_ref:
'RU'
untyped_ref:
'RQ'
numeral:
'(' ('-')? (digit)+ ')'
digit:
( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' )
</pre>
*/
static //private
Layout.Element[] tokenizeLayout(Layout self, int curCble, String layout) {
ArrayList<Layout.Element> col = new ArrayList<>(layout.length());
tokenizeLayout(self, curCble, layout, col);
Layout.Element[] res = new Layout.Element[col.size()];
col.toArray(res);
return res;
}
static //private
void tokenizeLayout(Layout self, int curCble, String layout, ArrayList<Layout.Element> col) {
boolean prevBCI = false;
for (int len = layout.length(), i = 0; i < len; ) {
int start = i;
int body;
Layout.Element e = self.new Element();
byte kind;
//System.out.println("at "+i+": ..."+layout.substring(i));
// strip a prefix
switch (layout.charAt(i++)) {
/// layout_element: integral
case 'B': case 'H': case 'I': case 'V': // unsigned_int
kind = EK_INT;
--i; // reparse
i = tokenizeUInt(e, layout, i);
break;
case 'S': // signed_int
kind = EK_INT;
--i; // reparse
i = tokenizeSInt(e, layout, i);
break;
case 'P': // bc_index
kind = EK_BCI;
if (layout.charAt(i++) == 'O') {
// bc_index: 'PO' tokenizeUInt
e.flags |= EF_DELTA;
// must follow P or PO:
if (!prevBCI)
{ i = -i; continue; } // fail
i++; // move forward
}
--i; // reparse
i = tokenizeUInt(e, layout, i);
break;
case 'O': // bc_offset
kind = EK_BCO;
e.flags |= EF_DELTA;
// must follow P or PO:
if (!prevBCI)
{ i = -i; continue; } // fail
i = tokenizeSInt(e, layout, i);
break;
case 'F': // flag
kind = EK_FLAG;
i = tokenizeUInt(e, layout, i);
break;
case 'N': // replication: 'N' uint '[' elem ... ']'
kind = EK_REPL;
i = tokenizeUInt(e, layout, i);
if (layout.charAt(i++) != '[')
{ i = -i; continue; } // fail
i = skipBody(layout, body = i);
e.body = tokenizeLayout(self, curCble,
layout.substring(body, i++));
break;
case 'T': // union: 'T' any_int union_case* '(' ')' '[' body ']'
kind = EK_UN;
i = tokenizeSInt(e, layout, i);
ArrayList<Layout.Element> cases = new ArrayList<>();
for (;;) {
// Keep parsing cases until we hit the default case.
if (layout.charAt(i++) != '(')
{ i = -i; break; } // fail
int beg = i;
i = layout.indexOf(')', i);
String cstr = layout.substring(beg, i++);
int cstrlen = cstr.length();
if (layout.charAt(i++) != '[')
{ i = -i; break; } // fail
// Check for duplication.
if (layout.charAt(i) == ']')
body = i; // missing body, which is legal here
else
i = skipBody(layout, body = i);
Layout.Element[] cbody
= tokenizeLayout(self, curCble,
layout.substring(body, i++));
if (cstrlen == 0) {
Layout.Element ce = self.new Element();
ce.body = cbody;
ce.kind = EK_CASE;
ce.removeBand();
cases.add(ce);
break; // done with the whole union
} else {
// Parse a case string.
boolean firstCaseNum = true;
for (int cp = 0, endp;; cp = endp+1) {
// Look for multiple case tags:
endp = cstr.indexOf(',', cp);
if (endp < 0) endp = cstrlen;
String cstr1 = cstr.substring(cp, endp);
if (cstr1.length() == 0)
cstr1 = "empty"; // will fail parse
int value0, value1;
// Check for a case range (new in 1.6).
int dash = findCaseDash(cstr1, 0);
if (dash >= 0) {
value0 = parseIntBefore(cstr1, dash);
value1 = parseIntAfter(cstr1, dash);
if (value0 >= value1)
{ i = -i; break; } // fail
} else {
value0 = value1 = Integer.parseInt(cstr1);
}
// Add a case for each value in value0..value1
for (;; value0++) {
Layout.Element ce = self.new Element();
ce.body = cbody; // all cases share one body
ce.kind = EK_CASE;
ce.removeBand();
if (!firstCaseNum)
// "backward case" repeats a body
ce.flags |= EF_BACK;
firstCaseNum = false;
ce.value = value0;
cases.add(ce);
if (value0 == value1) break;
}
if (endp == cstrlen) {
break; // done with this case
}
}
}
}
e.body = new Layout.Element[cases.size()];
cases.toArray(e.body);
e.kind = kind;
for (int j = 0; j < e.body.length-1; j++) {
Layout.Element ce = e.body[j];
if (matchCase(e, ce.value) != ce) {
// Duplicate tag.
{ i = -i; break; } // fail
}
}
break;
case '(': // call: '(' '-'? digit+ ')'
kind = EK_CALL;
e.removeBand();
i = layout.indexOf(')', i);
String cstr = layout.substring(start+1, i++);
int offset = Integer.parseInt(cstr);
int target = curCble + offset;
if (!(offset+"").equals(cstr) ||
self.elems == null ||
target < 0 ||
target >= self.elems.length)
{ i = -i; continue; } // fail
Layout.Element ce = self.elems[target];
assert(ce.kind == EK_CBLE);
e.value = target;
e.body = new Layout.Element[]{ ce };
// Is it a (recursive) backward call?
if (offset <= 0) {
// Yes. Mark both caller and callee backward.
e.flags |= EF_BACK;
ce.flags |= EF_BACK;
}
break;