1 /*
  2  * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package com.sun.tools.javac.jvm;
 27 
 28 import com.sun.tools.javac.code.Kinds.Kind;
 29 import com.sun.tools.javac.code.Symbol;
 30 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 31 import com.sun.tools.javac.code.Symbol.DynamicMethodSymbol;
 32 import com.sun.tools.javac.code.Symbol.MethodHandleSymbol;
 33 import com.sun.tools.javac.code.Symbol.ModuleSymbol;
 34 import com.sun.tools.javac.code.Symbol.PackageSymbol;
 35 import com.sun.tools.javac.code.Type;
 36 import com.sun.tools.javac.code.Type.ConstantPoolQType;
 37 import com.sun.tools.javac.code.Types;
 38 import com.sun.tools.javac.jvm.ClassWriter.PoolOverflow;
 39 import com.sun.tools.javac.jvm.ClassWriter.StringOverflow;
 40 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
 41 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant.BasicConstant;
 42 import com.sun.tools.javac.jvm.PoolConstant.Dynamic;
 43 import com.sun.tools.javac.jvm.PoolConstant.Dynamic.BsmKey;
 44 import com.sun.tools.javac.jvm.PoolConstant.NameAndType;
 45 import com.sun.tools.javac.util.ByteBuffer;
 46 import com.sun.tools.javac.util.List;
 47 import com.sun.tools.javac.util.Name;
 48 import com.sun.tools.javac.util.Names;
 49 
 50 import java.io.IOException;
 51 import java.io.OutputStream;
 52 import java.util.ArrayDeque;
 53 import java.util.HashMap;
 54 import java.util.LinkedHashMap;
 55 import java.util.LinkedHashSet;
 56 import java.util.Map;
 57 
 58 import static com.sun.tools.javac.code.Kinds.Kind.TYP;
 59 import static com.sun.tools.javac.code.TypeTag.ARRAY;
 60 import static com.sun.tools.javac.code.TypeTag.CLASS;
 61 import static com.sun.tools.javac.jvm.ClassFile.CONSTANT_Class;
 62 import static com.sun.tools.javac.jvm.ClassFile.CONSTANT_MethodType;
 63 import static com.sun.tools.javac.jvm.ClassFile.externalize;
 64 
 65 /**
 66  * Pool interface towards {@code ClassWriter}. Exposes methods to encode and write javac entities
 67  * into the constant pool.
 68  *
 69  *  <p><b>This is NOT part of any supported API.
 70  *  If you write code that depends on this, you do so at your own risk.
 71  *  This code and its internal interfaces are subject to change or
 72  *  deletion without notice.</b>
 73  */
 74 public class PoolWriter {
 75 
 76     /** Max number of constant pool entries. */
 77     public static final int MAX_ENTRIES = 0xFFFF;
 78 
 79     /** Max number of char in a string constant. */
 80     public static final int MAX_STRING_LENGTH = 0xFFFF;
 81 
 82     private static final int POOL_BUF_SIZE = 0x7fff;
 83 
 84     private final Types types;
 85 
 86     private final Names names;
 87 
 88     /** Pool helper **/
 89     final WriteablePoolHelper pool;
 90 
 91     /** Sole signature generator */
 92     final SharedSignatureGenerator signatureGen;
 93 
 94     /** The inner classes to be written, as an ordered set (enclosing first). */
 95     LinkedHashSet<ClassSymbol> innerClasses = new LinkedHashSet<>();
 96 
 97     /** The list of entries in the BootstrapMethods attribute. */
 98     Map<BsmKey, Integer> bootstrapMethods = new LinkedHashMap<>();
 99 
100     public PoolWriter(Types types, Names names) {
101         this.types = types;
102         this.names = names;
103         this.signatureGen = new SharedSignatureGenerator(types);
104         this.pool = new WriteablePoolHelper();
105     }
106 
107     /**
108      * Puts a class symbol into the pool and return its index.
109      */
110     int putClass(ClassSymbol csym) {
111         return putClass(csym.type);
112     }
113 
114     /**
115      * Puts a type into the pool and return its index. The type could be either a class, a type variable
116      * or an array type.
117      */
118     int putClass(Type t) {
119         /* Their is nothing to be gained by having the pair of class types Foo.ref and Foo.val
120            result in two different CONSTANT_Class_info strucures in the pool. These are
121            indistinguishable at the class file level. Hence we coalesce them here.
122         */
123         if (t.tsym.isPrimitiveClass())
124             t = t.asValueType();
125         return pool.writeIfNeeded(types.erasure(t));
126     }
127 
128     /**
129      * Puts a type into the pool and return its index. The type could be either a class, a type variable
130      * or an array type.
131      */
132     int putClass(ConstantPoolQType t) {
133         return pool.writeIfNeeded(t);
134     }
135 
136     /**
137      * Puts a member reference into the constant pool. Valid members are either field or method symbols.
138      */
139     int putMember(Symbol s) {
140         return pool.writeIfNeeded(s);
141     }
142 
143     /**
144      * Puts a dynamic reference into the constant pool and return its index.
145      */
146     int putDynamic(Dynamic d) {
147         return pool.writeIfNeeded(d);
148     }
149 
150     /**
151      * Puts a field or method descriptor into the constant pool and return its index.
152      */
153     int putDescriptor(Type t) {
154         return putName(typeSig(types.erasure(t)));
155     }
156 
157     /**
158      * Puts a field or method descriptor into the constant pool and return its index.
159      */
160     int putDescriptor(Symbol s) {
161         return putDescriptor(descriptorType(s));
162     }
163 
164     /**
165      * Puts a signature (see {@code Signature} attribute in JVMS 4.4) into the constant pool and
166      * return its index.
167      */
168     int putSignature(Symbol s) {
169         if (s.kind == TYP) {
170             return putName(classSig(s.type));
171         } else {
172             return putName(typeSig(s.type));
173         }
174     }
175 
176     /**
177      * Puts a constant value into the pool and return its index. Supported values are int, float, long,
178      * double and String.
179      */
180     int putConstant(Object o) {
181         if (o instanceof Integer intVal) {
182             return putConstant(LoadableConstant.Int(intVal));
183         } else if (o instanceof Float floatVal) {
184             return putConstant(LoadableConstant.Float(floatVal));
185         } else if (o instanceof Long longVal) {
186             return putConstant(LoadableConstant.Long(longVal));
187         } else if (o instanceof Double doubleVal) {
188             return putConstant(LoadableConstant.Double(doubleVal));
189         } else if (o instanceof String strVal) {
190             return putConstant(LoadableConstant.String(strVal));
191         } else {
192             throw new AssertionError("unexpected constant: " + o);
193         }
194     }
195 
196     /**
197      * Puts a constant into the pool and return its index.
198      */
199     int putConstant(LoadableConstant c) {
200         switch (c.poolTag()) {
201             case CONSTANT_Class:
202                 return putClass((Type)c);
203             case CONSTANT_MethodType:
204                 return pool.writeIfNeeded(types.erasure((Type)c));
205             default:
206                 return pool.writeIfNeeded(c);
207         }
208     }
209 
210     int putName(Name name) {
211         return pool.writeIfNeeded(name);
212     }
213 
214     /**
215      * Puts a name and type pair into the pool and returns its index.
216      */
217     int putNameAndType(Symbol s) {
218         return pool.writeIfNeeded(new NameAndType(s.name, descriptorType(s)));
219     }
220 
221     /**
222      * Puts a package entry into the pool and returns its index.
223      */
224     int putPackage(PackageSymbol pkg) {
225         return pool.writeIfNeeded(pkg);
226     }
227 
228     /**
229      * Puts a module entry into the pool and returns its index.
230      */
231     int putModule(ModuleSymbol mod) {
232         return pool.writeIfNeeded(mod);
233     }
234 
235     /**
236      * Enter an inner class into the `innerClasses' set.
237      */
238     void enterInner(ClassSymbol c) {
239         if (c.type.isCompound()) {
240             throw new AssertionError("Unexpected intersection type: " + c.type);
241         }
242         c.complete();
243         if (c.owner.enclClass() != null && !innerClasses.contains(c)) {
244             enterInner(c.owner.enclClass());
245             innerClasses.add(c);
246         }
247     }
248 
249     /**
250      * Create a new Utf8 entry representing a descriptor for given (member) symbol.
251      */
252     private Type descriptorType(Symbol s) {
253         return s.kind == Kind.MTH ? s.externalType(types) : s.erasure(types);
254     }
255 
256     private int makeBootstrapEntry(Dynamic dynamic) {
257         BsmKey bsmKey = dynamic.bsmKey(types);
258 
259         // Figure out the index for existing BSM; create a new BSM if no key
260         Integer index = bootstrapMethods.get(bsmKey);
261         if (index == null) {
262             index = bootstrapMethods.size();
263             bootstrapMethods.put(bsmKey, index);
264         }
265 
266         return index;
267     }
268 
269     /**
270      * Write pool contents into given byte buffer.
271      */
272     void writePool(OutputStream out) throws IOException, PoolOverflow {
273         if (pool.overflowString != null) {
274             throw new StringOverflow(pool.overflowString);
275         }
276         int size = size();
277         if (size > MAX_ENTRIES) {
278             throw new PoolOverflow();
279         }
280         out.write(size >> 8);
281         out.write(size);
282         out.write(pool.poolbuf.elems, 0, pool.poolbuf.length);
283     }
284 
285     /**
286      * Signature Generation
287      */
288     class SharedSignatureGenerator extends Types.SignatureGenerator {
289 
290         /**
291          * An output buffer for type signatures.
292          */
293         ByteBuffer sigbuf = new ByteBuffer();
294 
295         SharedSignatureGenerator(Types types) {
296             super(types);
297         }
298 
299         /**
300          * Assemble signature of given type in string buffer.
301          * Check for uninitialized types before calling the general case.
302          */
303         @Override
304         public void assembleSig(Type type) {
305             switch (type.getTag()) {
306                 case UNINITIALIZED_THIS:
307                 case UNINITIALIZED_OBJECT:
308                     // we don't yet have a spec for uninitialized types in the
309                     // local variable table
310                     assembleSig(types.erasure(((UninitializedType)type).qtype));
311                     break;
312                 default:
313                     super.assembleSig(type);
314             }
315         }
316 
317         @Override
318         protected void append(char ch) {
319             sigbuf.appendByte(ch);
320         }
321 
322         @Override
323         protected void append(byte[] ba) {
324             sigbuf.appendBytes(ba);
325         }
326 
327         @Override
328         protected void append(Name name) {
329             sigbuf.appendName(name);
330         }
331 
332         @Override
333         protected void classReference(ClassSymbol c) {
334             enterInner(c);
335         }
336 
337         protected void reset() {
338             sigbuf.reset();
339         }
340 
341         protected Name toName() {
342             return sigbuf.toName(names);
343         }
344     }
345 
346     class WriteablePoolHelper {
347 
348         /** Pool entries. */
349         private final Map<Object, Integer> keysToPos = new HashMap<>(64);
350 
351         final ByteBuffer poolbuf = new ByteBuffer(POOL_BUF_SIZE);
352 
353         int currentIndex = 1;
354 
355         ArrayDeque<PoolConstant> todo = new ArrayDeque<>();
356 
357         String overflowString = null;
358 
359         private <P extends PoolConstant> int writeIfNeeded(P p) {
360             Object key = p.poolKey(types);
361             Integer index = keysToPos.get(key);
362             if (index == null) {
363                 keysToPos.put(key, index = currentIndex++);
364                 boolean first = todo.isEmpty();
365                 todo.addLast(p);
366                 if (first) {
367                     while (!todo.isEmpty()) {
368                         writeConstant(todo.peekFirst());
369                         todo.removeFirst();
370                     }
371                 }
372             }
373             return index;
374         }
375 
376         void writeConstant(PoolConstant c) {
377             int tag = c.poolTag();
378             switch (tag) {
379                 case ClassFile.CONSTANT_Class: {
380                     Type ct = c instanceof ConstantPoolQType ? ((ConstantPoolQType)c).type : (Type)c;
381                     Name name = ct.hasTag(ARRAY) ?
382                             typeSig(ct) :
383                             c instanceof ConstantPoolQType ? names.fromString("Q" + new String(externalize(ct.tsym.flatName())) + ";") : names.fromUtf(externalize(ct.tsym.flatName()));
384                     poolbuf.appendByte(tag);
385                     poolbuf.appendChar(putName(name));
386                     if (ct.hasTag(CLASS)) {
387                         enterInner((ClassSymbol)ct.tsym);
388                     }
389                     break;
390                 }
391                 case ClassFile.CONSTANT_Utf8: {
392                     Name name = (Name)c;
393                     poolbuf.appendByte(tag);
394                     byte[] bs = name.toUtf();
395                     poolbuf.appendChar(bs.length);
396                     poolbuf.appendBytes(bs, 0, bs.length);
397                     if (overflowString == null && bs.length > MAX_STRING_LENGTH) {
398                         //report error only once
399                         overflowString = new String(bs);
400                     }
401                     break;
402                 }
403                 case ClassFile.CONSTANT_InterfaceMethodref:
404                 case ClassFile.CONSTANT_Methodref:
405                 case ClassFile.CONSTANT_Fieldref: {
406                     Symbol sym = (Symbol)c;
407                     poolbuf.appendByte(tag);
408                     poolbuf.appendChar(putClass((ClassSymbol)sym.owner));
409                     poolbuf.appendChar(putNameAndType(sym));
410                     break;
411                 }
412                 case ClassFile.CONSTANT_Package: {
413                     PackageSymbol pkg = (PackageSymbol)c;
414                     Name pkgName = names.fromUtf(externalize(pkg.flatName()));
415                     poolbuf.appendByte(tag);
416                     poolbuf.appendChar(putName(pkgName));
417                     break;
418                 }
419                 case ClassFile.CONSTANT_Module: {
420                     ModuleSymbol mod = (ModuleSymbol)c;
421                     int modName = putName(mod.name);
422                     poolbuf.appendByte(mod.poolTag());
423                     poolbuf.appendChar(modName);
424                     break;
425                 }
426                 case ClassFile.CONSTANT_Integer:
427                     poolbuf.appendByte(tag);
428                     poolbuf.appendInt((int)((BasicConstant)c).data);
429                     break;
430                 case ClassFile.CONSTANT_Float:
431                     poolbuf.appendByte(tag);
432                     poolbuf.appendFloat((float)((BasicConstant)c).data);
433                     break;
434                 case ClassFile.CONSTANT_Long:
435                     currentIndex++;
436                     poolbuf.appendByte(tag);
437                     poolbuf.appendLong((long)((BasicConstant)c).data);
438                     break;
439                 case ClassFile.CONSTANT_Double:
440                     currentIndex++;
441                     poolbuf.appendByte(tag);
442                     poolbuf.appendDouble((double)((BasicConstant)c).data);
443                     break;
444                 case ClassFile.CONSTANT_MethodHandle: {
445                     MethodHandleSymbol h = (MethodHandleSymbol)c;
446                     poolbuf.appendByte(tag);
447                     poolbuf.appendByte(h.referenceKind());
448                     poolbuf.appendChar(putMember(h.baseSymbol()));
449                     break;
450                 }
451                 case ClassFile.CONSTANT_MethodType: {
452                     Type.MethodType mt = (Type.MethodType)c;
453                     poolbuf.appendByte(tag);
454                     poolbuf.appendChar(putDescriptor(mt.baseType()));
455                     break;
456                 }
457                 case ClassFile.CONSTANT_String: {
458                     Name utf = names.fromString((String)((BasicConstant)c).data);
459                     poolbuf.appendByte(tag);
460                     poolbuf.appendChar(putName(utf));
461                     break;
462                 }
463                 case ClassFile.CONSTANT_NameandType: {
464                     NameAndType nt = (NameAndType)c;
465                     poolbuf.appendByte(tag);
466                     poolbuf.appendChar(putName(nt.name));
467                     poolbuf.appendChar(putDescriptor(nt.type));
468                     break;
469                 }
470                 case ClassFile.CONSTANT_InvokeDynamic: {
471                     DynamicMethodSymbol d = (DynamicMethodSymbol)c;
472                     poolbuf.appendByte(tag);
473                     poolbuf.appendChar(makeBootstrapEntry(d));
474                     poolbuf.appendChar(putNameAndType(d));
475                     break;
476                 }
477                 case ClassFile.CONSTANT_Dynamic: {
478                     Symbol.DynamicVarSymbol d = (Symbol.DynamicVarSymbol)c;
479                     poolbuf.appendByte(tag);
480                     poolbuf.appendChar(makeBootstrapEntry(d));
481                     poolbuf.appendChar(putNameAndType(d));
482                     break;
483                 }
484                 default:
485                     throw new AssertionError("Unexpected constant tag: " + tag);
486             }
487         }
488 
489         void reset() {
490             keysToPos.clear();
491             currentIndex = 1;
492             todo.clear();
493             overflowString = null;
494             poolbuf.reset();
495         }
496     }
497 
498     int size() {
499         return pool.currentIndex;
500     }
501 
502     /**
503      * Return signature of given type
504      */
505     private Name typeSig(Type type) {
506         signatureGen.reset();
507         signatureGen.assembleSig(type);
508         return signatureGen.toName();
509     }
510 
511     private Name classSig(Type t) {
512         signatureGen.reset();
513         List<Type> typarams = t.getTypeArguments();
514         if (typarams.nonEmpty()) {
515             signatureGen.assembleParamsSig(typarams);
516         }
517         signatureGen.assembleSig(types.supertype(t));
518         for (Type i : types.interfaces(t))
519             signatureGen.assembleSig(i);
520 
521         return signatureGen.toName();
522     }
523 
524     void reset() {
525         innerClasses.clear();
526         bootstrapMethods.clear();
527         pool.reset();
528     }
529 }