1 /*
   2  * Copyright (c) 2008, 2016, 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         @Override
 287         public Integer visitLong(CONSTANT_Long_info info, ClassOutputStream out) {
 288             out.writeLong(info.value);
 289             return 2;
 290         }
 291 
 292         @Override
 293         public Integer visitNameAndType(CONSTANT_NameAndType_info info, ClassOutputStream out) {
 294             out.writeShort(info.name_index);
 295             out.writeShort(info.type_index);
 296             return 1;
 297         }
 298 
 299         @Override
 300         public Integer visitMethodHandle(CONSTANT_MethodHandle_info info, ClassOutputStream out) {
 301             out.writeByte(info.reference_kind.tag);
 302             out.writeShort(info.reference_index);
 303             return 1;
 304         }
 305 
 306         @Override
 307         public Integer visitMethodType(CONSTANT_MethodType_info info, ClassOutputStream out) {
 308             out.writeShort(info.descriptor_index);
 309             return 1;
 310         }
 311 
 312         @Override
 313         public Integer visitMethodref(CONSTANT_Methodref_info info, ClassOutputStream out) {
 314             return writeRef(info, out);
 315         }
 316 
 317         @Override
 318         public Integer visitString(CONSTANT_String_info info, ClassOutputStream out) {
 319             out.writeShort(info.string_index);
 320             return 1;
 321         }
 322 
 323         @Override
 324         public Integer visitUtf8(CONSTANT_Utf8_info info, ClassOutputStream out) {
 325             out.writeUTF(info.value);
 326             return 1;
 327         }
 328 
 329         protected Integer writeRef(CPRefInfo info, ClassOutputStream out) {
 330             out.writeShort(info.class_index);
 331             out.writeShort(info.name_and_type_index);
 332             return 1;
 333         }
 334     }
 335 
 336     /**
 337      * Writer for the different types of attribute.
 338      */
 339     protected static class AttributeWriter implements Attribute.Visitor<Void,ClassOutputStream> {
 340         public void write(Attributes attributes, ClassOutputStream out) {
 341             int size = attributes.size();
 342             out.writeShort(size);
 343             for (Attribute a: attributes)
 344                 write(a, out);
 345         }
 346 
 347         // Note: due to the use of shared resources, this method is not reentrant.
 348         public void write(Attribute attr, ClassOutputStream out) {
 349             out.writeShort(attr.attribute_name_index);
 350             sharedOut.reset();
 351             attr.accept(this, sharedOut);
 352             out.writeInt(sharedOut.size());
 353             sharedOut.writeTo(out);
 354         }
 355 
 356         protected ClassOutputStream sharedOut = new ClassOutputStream();
 357         protected AnnotationWriter annotationWriter = new AnnotationWriter();
 358 
 359         @Override
 360         public Void visitDefault(DefaultAttribute attr, ClassOutputStream out) {
 361             out.write(attr.info, 0, attr.info.length);
 362             return null;
 363         }
 364 
 365         @Override
 366         public Void visitAnnotationDefault(AnnotationDefault_attribute attr, ClassOutputStream out) {
 367             annotationWriter.write(attr.default_value, out);
 368             return null;
 369         }
 370 
 371         @Override
 372         public Void visitBootstrapMethods(BootstrapMethods_attribute attr, ClassOutputStream out) {
 373             out.writeShort(attr.bootstrap_method_specifiers.length);
 374             for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsm : attr.bootstrap_method_specifiers) {
 375                 out.writeShort(bsm.bootstrap_method_ref);
 376                 int bsm_args_count = bsm.bootstrap_arguments.length;
 377                 out.writeShort(bsm_args_count);
 378                 for (int i : bsm.bootstrap_arguments) {
 379                     out.writeShort(i);
 380                 }
 381             }
 382             return null;
 383         }
 384 
 385         @Override
 386         public Void visitCharacterRangeTable(CharacterRangeTable_attribute attr, ClassOutputStream out) {
 387             out.writeShort(attr.character_range_table.length);
 388             for (CharacterRangeTable_attribute.Entry e: attr.character_range_table)
 389                 writeCharacterRangeTableEntry(e, out);
 390             return null;
 391         }
 392 
 393         protected void writeCharacterRangeTableEntry(CharacterRangeTable_attribute.Entry entry, ClassOutputStream out) {
 394             out.writeShort(entry.start_pc);
 395             out.writeShort(entry.end_pc);
 396             out.writeInt(entry.character_range_start);
 397             out.writeInt(entry.character_range_end);
 398             out.writeShort(entry.flags);
 399         }
 400 
 401         @Override
 402         public Void visitCode(Code_attribute attr, ClassOutputStream out) {
 403             out.writeShort(attr.max_stack);
 404             out.writeShort(attr.max_locals);
 405             out.writeInt(attr.code.length);
 406             out.write(attr.code, 0, attr.code.length);
 407             out.writeShort(attr.exception_table.length);
 408             for (Code_attribute.Exception_data e: attr.exception_table)
 409                 writeExceptionTableEntry(e, out);
 410             new AttributeWriter().write(attr.attributes, out);
 411             return null;
 412         }
 413 
 414         protected void writeExceptionTableEntry(Code_attribute.Exception_data exception_data, ClassOutputStream out) {
 415             out.writeShort(exception_data.start_pc);
 416             out.writeShort(exception_data.end_pc);
 417             out.writeShort(exception_data.handler_pc);
 418             out.writeShort(exception_data.catch_type);
 419         }
 420 
 421         @Override
 422         public Void visitCompilationID(CompilationID_attribute attr, ClassOutputStream out) {
 423             out.writeShort(attr.compilationID_index);
 424             return null;
 425         }
 426 
 427         @Override
 428         public Void visitModulePackages(ModulePackages_attribute attr, ClassOutputStream out) {
 429             out.writeShort(attr.packages_count);
 430             for (int i: attr.packages_index)
 431                 out.writeShort(i);
 432             return null;
 433         }
 434 
 435         @Override
 436         public Void visitConstantValue(ConstantValue_attribute attr, ClassOutputStream out) {
 437             out.writeShort(attr.constantvalue_index);
 438             return null;
 439         }
 440 
 441         @Override
 442         public Void visitDeprecated(Deprecated_attribute attr, ClassOutputStream out) {
 443             return null;
 444         }
 445 
 446         @Override
 447         public Void visitEnclosingMethod(EnclosingMethod_attribute attr, ClassOutputStream out) {
 448             out.writeShort(attr.class_index);
 449             out.writeShort(attr.method_index);
 450             return null;
 451         }
 452 
 453         @Override
 454         public Void visitExceptions(Exceptions_attribute attr, ClassOutputStream out) {
 455             out.writeShort(attr.exception_index_table.length);
 456             for (int i: attr.exception_index_table)
 457                 out.writeShort(i);
 458             return null;
 459         }
 460 
 461         @Override
 462         public Void visitInnerClasses(InnerClasses_attribute attr, ClassOutputStream out) {
 463             out.writeShort(attr.classes.length);
 464             for (InnerClasses_attribute.Info info: attr.classes)
 465                 writeInnerClassesInfo(info, out);
 466             return null;
 467         }
 468 
 469         @Override
 470         public Void visitModuleHashes(ModuleHashes_attribute attr, ClassOutputStream out) {
 471             out.writeShort(attr.algorithm_index);
 472             out.writeShort(attr.hashes_table.length);
 473             for (ModuleHashes_attribute.Entry e: attr.hashes_table) {
 474                 out.writeShort(e.module_name_index);
 475                 out.writeShort(e.hash.length);
 476                 for (byte b: e.hash) {
 477                     out.writeByte(b);
 478                 }
 479             }
 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 visitMethodParameters(MethodParameters_attribute attr, ClassOutputStream out) {
 537             out.writeByte(attr.method_parameter_table.length);
 538             for (MethodParameters_attribute.Entry e : attr.method_parameter_table) {
 539                 out.writeShort(e.name_index);
 540                 out.writeShort(e.flags);
 541             }
 542             return null;
 543         }
 544 
 545         @Override
 546         public Void visitModuleMainClass(ModuleMainClass_attribute attr, ClassOutputStream out) {
 547             out.writeShort(attr.main_class_index);
 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 
 556             out.writeShort(attr.requires.length);
 557             for (Module_attribute.RequiresEntry e: attr.requires) {
 558                 out.writeShort(e.requires_index);
 559                 out.writeShort(e.requires_flags);
 560             }
 561 
 562             out.writeShort(attr.exports.length);
 563             for (Module_attribute.ExportsEntry e: attr.exports) {
 564                 out.writeShort(e.exports_index);
 565                 out.writeShort(e.exports_flags);
 566                 out.writeShort(e.exports_to_index.length);
 567                 for (int index: e.exports_to_index)
 568                     out.writeShort(index);
 569             }
 570 
 571             out.writeShort(attr.opens.length);
 572             for (Module_attribute.OpensEntry e: attr.opens) {
 573                 out.writeShort(e.opens_index);
 574                 out.writeShort(e.opens_flags);
 575                 out.writeShort(e.opens_to_index.length);
 576                 for (int index: e.opens_to_index)
 577                     out.writeShort(index);
 578             }
 579 
 580             out.writeShort(attr.uses_index.length);
 581             for (int index: attr.uses_index) {
 582                 out.writeShort(index);
 583             }
 584 
 585             out.writeShort(attr.provides.length);
 586             for (Module_attribute.ProvidesEntry e: attr.provides) {
 587                 out.writeShort(e.provides_index);
 588                 out.writeShort(e.with_count);
 589                 for (int with : e.with_index) {
 590                     out.writeShort(with);
 591                 }
 592             }
 593 
 594             return null;
 595         }
 596 
 597         @Override
 598         public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, ClassOutputStream out) {
 599             annotationWriter.write(attr.annotations, out);
 600             return null;
 601         }
 602 
 603         @Override
 604         public Void visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, ClassOutputStream out) {
 605             annotationWriter.write(attr.annotations, out);
 606             return null;
 607         }
 608 
 609         @Override
 610         public Void visitRuntimeVisibleTypeAnnotations(RuntimeVisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
 611             annotationWriter.write(attr.annotations, out);
 612             return null;
 613         }
 614 
 615         @Override
 616         public Void visitRuntimeInvisibleTypeAnnotations(RuntimeInvisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
 617             annotationWriter.write(attr.annotations, out);
 618             return null;
 619         }
 620 
 621         @Override
 622         public Void visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
 623             out.writeByte(attr.parameter_annotations.length);
 624             for (Annotation[] annos: attr.parameter_annotations)
 625                 annotationWriter.write(annos, out);
 626             return null;
 627         }
 628 
 629         @Override
 630         public Void visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
 631             out.writeByte(attr.parameter_annotations.length);
 632             for (Annotation[] annos: attr.parameter_annotations)
 633                 annotationWriter.write(annos, out);
 634             return null;
 635         }
 636 
 637         @Override
 638         public Void visitSignature(Signature_attribute attr, ClassOutputStream out) {
 639             out.writeShort(attr.signature_index);
 640             return null;
 641         }
 642 
 643         @Override
 644         public Void visitSourceDebugExtension(SourceDebugExtension_attribute attr, ClassOutputStream out) {
 645             out.write(attr.debug_extension, 0, attr.debug_extension.length);
 646             return null;
 647         }
 648 
 649         @Override
 650         public Void visitSourceFile(SourceFile_attribute attr, ClassOutputStream out) {
 651             out.writeShort(attr.sourcefile_index);
 652             return null;
 653         }
 654 
 655         @Override
 656         public Void visitSourceID(SourceID_attribute attr, ClassOutputStream out) {
 657             out.writeShort(attr.sourceID_index);
 658             return null;
 659         }
 660 
 661         @Override
 662         public Void visitStackMap(StackMap_attribute attr, ClassOutputStream out) {
 663             if (stackMapWriter == null)
 664                 stackMapWriter = new StackMapTableWriter();
 665 
 666             out.writeShort(attr.entries.length);
 667             for (stack_map_frame f: attr.entries)
 668                 stackMapWriter.write(f, out);
 669             return null;
 670         }
 671 
 672         @Override
 673         public Void visitStackMapTable(StackMapTable_attribute attr, ClassOutputStream out) {
 674             if (stackMapWriter == null)
 675                 stackMapWriter = new StackMapTableWriter();
 676 
 677             out.writeShort(attr.entries.length);
 678             for (stack_map_frame f: attr.entries)
 679                 stackMapWriter.write(f, out);
 680             return null;
 681         }
 682 
 683         @Override
 684         public Void visitSynthetic(Synthetic_attribute attr, ClassOutputStream out) {
 685             return null;
 686         }
 687 
 688         @Override
 689         public Void visitModuleTarget(ModuleTarget_attribute attr, ClassOutputStream out) {
 690             out.writeShort(attr.os_name_index);
 691             out.writeShort(attr.os_arch_index);
 692             out.writeShort(attr.os_version_index);
 693             return null;
 694         }
 695 
 696         protected void writeAccessFlags(AccessFlags flags, ClassOutputStream p) {
 697             sharedOut.writeShort(flags.flags);
 698         }
 699 
 700         @Override
 701         public Void visitModuleVersion(ModuleVersion_attribute attr, ClassOutputStream out) {
 702             out.writeShort(attr.version_index);
 703             return null;
 704         }
 705 
 706         protected StackMapTableWriter stackMapWriter;
 707     }
 708 
 709     /**
 710      * Writer for the frames of StackMap and StackMapTable attributes.
 711      */
 712     protected static class StackMapTableWriter
 713             implements stack_map_frame.Visitor<Void,ClassOutputStream> {
 714 
 715         public void write(stack_map_frame frame, ClassOutputStream out) {
 716             out.write(frame.frame_type);
 717             frame.accept(this, out);
 718         }
 719 
 720         @Override
 721         public Void visit_same_frame(same_frame frame, ClassOutputStream p) {
 722             return null;
 723         }
 724 
 725         @Override
 726         public Void visit_same_locals_1_stack_item_frame(same_locals_1_stack_item_frame frame, ClassOutputStream out) {
 727             writeVerificationTypeInfo(frame.stack[0], out);
 728             return null;
 729         }
 730 
 731         @Override
 732         public Void visit_same_locals_1_stack_item_frame_extended(same_locals_1_stack_item_frame_extended frame, ClassOutputStream out) {
 733             out.writeShort(frame.offset_delta);
 734             writeVerificationTypeInfo(frame.stack[0], out);
 735             return null;
 736         }
 737 
 738         @Override
 739         public Void visit_chop_frame(chop_frame frame, ClassOutputStream out) {
 740             out.writeShort(frame.offset_delta);
 741             return null;
 742         }
 743 
 744         @Override
 745         public Void visit_same_frame_extended(same_frame_extended frame, ClassOutputStream out) {
 746             out.writeShort(frame.offset_delta);
 747             return null;
 748         }
 749 
 750         @Override
 751         public Void visit_append_frame(append_frame frame, ClassOutputStream out) {
 752             out.writeShort(frame.offset_delta);
 753             for (verification_type_info l: frame.locals)
 754                 writeVerificationTypeInfo(l, out);
 755             return null;
 756         }
 757 
 758         @Override
 759         public Void visit_full_frame(full_frame frame, ClassOutputStream out) {
 760             out.writeShort(frame.offset_delta);
 761             out.writeShort(frame.locals.length);
 762             for (verification_type_info l: frame.locals)
 763                 writeVerificationTypeInfo(l, out);
 764             out.writeShort(frame.stack.length);
 765             for (verification_type_info s: frame.stack)
 766                 writeVerificationTypeInfo(s, out);
 767             return null;
 768         }
 769 
 770         protected void writeVerificationTypeInfo(verification_type_info info,
 771                 ClassOutputStream out)  {
 772             out.write(info.tag);
 773             switch (info.tag) {
 774             case ITEM_Top:
 775             case ITEM_Integer:
 776             case ITEM_Float:
 777             case ITEM_Long:
 778             case ITEM_Double:
 779             case ITEM_Null:
 780             case ITEM_UninitializedThis:
 781                 break;
 782 
 783             case ITEM_Object:
 784                 Object_variable_info o = (Object_variable_info) info;
 785                 out.writeShort(o.cpool_index);
 786                 break;
 787 
 788             case ITEM_Uninitialized:
 789                 Uninitialized_variable_info u = (Uninitialized_variable_info) info;
 790                 out.writeShort(u.offset);
 791                 break;
 792 
 793             default:
 794                 throw new Error();
 795             }
 796         }
 797     }
 798 
 799     /**
 800      * Writer for annotations and the values they contain.
 801      */
 802     protected static class AnnotationWriter
 803             implements Annotation.element_value.Visitor<Void,ClassOutputStream> {
 804         public void write(Annotation[] annos, ClassOutputStream out) {
 805             out.writeShort(annos.length);
 806             for (Annotation anno: annos)
 807                 write(anno, out);
 808         }
 809 
 810         public void write(TypeAnnotation[] annos, ClassOutputStream out) {
 811             out.writeShort(annos.length);
 812             for (TypeAnnotation anno: annos)
 813                 write(anno, out);
 814         }
 815 
 816         public void write(Annotation anno, ClassOutputStream out) {
 817             out.writeShort(anno.type_index);
 818             out.writeShort(anno.element_value_pairs.length);
 819             for (element_value_pair p: anno.element_value_pairs)
 820                 write(p, out);
 821         }
 822 
 823         public void write(TypeAnnotation anno, ClassOutputStream out) {
 824             write(anno.position, out);
 825             write(anno.annotation, out);
 826         }
 827 
 828         public void write(element_value_pair pair, ClassOutputStream out) {
 829             out.writeShort(pair.element_name_index);
 830             write(pair.value, out);
 831         }
 832 
 833         public void write(element_value ev, ClassOutputStream out) {
 834             out.writeByte(ev.tag);
 835             ev.accept(this, out);
 836         }
 837 
 838         @Override
 839         public Void visitPrimitive(Primitive_element_value ev, ClassOutputStream out) {
 840             out.writeShort(ev.const_value_index);
 841             return null;
 842         }
 843 
 844         @Override
 845         public Void visitEnum(Enum_element_value ev, ClassOutputStream out) {
 846             out.writeShort(ev.type_name_index);
 847             out.writeShort(ev.const_name_index);
 848             return null;
 849         }
 850 
 851         @Override
 852         public Void visitClass(Class_element_value ev, ClassOutputStream out) {
 853             out.writeShort(ev.class_info_index);
 854             return null;
 855         }
 856 
 857         @Override
 858         public Void visitAnnotation(Annotation_element_value ev, ClassOutputStream out) {
 859             write(ev.annotation_value, out);
 860             return null;
 861         }
 862 
 863         @Override
 864         public Void visitArray(Array_element_value ev, ClassOutputStream out) {
 865             out.writeShort(ev.num_values);
 866             for (element_value v: ev.values)
 867                 write(v, out);
 868             return null;
 869         }
 870 
 871         // TODO: Move this to TypeAnnotation to be closer with similar logic?
 872         private void write(TypeAnnotation.Position p, ClassOutputStream out) {
 873             out.writeByte(p.type.targetTypeValue());
 874             switch (p.type) {
 875             // instanceof
 876             case INSTANCEOF:
 877             // new expression
 878             case NEW:
 879             // constructor/method reference receiver
 880             case CONSTRUCTOR_REFERENCE:
 881             case METHOD_REFERENCE:
 882                 out.writeShort(p.offset);
 883                 break;
 884             // local variable
 885             case LOCAL_VARIABLE:
 886             // resource variable
 887             case RESOURCE_VARIABLE:
 888                 int table_length = p.lvarOffset.length;
 889                 out.writeShort(table_length);
 890                 for (int i = 0; i < table_length; ++i) {
 891                     out.writeShort(1);  // for table length
 892                     out.writeShort(p.lvarOffset[i]);
 893                     out.writeShort(p.lvarLength[i]);
 894                     out.writeShort(p.lvarIndex[i]);
 895                 }
 896                 break;
 897             // exception parameter
 898             case EXCEPTION_PARAMETER:
 899                 out.writeShort(p.exception_index);
 900                 break;
 901             // method receiver
 902             case METHOD_RECEIVER:
 903                 // Do nothing
 904                 break;
 905             // type parameters
 906             case CLASS_TYPE_PARAMETER:
 907             case METHOD_TYPE_PARAMETER:
 908                 out.writeByte(p.parameter_index);
 909                 break;
 910             // type parameters bounds
 911             case CLASS_TYPE_PARAMETER_BOUND:
 912             case METHOD_TYPE_PARAMETER_BOUND:
 913                 out.writeByte(p.parameter_index);
 914                 out.writeByte(p.bound_index);
 915                 break;
 916             // class extends or implements clause
 917             case CLASS_EXTENDS:
 918                 out.writeShort(p.type_index);
 919                 break;
 920             // throws
 921             case THROWS:
 922                 out.writeShort(p.type_index);
 923                 break;
 924             // method parameter
 925             case METHOD_FORMAL_PARAMETER:
 926                 out.writeByte(p.parameter_index);
 927                 break;
 928             // type cast
 929             case CAST:
 930             // method/constructor/reference type argument
 931             case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
 932             case METHOD_INVOCATION_TYPE_ARGUMENT:
 933             case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
 934             case METHOD_REFERENCE_TYPE_ARGUMENT:
 935                 out.writeShort(p.offset);
 936                 out.writeByte(p.type_index);
 937                 break;
 938             // We don't need to worry about these
 939             case METHOD_RETURN:
 940             case FIELD:
 941                 break;
 942             case UNKNOWN:
 943                 throw new AssertionError("ClassWriter: UNKNOWN target type should never occur!");
 944             default:
 945                 throw new AssertionError("ClassWriter: Unknown target type for position: " + p);
 946             }
 947 
 948             { // Append location data for generics/arrays.
 949                 // TODO: check for overrun?
 950                 out.writeByte((byte)p.location.size());
 951                 for (int i : TypeAnnotation.Position.getBinaryFromTypePath(p.location))
 952                     out.writeByte((byte)i);
 953             }
 954         }
 955     }
 956 }