1 /*
   2  * Copyright (c) 2008, 2020, 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 
  27 package com.sun.tools.classfile;
  28 
  29 import java.io.ByteArrayOutputStream;
  30 import java.io.DataOutputStream;
  31 import java.io.File;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.OutputStream;
  35 
  36 import static com.sun.tools.classfile.Annotation.*;
  37 import static com.sun.tools.classfile.ConstantPool.*;
  38 import static com.sun.tools.classfile.StackMapTable_attribute.*;
  39 import static com.sun.tools.classfile.StackMapTable_attribute.verification_type_info.*;
  40 
  41 /**
  42  * Write a ClassFile data structure to a file or stream.
  43  *
  44  *  <p><b>This is NOT part of any supported API.
  45  *  If you write code that depends on this, you do so at your own risk.
  46  *  This code and its internal interfaces are subject to change or
  47  *  deletion without notice.</b>
  48  */
  49 public class ClassWriter {
  50     public ClassWriter() {
  51         attributeWriter = new AttributeWriter();
  52         constantPoolWriter = new ConstantPoolWriter();
  53         out = new ClassOutputStream();
  54     }
  55 
  56     /**
  57      * Write a ClassFile data structure to a file.
  58      * @param classFile the classfile object to be written
  59      * @param f the file
  60      * @throws IOException if an error occurs while writing the file
  61      */
  62     public void write(ClassFile classFile, File f) throws IOException {
  63         try (FileOutputStream f_out = new FileOutputStream(f)) {
  64             write(classFile, f_out);
  65         }
  66     }
  67 
  68     /**
  69      * Write a ClassFile data structure to a stream.
  70      * @param classFile the classfile object to be written
  71      * @param s the stream
  72      * @throws IOException if an error occurs while writing the file
  73      */
  74     public void write(ClassFile classFile, OutputStream s) throws IOException {
  75         this.classFile = classFile;
  76         out.reset();
  77         write();
  78         out.writeTo(s);
  79     }
  80 
  81     protected void write() throws IOException {
  82         writeHeader();
  83         writeConstantPool();
  84         writeAccessFlags(classFile.access_flags);
  85         writeClassInfo();
  86         writeFields();
  87         writeMethods();
  88         writeAttributes(classFile.attributes);
  89     }
  90 
  91     protected void writeHeader() {
  92         out.writeInt(classFile.magic);
  93         out.writeShort(classFile.minor_version);
  94         out.writeShort(classFile.major_version);
  95     }
  96 
  97     protected void writeAccessFlags(AccessFlags flags) {
  98         out.writeShort(flags.flags);
  99     }
 100 
 101     protected void writeAttributes(Attributes attributes) {
 102         int size = attributes.size();
 103         out.writeShort(size);
 104         for (Attribute attr: attributes)
 105             attributeWriter.write(attr, out);
 106     }
 107 
 108     protected void writeClassInfo() {
 109         out.writeShort(classFile.this_class);
 110         out.writeShort(classFile.super_class);
 111         int[] interfaces = classFile.interfaces;
 112         out.writeShort(interfaces.length);
 113         for (int i: interfaces)
 114             out.writeShort(i);
 115     }
 116 
 117     protected void writeDescriptor(Descriptor d) {
 118         out.writeShort(d.index);
 119     }
 120 
 121     protected void writeConstantPool() {
 122         ConstantPool pool = classFile.constant_pool;
 123         int size = pool.size();
 124         out.writeShort(size);
 125         for (CPInfo cpInfo: pool.entries())
 126             constantPoolWriter.write(cpInfo, out);
 127     }
 128 
 129     protected void writeFields() throws IOException {
 130         Field[] fields = classFile.fields;
 131         out.writeShort(fields.length);
 132         for (Field f: fields)
 133             writeField(f);
 134     }
 135 
 136     protected void writeField(Field f) throws IOException {
 137         writeAccessFlags(f.access_flags);
 138         out.writeShort(f.name_index);
 139         writeDescriptor(f.descriptor);
 140         writeAttributes(f.attributes);
 141     }
 142 
 143     protected void writeMethods() throws IOException {
 144         Method[] methods = classFile.methods;
 145         out.writeShort(methods.length);
 146         for (Method m: methods) {
 147             writeMethod(m);
 148         }
 149     }
 150 
 151     protected void writeMethod(Method m) throws IOException {
 152         writeAccessFlags(m.access_flags);
 153         out.writeShort(m.name_index);
 154         writeDescriptor(m.descriptor);
 155         writeAttributes(m.attributes);
 156     }
 157 
 158     protected ClassFile classFile;
 159     protected ClassOutputStream out;
 160     protected AttributeWriter attributeWriter;
 161     protected ConstantPoolWriter constantPoolWriter;
 162 
 163     /**
 164      * Subtype of ByteArrayOutputStream with the convenience methods of
 165      * a DataOutputStream. Since ByteArrayOutputStream does not throw
 166      * IOException, there are no exceptions from the additional
 167      * convenience methods either,
 168      */
 169     protected static class ClassOutputStream extends ByteArrayOutputStream {
 170         public ClassOutputStream() {
 171             d = new DataOutputStream(this);
 172         }
 173 
 174         public void writeByte(int value) {
 175             try {
 176                 d.writeByte(value);
 177             } catch (IOException ignore) {
 178             }
 179         }
 180 
 181         public void writeShort(int value) {
 182             try {
 183                 d.writeShort(value);
 184             } catch (IOException ignore) {
 185             }
 186         }
 187 
 188         public void writeInt(int value) {
 189             try {
 190                 d.writeInt(value);
 191             } catch (IOException ignore) {
 192             }
 193         }
 194 
 195         public void writeLong(long value) {
 196             try {
 197                 d.writeLong(value);
 198             } catch (IOException ignore) {
 199             }
 200         }
 201 
 202         public void writeFloat(float value) {
 203             try {
 204                 d.writeFloat(value);
 205             } catch (IOException ignore) {
 206             }
 207         }
 208 
 209         public void writeDouble(double value) {
 210             try {
 211                 d.writeDouble(value);
 212             } catch (IOException ignore) {
 213             }
 214         }
 215 
 216         public void writeUTF(String value) {
 217             try {
 218                 d.writeUTF(value);
 219             } catch (IOException ignore) {
 220             }
 221         }
 222 
 223         public void writeTo(ClassOutputStream s) {
 224             try {
 225                 super.writeTo(s);
 226             } catch (IOException ignore) {
 227             }
 228         }
 229 
 230         private final DataOutputStream d;
 231     }
 232 
 233     /**
 234      * Writer for the entries in the constant pool.
 235      */
 236     protected static class ConstantPoolWriter
 237            implements ConstantPool.Visitor<Integer,ClassOutputStream> {
 238         protected int write(CPInfo info, ClassOutputStream out) {
 239             out.writeByte(info.getTag());
 240             return info.accept(this, out);
 241         }
 242 
 243         @Override
 244         public Integer visitClass(CONSTANT_Class_info info, ClassOutputStream out) {
 245             out.writeShort(info.name_index);
 246             return 1;
 247         }
 248 
 249         @Override
 250         public Integer visitDouble(CONSTANT_Double_info info, ClassOutputStream out) {
 251             out.writeDouble(info.value);
 252             return 2;
 253         }
 254 
 255         @Override
 256         public Integer visitFieldref(CONSTANT_Fieldref_info info, ClassOutputStream out) {
 257             writeRef(info, out);
 258             return 1;
 259         }
 260 
 261         @Override
 262         public Integer visitFloat(CONSTANT_Float_info info, ClassOutputStream out) {
 263             out.writeFloat(info.value);
 264             return 1;
 265         }
 266 
 267         @Override
 268         public Integer visitInteger(CONSTANT_Integer_info info, ClassOutputStream out) {
 269             out.writeInt(info.value);
 270             return 1;
 271         }
 272 
 273         @Override
 274         public Integer visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, ClassOutputStream out) {
 275             writeRef(info, out);
 276             return 1;
 277         }
 278 
 279         @Override
 280         public Integer visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, ClassOutputStream out) {
 281             out.writeShort(info.bootstrap_method_attr_index);
 282             out.writeShort(info.name_and_type_index);
 283             return 1;
 284         }
 285 
 286         public Integer visitDynamicConstant(CONSTANT_Dynamic_info info, ClassOutputStream out) {
 287             out.writeShort(info.bootstrap_method_attr_index);
 288             out.writeShort(info.name_and_type_index);
 289             return 1;
 290         }
 291 
 292         @Override
 293         public Integer visitLong(CONSTANT_Long_info info, ClassOutputStream out) {
 294             out.writeLong(info.value);
 295             return 2;
 296         }
 297 
 298         @Override
 299         public Integer visitMethodHandle(CONSTANT_MethodHandle_info info, ClassOutputStream out) {
 300             out.writeByte(info.reference_kind.tag);
 301             out.writeShort(info.reference_index);
 302             return 1;
 303         }
 304 
 305         @Override
 306         public Integer visitMethodType(CONSTANT_MethodType_info info, ClassOutputStream out) {
 307             out.writeShort(info.descriptor_index);
 308             return 1;
 309         }
 310 
 311         @Override
 312         public Integer visitMethodref(CONSTANT_Methodref_info info, ClassOutputStream out) {
 313             return writeRef(info, out);
 314         }
 315 
 316         @Override
 317         public Integer visitModule(CONSTANT_Module_info info, ClassOutputStream out) {
 318             out.writeShort(info.name_index);
 319             return 1;
 320         }
 321 
 322         @Override
 323         public Integer visitNameAndType(CONSTANT_NameAndType_info info, ClassOutputStream out) {
 324             out.writeShort(info.name_index);
 325             out.writeShort(info.type_index);
 326             return 1;
 327         }
 328 
 329         @Override
 330         public Integer visitPackage(CONSTANT_Package_info info, ClassOutputStream out) {
 331             out.writeShort(info.name_index);
 332             return 1;
 333         }
 334 
 335         @Override
 336         public Integer visitString(CONSTANT_String_info info, ClassOutputStream out) {
 337             out.writeShort(info.string_index);
 338             return 1;
 339         }
 340 
 341         @Override
 342         public Integer visitUtf8(CONSTANT_Utf8_info info, ClassOutputStream out) {
 343             out.writeUTF(info.value);
 344             return 1;
 345         }
 346 
 347         protected Integer writeRef(CPRefInfo info, ClassOutputStream out) {
 348             out.writeShort(info.class_index);
 349             out.writeShort(info.name_and_type_index);
 350             return 1;
 351         }
 352     }
 353 
 354     /**
 355      * Writer for the different types of attribute.
 356      */
 357     protected static class AttributeWriter implements Attribute.Visitor<Void,ClassOutputStream> {
 358         public void write(Attributes attributes, ClassOutputStream out) {
 359             int size = attributes.size();
 360             out.writeShort(size);
 361             for (Attribute a: attributes)
 362                 write(a, out);
 363         }
 364 
 365         public void write(Attribute attr, ClassOutputStream out) {
 366             out.writeShort(attr.attribute_name_index);
 367             ClassOutputStream nestedOut = new ClassOutputStream();
 368             attr.accept(this, nestedOut);
 369             out.writeInt(nestedOut.size());
 370             nestedOut.writeTo(out);
 371         }
 372 
 373         protected AnnotationWriter annotationWriter = new AnnotationWriter();
 374 
 375         @Override
 376         public Void visitDefault(DefaultAttribute attr, ClassOutputStream out) {
 377             out.write(attr.info, 0, attr.info.length);
 378             return null;
 379         }
 380 
 381         @Override
 382         public Void visitAnnotationDefault(AnnotationDefault_attribute attr, ClassOutputStream out) {
 383             annotationWriter.write(attr.default_value, out);
 384             return null;
 385         }
 386 
 387         @Override
 388         public Void visitBootstrapMethods(BootstrapMethods_attribute attr, ClassOutputStream out) {
 389             out.writeShort(attr.bootstrap_method_specifiers.length);
 390             for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsm : attr.bootstrap_method_specifiers) {
 391                 out.writeShort(bsm.bootstrap_method_ref);
 392                 int bsm_args_count = bsm.bootstrap_arguments.length;
 393                 out.writeShort(bsm_args_count);
 394                 for (int i : bsm.bootstrap_arguments) {
 395                     out.writeShort(i);
 396                 }
 397             }
 398             return null;
 399         }
 400 
 401         @Override
 402         public Void visitCharacterRangeTable(CharacterRangeTable_attribute attr, ClassOutputStream out) {
 403             out.writeShort(attr.character_range_table.length);
 404             for (CharacterRangeTable_attribute.Entry e: attr.character_range_table)
 405                 writeCharacterRangeTableEntry(e, out);
 406             return null;
 407         }
 408 
 409         protected void writeCharacterRangeTableEntry(CharacterRangeTable_attribute.Entry entry, ClassOutputStream out) {
 410             out.writeShort(entry.start_pc);
 411             out.writeShort(entry.end_pc);
 412             out.writeInt(entry.character_range_start);
 413             out.writeInt(entry.character_range_end);
 414             out.writeShort(entry.flags);
 415         }
 416 
 417         @Override
 418         public Void visitCode(Code_attribute attr, ClassOutputStream out) {
 419             out.writeShort(attr.max_stack);
 420             out.writeShort(attr.max_locals);
 421             out.writeInt(attr.code.length);
 422             out.write(attr.code, 0, attr.code.length);
 423             out.writeShort(attr.exception_table.length);
 424             for (Code_attribute.Exception_data e: attr.exception_table)
 425                 writeExceptionTableEntry(e, out);
 426             new AttributeWriter().write(attr.attributes, out);
 427             return null;
 428         }
 429 
 430         protected void writeExceptionTableEntry(Code_attribute.Exception_data exception_data, ClassOutputStream out) {
 431             out.writeShort(exception_data.start_pc);
 432             out.writeShort(exception_data.end_pc);
 433             out.writeShort(exception_data.handler_pc);
 434             out.writeShort(exception_data.catch_type);
 435         }
 436 
 437         @Override
 438         public Void visitCompilationID(CompilationID_attribute attr, ClassOutputStream out) {
 439             out.writeShort(attr.compilationID_index);
 440             return null;
 441         }
 442 
 443         @Override
 444         public Void visitConstantValue(ConstantValue_attribute attr, ClassOutputStream out) {
 445             out.writeShort(attr.constantvalue_index);
 446             return null;
 447         }
 448 
 449         @Override
 450         public Void visitDeprecated(Deprecated_attribute attr, ClassOutputStream out) {
 451             return null;
 452         }
 453 
 454         @Override
 455         public Void visitEnclosingMethod(EnclosingMethod_attribute attr, ClassOutputStream out) {
 456             out.writeShort(attr.class_index);
 457             out.writeShort(attr.method_index);
 458             return null;
 459         }
 460 
 461         @Override
 462         public Void visitExceptions(Exceptions_attribute attr, ClassOutputStream out) {
 463             out.writeShort(attr.exception_index_table.length);
 464             for (int i: attr.exception_index_table)
 465                 out.writeShort(i);
 466             return null;
 467         }
 468 
 469         @Override
 470         public Void visitInnerClasses(InnerClasses_attribute attr, ClassOutputStream out) {
 471             out.writeShort(attr.classes.length);
 472             for (InnerClasses_attribute.Info info: attr.classes)
 473                 writeInnerClassesInfo(info, out);
 474             return null;
 475         }
 476 
 477         @Override
 478         public Void visitJavaFlags(JavaFlags_attribute attr, ClassOutputStream out) {
 479             out.writeShort(attr.extendedFlags);
 480             return null;
 481         }
 482 
 483         protected void writeInnerClassesInfo(InnerClasses_attribute.Info info, ClassOutputStream out) {
 484             out.writeShort(info.inner_class_info_index);
 485             out.writeShort(info.outer_class_info_index);
 486             out.writeShort(info.inner_name_index);
 487             writeAccessFlags(info.inner_class_access_flags, out);
 488         }
 489 
 490         @Override
 491         public Void visitLineNumberTable(LineNumberTable_attribute attr, ClassOutputStream out) {
 492             out.writeShort(attr.line_number_table.length);
 493             for (LineNumberTable_attribute.Entry e: attr.line_number_table)
 494                 writeLineNumberTableEntry(e, out);
 495             return null;
 496         }
 497 
 498         protected void writeLineNumberTableEntry(LineNumberTable_attribute.Entry entry, ClassOutputStream out) {
 499             out.writeShort(entry.start_pc);
 500             out.writeShort(entry.line_number);
 501         }
 502 
 503         @Override
 504         public Void visitLocalVariableTable(LocalVariableTable_attribute attr, ClassOutputStream out) {
 505             out.writeShort(attr.local_variable_table.length);
 506             for (LocalVariableTable_attribute.Entry e: attr.local_variable_table)
 507                 writeLocalVariableTableEntry(e, out);
 508             return null;
 509         }
 510 
 511         protected void writeLocalVariableTableEntry(LocalVariableTable_attribute.Entry entry, ClassOutputStream out) {
 512             out.writeShort(entry.start_pc);
 513             out.writeShort(entry.length);
 514             out.writeShort(entry.name_index);
 515             out.writeShort(entry.descriptor_index);
 516             out.writeShort(entry.index);
 517         }
 518 
 519         @Override
 520         public Void visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, ClassOutputStream out) {
 521             out.writeShort(attr.local_variable_table.length);
 522             for (LocalVariableTypeTable_attribute.Entry e: attr.local_variable_table)
 523                 writeLocalVariableTypeTableEntry(e, out);
 524             return null;
 525         }
 526 
 527         protected void writeLocalVariableTypeTableEntry(LocalVariableTypeTable_attribute.Entry entry, ClassOutputStream out) {
 528             out.writeShort(entry.start_pc);
 529             out.writeShort(entry.length);
 530             out.writeShort(entry.name_index);
 531             out.writeShort(entry.signature_index);
 532             out.writeShort(entry.index);
 533         }
 534 
 535         @Override
 536         public Void visitNestHost(NestHost_attribute attr, ClassOutputStream out) {
 537             out.writeShort(attr.top_index);
 538             return null;
 539         }
 540 
 541         @Override
 542         public Void visitMethodParameters(MethodParameters_attribute attr, ClassOutputStream out) {
 543             out.writeByte(attr.method_parameter_table.length);
 544             for (MethodParameters_attribute.Entry e : attr.method_parameter_table) {
 545                 out.writeShort(e.name_index);
 546                 out.writeShort(e.flags);
 547             }
 548             return null;
 549         }
 550 
 551         @Override
 552         public Void visitModule(Module_attribute attr, ClassOutputStream out) {
 553             out.writeShort(attr.module_name);
 554             out.writeShort(attr.module_flags);
 555             out.writeShort(attr.module_version_index);
 556 
 557             out.writeShort(attr.requires.length);
 558             for (Module_attribute.RequiresEntry e: attr.requires) {
 559                 out.writeShort(e.requires_index);
 560                 out.writeShort(e.requires_flags);
 561                 out.writeShort(e.requires_version_index);
 562             }
 563 
 564             out.writeShort(attr.exports.length);
 565             for (Module_attribute.ExportsEntry e: attr.exports) {
 566                 out.writeShort(e.exports_index);
 567                 out.writeShort(e.exports_flags);
 568                 out.writeShort(e.exports_to_index.length);
 569                 for (int index: e.exports_to_index)
 570                     out.writeShort(index);
 571             }
 572 
 573             out.writeShort(attr.opens.length);
 574             for (Module_attribute.OpensEntry e: attr.opens) {
 575                 out.writeShort(e.opens_index);
 576                 out.writeShort(e.opens_flags);
 577                 out.writeShort(e.opens_to_index.length);
 578                 for (int index: e.opens_to_index)
 579                     out.writeShort(index);
 580             }
 581 
 582             out.writeShort(attr.uses_index.length);
 583             for (int index: attr.uses_index) {
 584                 out.writeShort(index);
 585             }
 586 
 587             out.writeShort(attr.provides.length);
 588             for (Module_attribute.ProvidesEntry e: attr.provides) {
 589                 out.writeShort(e.provides_index);
 590                 out.writeShort(e.with_count);
 591                 for (int with : e.with_index) {
 592                     out.writeShort(with);
 593                 }
 594             }
 595 
 596             return null;
 597         }
 598 
 599         @Override
 600         public Void visitModuleHashes(ModuleHashes_attribute attr, ClassOutputStream out) {
 601             out.writeShort(attr.algorithm_index);
 602             out.writeShort(attr.hashes_table.length);
 603             for (ModuleHashes_attribute.Entry e: attr.hashes_table) {
 604                 out.writeShort(e.module_name_index);
 605                 out.writeShort(e.hash.length);
 606                 for (byte b: e.hash) {
 607                     out.writeByte(b);
 608                 }
 609             }
 610             return null;
 611         }
 612 
 613         @Override
 614         public Void visitModuleMainClass(ModuleMainClass_attribute attr, ClassOutputStream out) {
 615             out.writeShort(attr.main_class_index);
 616             return null;
 617         }
 618 
 619         @Override
 620         public Void visitModulePackages(ModulePackages_attribute attr, ClassOutputStream out) {
 621             out.writeShort(attr.packages_count);
 622             for (int i: attr.packages_index)
 623                 out.writeShort(i);
 624             return null;
 625         }
 626 
 627         @Override
 628         public Void visitModuleResolution(ModuleResolution_attribute attr, ClassOutputStream out) {
 629             out.writeShort(attr.resolution_flags);
 630             return null;
 631         }
 632 
 633         @Override
 634         public Void visitModuleTarget(ModuleTarget_attribute attr, ClassOutputStream out) {
 635             out.writeShort(attr.target_platform_index);
 636             return null;
 637         }
 638 
 639         @Override
 640         public Void visitNestMembers(NestMembers_attribute attr, ClassOutputStream out) {
 641             out.writeShort(attr.members_indexes.length);
 642             for (int i : attr.members_indexes) {
 643                 out.writeShort(i);
 644             }
 645             return null;
 646         }
 647 
 648         @Override
 649         public Void visitRecord(Record_attribute attr, ClassOutputStream out) {
 650             out.writeShort(attr.component_count);
 651             for (Record_attribute.ComponentInfo info: attr.component_info_arr) {
 652                 out.writeShort(info.name_index);
 653                 out.writeShort(info.descriptor.index);
 654                 int size = info.attributes.size();
 655                 out.writeShort(size);
 656                 for (Attribute componentAttr: info.attributes)
 657                     write(componentAttr, out);
 658             }
 659             return null;
 660         }
 661 
 662         @Override
 663         public Void visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, ClassOutputStream out) {
 664             annotationWriter.write(attr.annotations, out);
 665             return null;
 666         }
 667 
 668         @Override
 669         public Void visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
 670             out.writeByte(attr.parameter_annotations.length);
 671             for (Annotation[] annos: attr.parameter_annotations)
 672                 annotationWriter.write(annos, out);
 673             return null;
 674         }
 675 
 676         @Override
 677         public Void visitRuntimeInvisibleTypeAnnotations(RuntimeInvisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
 678             annotationWriter.write(attr.annotations, out);
 679             return null;
 680         }
 681 
 682         @Override
 683         public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, ClassOutputStream out) {
 684             annotationWriter.write(attr.annotations, out);
 685             return null;
 686         }
 687 
 688         @Override
 689         public Void visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
 690             out.writeByte(attr.parameter_annotations.length);
 691             for (Annotation[] annos: attr.parameter_annotations)
 692                 annotationWriter.write(annos, out);
 693             return null;
 694         }
 695 
 696         @Override
 697         public Void visitRuntimeVisibleTypeAnnotations(RuntimeVisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
 698             annotationWriter.write(attr.annotations, out);
 699             return null;
 700         }
 701 
 702         @Override
 703         public Void visitPermittedSubclasses(PermittedSubclasses_attribute attr, ClassOutputStream out) {
 704             int n = attr.subtypes.length;
 705             out.writeShort(n);
 706             for (int i = 0 ; i < n ; i++) {
 707                 out.writeShort(attr.subtypes[i]);
 708             }
 709             return null;
 710         }
 711 
 712         @Override
 713         public Void visitSignature(Signature_attribute attr, ClassOutputStream out) {
 714             out.writeShort(attr.signature_index);
 715             return null;
 716         }
 717 
 718         @Override
 719         public Void visitSourceDebugExtension(SourceDebugExtension_attribute attr, ClassOutputStream out) {
 720             out.write(attr.debug_extension, 0, attr.debug_extension.length);
 721             return null;
 722         }
 723 
 724         @Override
 725         public Void visitSourceFile(SourceFile_attribute attr, ClassOutputStream out) {
 726             out.writeShort(attr.sourcefile_index);
 727             return null;
 728         }
 729 
 730         @Override
 731         public Void visitSourceID(SourceID_attribute attr, ClassOutputStream out) {
 732             out.writeShort(attr.sourceID_index);
 733             return null;
 734         }
 735 
 736         @Override
 737         public Void visitStackMap(StackMap_attribute attr, ClassOutputStream out) {
 738             if (stackMapWriter == null)
 739                 stackMapWriter = new StackMapTableWriter();
 740 
 741             out.writeShort(attr.entries.length);
 742             for (stack_map_frame f: attr.entries)
 743                 stackMapWriter.write(f, out);
 744             return null;
 745         }
 746 
 747         @Override
 748         public Void visitStackMapTable(StackMapTable_attribute attr, ClassOutputStream out) {
 749             if (stackMapWriter == null)
 750                 stackMapWriter = new StackMapTableWriter();
 751 
 752             out.writeShort(attr.entries.length);
 753             for (stack_map_frame f: attr.entries)
 754                 stackMapWriter.write(f, out);
 755             return null;
 756         }
 757 
 758         @Override
 759         public Void visitSynthetic(Synthetic_attribute attr, ClassOutputStream out) {
 760             return null;
 761         }
 762 
 763         protected void writeAccessFlags(AccessFlags flags, ClassOutputStream out) {
 764             out.writeShort(flags.flags);
 765         }
 766 
 767         protected StackMapTableWriter stackMapWriter;
 768     }
 769 
 770     /**
 771      * Writer for the frames of StackMap and StackMapTable attributes.
 772      */
 773     protected static class StackMapTableWriter
 774             implements stack_map_frame.Visitor<Void,ClassOutputStream> {
 775 
 776         public void write(stack_map_frame frame, ClassOutputStream out) {
 777             out.write(frame.frame_type);
 778             frame.accept(this, out);
 779         }
 780 
 781         @Override
 782         public Void visit_same_frame(same_frame frame, ClassOutputStream p) {
 783             return null;
 784         }
 785 
 786         @Override
 787         public Void visit_same_locals_1_stack_item_frame(same_locals_1_stack_item_frame frame, ClassOutputStream out) {
 788             writeVerificationTypeInfo(frame.stack[0], out);
 789             return null;
 790         }
 791 
 792         @Override
 793         public Void visit_same_locals_1_stack_item_frame_extended(same_locals_1_stack_item_frame_extended frame, ClassOutputStream out) {
 794             out.writeShort(frame.offset_delta);
 795             writeVerificationTypeInfo(frame.stack[0], out);
 796             return null;
 797         }
 798 
 799         @Override
 800         public Void visit_chop_frame(chop_frame frame, ClassOutputStream out) {
 801             out.writeShort(frame.offset_delta);
 802             return null;
 803         }
 804 
 805         @Override
 806         public Void visit_same_frame_extended(same_frame_extended frame, ClassOutputStream out) {
 807             out.writeShort(frame.offset_delta);
 808             return null;
 809         }
 810 
 811         @Override
 812         public Void visit_append_frame(append_frame frame, ClassOutputStream out) {
 813             out.writeShort(frame.offset_delta);
 814             for (verification_type_info l: frame.locals)
 815                 writeVerificationTypeInfo(l, out);
 816             return null;
 817         }
 818 
 819         @Override
 820         public Void visit_full_frame(full_frame frame, ClassOutputStream out) {
 821             out.writeShort(frame.offset_delta);
 822             out.writeShort(frame.locals.length);
 823             for (verification_type_info l: frame.locals)
 824                 writeVerificationTypeInfo(l, out);
 825             out.writeShort(frame.stack.length);
 826             for (verification_type_info s: frame.stack)
 827                 writeVerificationTypeInfo(s, out);
 828             return null;
 829         }
 830 
 831         protected void writeVerificationTypeInfo(verification_type_info info,
 832                 ClassOutputStream out)  {
 833             out.write(info.tag);
 834             switch (info.tag) {
 835             case ITEM_Top:
 836             case ITEM_Integer:
 837             case ITEM_Float:
 838             case ITEM_Long:
 839             case ITEM_Double:
 840             case ITEM_Null:
 841             case ITEM_UninitializedThis:
 842                 break;
 843 
 844             case ITEM_Object:
 845                 Object_variable_info o = (Object_variable_info) info;
 846                 out.writeShort(o.cpool_index);
 847                 break;
 848 
 849             case ITEM_Uninitialized:
 850                 Uninitialized_variable_info u = (Uninitialized_variable_info) info;
 851                 out.writeShort(u.offset);
 852                 break;
 853 
 854             default:
 855                 throw new Error();
 856             }
 857         }
 858     }
 859 
 860     /**
 861      * Writer for annotations and the values they contain.
 862      */
 863     protected static class AnnotationWriter
 864             implements Annotation.element_value.Visitor<Void,ClassOutputStream> {
 865         public void write(Annotation[] annos, ClassOutputStream out) {
 866             out.writeShort(annos.length);
 867             for (Annotation anno: annos)
 868                 write(anno, out);
 869         }
 870 
 871         public void write(TypeAnnotation[] annos, ClassOutputStream out) {
 872             out.writeShort(annos.length);
 873             for (TypeAnnotation anno: annos)
 874                 write(anno, out);
 875         }
 876 
 877         public void write(Annotation anno, ClassOutputStream out) {
 878             out.writeShort(anno.type_index);
 879             out.writeShort(anno.element_value_pairs.length);
 880             for (element_value_pair p: anno.element_value_pairs)
 881                 write(p, out);
 882         }
 883 
 884         public void write(TypeAnnotation anno, ClassOutputStream out) {
 885             write(anno.position, out);
 886             write(anno.annotation, out);
 887         }
 888 
 889         public void write(element_value_pair pair, ClassOutputStream out) {
 890             out.writeShort(pair.element_name_index);
 891             write(pair.value, out);
 892         }
 893 
 894         public void write(element_value ev, ClassOutputStream out) {
 895             out.writeByte(ev.tag);
 896             ev.accept(this, out);
 897         }
 898 
 899         @Override
 900         public Void visitPrimitive(Primitive_element_value ev, ClassOutputStream out) {
 901             out.writeShort(ev.const_value_index);
 902             return null;
 903         }
 904 
 905         @Override
 906         public Void visitEnum(Enum_element_value ev, ClassOutputStream out) {
 907             out.writeShort(ev.type_name_index);
 908             out.writeShort(ev.const_name_index);
 909             return null;
 910         }
 911 
 912         @Override
 913         public Void visitClass(Class_element_value ev, ClassOutputStream out) {
 914             out.writeShort(ev.class_info_index);
 915             return null;
 916         }
 917 
 918         @Override
 919         public Void visitAnnotation(Annotation_element_value ev, ClassOutputStream out) {
 920             write(ev.annotation_value, out);
 921             return null;
 922         }
 923 
 924         @Override
 925         public Void visitArray(Array_element_value ev, ClassOutputStream out) {
 926             out.writeShort(ev.num_values);
 927             for (element_value v: ev.values)
 928                 write(v, out);
 929             return null;
 930         }
 931 
 932         // TODO: Move this to TypeAnnotation to be closer with similar logic?
 933         private void write(TypeAnnotation.Position p, ClassOutputStream out) {
 934             out.writeByte(p.type.targetTypeValue());
 935             switch (p.type) {
 936             // instanceof
 937             case INSTANCEOF:
 938             // new expression
 939             case NEW:
 940             // constructor/method reference receiver
 941             case CONSTRUCTOR_REFERENCE:
 942             case METHOD_REFERENCE:
 943                 out.writeShort(p.offset);
 944                 break;
 945             // local variable
 946             case LOCAL_VARIABLE:
 947             // resource variable
 948             case RESOURCE_VARIABLE:
 949                 int table_length = p.lvarOffset.length;
 950                 out.writeShort(table_length);
 951                 for (int i = 0; i < table_length; ++i) {
 952                     out.writeShort(1);  // for table length
 953                     out.writeShort(p.lvarOffset[i]);
 954                     out.writeShort(p.lvarLength[i]);
 955                     out.writeShort(p.lvarIndex[i]);
 956                 }
 957                 break;
 958             // exception parameter
 959             case EXCEPTION_PARAMETER:
 960                 out.writeShort(p.exception_index);
 961                 break;
 962             // method receiver
 963             case METHOD_RECEIVER:
 964                 // Do nothing
 965                 break;
 966             // type parameters
 967             case CLASS_TYPE_PARAMETER:
 968             case METHOD_TYPE_PARAMETER:
 969                 out.writeByte(p.parameter_index);
 970                 break;
 971             // type parameters bounds
 972             case CLASS_TYPE_PARAMETER_BOUND:
 973             case METHOD_TYPE_PARAMETER_BOUND:
 974                 out.writeByte(p.parameter_index);
 975                 out.writeByte(p.bound_index);
 976                 break;
 977             // class extends or implements clause
 978             case CLASS_EXTENDS:
 979                 out.writeShort(p.type_index);
 980                 break;
 981             // throws
 982             case THROWS:
 983                 out.writeShort(p.type_index);
 984                 break;
 985             // method parameter
 986             case METHOD_FORMAL_PARAMETER:
 987                 out.writeByte(p.parameter_index);
 988                 break;
 989             // type cast
 990             case CAST:
 991             // method/constructor/reference type argument
 992             case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
 993             case METHOD_INVOCATION_TYPE_ARGUMENT:
 994             case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
 995             case METHOD_REFERENCE_TYPE_ARGUMENT:
 996                 out.writeShort(p.offset);
 997                 out.writeByte(p.type_index);
 998                 break;
 999             // We don't need to worry about these
1000             case METHOD_RETURN:
1001             case FIELD:
1002                 break;
1003             case UNKNOWN:
1004                 throw new AssertionError("ClassWriter: UNKNOWN target type should never occur!");
1005             default:
1006                 throw new AssertionError("ClassWriter: Unknown target type for position: " + p);
1007             }
1008 
1009             { // Append location data for generics/arrays.
1010                 // TODO: check for overrun?
1011                 out.writeByte((byte)p.location.size());
1012                 for (int i : TypeAnnotation.Position.getBinaryFromTypePath(p.location))
1013                     out.writeByte((byte)i);
1014             }
1015         }
1016     }
1017 }