1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  31  * ASM: a very small and fast Java bytecode manipulation framework
  32  * Copyright (c) 2000-2011 INRIA, France Telecom
  33  * All rights reserved.
  34  *
  35  * Redistribution and use in source and binary forms, with or without
  36  * modification, are permitted provided that the following conditions
  37  * are met:
  38  * 1. Redistributions of source code must retain the above copyright
  39  *    notice, this list of conditions and the following disclaimer.
  40  * 2. Redistributions in binary form must reproduce the above copyright
  41  *    notice, this list of conditions and the following disclaimer in the
  42  *    documentation and/or other materials provided with the distribution.
  43  * 3. Neither the name of the copyright holders nor the names of its
  44  *    contributors may be used to endorse or promote products derived from
  45  *    this software without specific prior written permission.
  46  *
  47  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  48  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  50  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  51  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  52  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  53  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  54  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  55  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  56  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  57  * THE POSSIBILITY OF SUCH DAMAGE.
  58  */
  59 package jdk.internal.org.objectweb.asm.commons;
  60 
  61 import java.io.ByteArrayOutputStream;
  62 import java.io.DataOutput;
  63 import java.io.DataOutputStream;
  64 import java.io.IOException;
  65 import java.security.MessageDigest;
  66 import java.util.ArrayList;
  67 import java.util.Arrays;
  68 import java.util.Collection;
  69 
  70 import jdk.internal.org.objectweb.asm.ClassVisitor;
  71 import jdk.internal.org.objectweb.asm.FieldVisitor;
  72 import jdk.internal.org.objectweb.asm.MethodVisitor;
  73 import jdk.internal.org.objectweb.asm.Opcodes;
  74 
  75 /**
  76  * A {@link ClassVisitor} that adds a serial version unique identifier to a
  77  * class if missing. Here is typical usage of this class:
  78  *
  79  * <pre>
  80  *   ClassWriter cw = new ClassWriter(...);
  81  *   ClassVisitor sv = new SerialVersionUIDAdder(cw);
  82  *   ClassVisitor ca = new MyClassAdapter(sv);
  83  *   new ClassReader(orginalClass).accept(ca, false);
  84  * </pre>
  85  *
  86  * The SVUID algorithm can be found <a href=
  87  * "http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html"
  88  * >http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html</a>:
  89  *
  90  * <pre>
  91  * The serialVersionUID is computed using the signature of a stream of bytes
  92  * that reflect the class definition. The National Institute of Standards and
  93  * Technology (NIST) Secure Hash Algorithm (SHA-1) is used to compute a
  94  * signature for the stream. The first two 32-bit quantities are used to form a
  95  * 64-bit hash. A java.lang.DataOutputStream is used to convert primitive data
  96  * types to a sequence of bytes. The values input to the stream are defined by
  97  * the Java Virtual Machine (VM) specification for classes.
  98  *
  99  * The sequence of items in the stream is as follows:
 100  *
 101  * 1. The class name written using UTF encoding.
 102  * 2. The class modifiers written as a 32-bit integer.
 103  * 3. The name of each interface sorted by name written using UTF encoding.
 104  * 4. For each field of the class sorted by field name (except private static
 105  * and private transient fields):
 106  * 1. The name of the field in UTF encoding.
 107  * 2. The modifiers of the field written as a 32-bit integer.
 108  * 3. The descriptor of the field in UTF encoding
 109  * 5. If a class initializer exists, write out the following:
 110  * 1. The name of the method, &lt;clinit&gt;, in UTF encoding.
 111  * 2. The modifier of the method, java.lang.reflect.Modifier.STATIC,
 112  * written as a 32-bit integer.
 113  * 3. The descriptor of the method, ()V, in UTF encoding.
 114  * 6. For each non-private constructor sorted by method name and signature:
 115  * 1. The name of the method, &lt;init&gt;, in UTF encoding.
 116  * 2. The modifiers of the method written as a 32-bit integer.
 117  * 3. The descriptor of the method in UTF encoding.
 118  * 7. For each non-private method sorted by method name and signature:
 119  * 1. The name of the method in UTF encoding.
 120  * 2. The modifiers of the method written as a 32-bit integer.
 121  * 3. The descriptor of the method in UTF encoding.
 122  * 8. The SHA-1 algorithm is executed on the stream of bytes produced by
 123  * DataOutputStream and produces five 32-bit values sha[0..4].
 124  *
 125  * 9. The hash value is assembled from the first and second 32-bit values of
 126  * the SHA-1 message digest. If the result of the message digest, the five
 127  * 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named
 128  * sha, the hash value would be computed as follows:
 129  *
 130  * long hash = ((sha[0] &gt;&gt;&gt; 24) &amp; 0xFF) |
 131  * ((sha[0] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 8 |
 132  * ((sha[0] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 16 |
 133  * ((sha[0] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 24 |
 134  * ((sha[1] &gt;&gt;&gt; 24) &amp; 0xFF) &lt;&lt; 32 |
 135  * ((sha[1] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 40 |
 136  * ((sha[1] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 48 |
 137  * ((sha[1] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 56;
 138  * </pre>
 139  *
 140  * @author Rajendra Inamdar, Vishal Vishnoi
 141  */
 142 public class SerialVersionUIDAdder extends ClassVisitor {
 143 
 144     /**
 145      * Flag that indicates if we need to compute SVUID.
 146      */
 147     private boolean computeSVUID;
 148 
 149     /**
 150      * Set to true if the class already has SVUID.
 151      */
 152     private boolean hasSVUID;
 153 
 154     /**
 155      * Classes access flags.
 156      */
 157     private int access;
 158 
 159     /**
 160      * Internal name of the class
 161      */
 162     private String name;
 163 
 164     /**
 165      * Interfaces implemented by the class.
 166      */
 167     private String[] interfaces;
 168 
 169     /**
 170      * Collection of fields. (except private static and private transient
 171      * fields)
 172      */
 173     private Collection<Item> svuidFields;
 174 
 175     /**
 176      * Set to true if the class has static initializer.
 177      */
 178     private boolean hasStaticInitializer;
 179 
 180     /**
 181      * Collection of non-private constructors.
 182      */
 183     private Collection<Item> svuidConstructors;
 184 
 185     /**
 186      * Collection of non-private methods.
 187      */
 188     private Collection<Item> svuidMethods;
 189 
 190     /**
 191      * Creates a new {@link SerialVersionUIDAdder}. <i>Subclasses must not use
 192      * this constructor</i>. Instead, they must use the
 193      * {@link #SerialVersionUIDAdder(int, ClassVisitor)} version.
 194      *
 195      * @param cv
 196      *            a {@link ClassVisitor} to which this visitor will delegate
 197      *            calls.
 198      */
 199     public SerialVersionUIDAdder(final ClassVisitor cv) {
 200         this(Opcodes.ASM5, cv);
 201     }
 202 
 203     /**
 204      * Creates a new {@link SerialVersionUIDAdder}.
 205      *
 206      * @param api
 207      *            the ASM API version implemented by this visitor. Must be one
 208      *            of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
 209      * @param cv
 210      *            a {@link ClassVisitor} to which this visitor will delegate
 211      *            calls.
 212      */
 213     protected SerialVersionUIDAdder(final int api, final ClassVisitor cv) {
 214         super(api, cv);
 215         svuidFields = new ArrayList<Item>();
 216         svuidConstructors = new ArrayList<Item>();
 217         svuidMethods = new ArrayList<Item>();
 218     }
 219 
 220     // ------------------------------------------------------------------------
 221     // Overriden methods
 222     // ------------------------------------------------------------------------
 223 
 224     /*
 225      * Visit class header and get class name, access , and interfaces
 226      * information (step 1,2, and 3) for SVUID computation.
 227      */
 228     @Override
 229     public void visit(final int version, final int access, final String name,
 230             final String signature, final String superName,
 231             final String[] interfaces) {
 232         computeSVUID = (access & Opcodes.ACC_INTERFACE) == 0;
 233 
 234         if (computeSVUID) {
 235             this.name = name;
 236             this.access = access;
 237             this.interfaces = interfaces;
 238         }
 239 
 240         super.visit(version, access, name, signature, superName, interfaces);
 241     }
 242 
 243     /*
 244      * Visit the methods and get constructor and method information (step 5 and
 245      * 7). Also determine if there is a class initializer (step 6).
 246      */
 247     @Override
 248     public MethodVisitor visitMethod(final int access, final String name,
 249             final String desc, final String signature, final String[] exceptions) {
 250         if (computeSVUID) {
 251             if ("<clinit>".equals(name)) {
 252                 hasStaticInitializer = true;
 253             }
 254             /*
 255              * Remembers non private constructors and methods for SVUID
 256              * computation For constructor and method modifiers, only the
 257              * ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
 258              * ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags
 259              * are used.
 260              */
 261             int mods = access
 262                     & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
 263                             | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
 264                             | Opcodes.ACC_FINAL | Opcodes.ACC_SYNCHRONIZED
 265                             | Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_STRICT);
 266 
 267             // all non private methods
 268             if ((access & Opcodes.ACC_PRIVATE) == 0) {
 269                 if ("<init>".equals(name)) {
 270                     svuidConstructors.add(new Item(name, mods, desc));
 271                 } else if (!"<clinit>".equals(name)) {
 272                     svuidMethods.add(new Item(name, mods, desc));
 273                 }
 274             }
 275         }
 276 
 277         return super.visitMethod(access, name, desc, signature, exceptions);
 278     }
 279 
 280     /*
 281      * Gets class field information for step 4 of the algorithm. Also determines
 282      * if the class already has a SVUID.
 283      */
 284     @Override
 285     public FieldVisitor visitField(final int access, final String name,
 286             final String desc, final String signature, final Object value) {
 287         if (computeSVUID) {
 288             if ("serialVersionUID".equals(name)) {
 289                 // since the class already has SVUID, we won't be computing it.
 290                 computeSVUID = false;
 291                 hasSVUID = true;
 292             }
 293             /*
 294              * Remember field for SVUID computation For field modifiers, only
 295              * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
 296              * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
 297              * computing serialVersionUID values.
 298              */
 299             if ((access & Opcodes.ACC_PRIVATE) == 0
 300                     || (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
 301                 int mods = access
 302                         & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
 303                                 | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
 304                                 | Opcodes.ACC_FINAL | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
 305                 svuidFields.add(new Item(name, mods, desc));
 306             }
 307         }
 308 
 309         return super.visitField(access, name, desc, signature, value);
 310     }
 311 
 312     /**
 313      * Handle a bizarre special case. Nested classes (static classes declared
 314      * inside another class) that are protected have their access bit set to
 315      * public in their class files to deal with some odd reflection situation.
 316      * Our SVUID computation must do as the JVM does and ignore access bits in
 317      * the class file in favor of the access bits InnerClass attribute.
 318      */
 319     @Override
 320     public void visitInnerClass(final String aname, final String outerName,
 321             final String innerName, final int attr_access) {
 322         if ((name != null) && name.equals(aname)) {
 323             this.access = attr_access;
 324         }
 325         super.visitInnerClass(aname, outerName, innerName, attr_access);
 326     }
 327 
 328     /*
 329      * Add the SVUID if class doesn't have one
 330      */
 331     @Override
 332     public void visitEnd() {
 333         // compute SVUID and add it to the class
 334         if (computeSVUID && !hasSVUID) {
 335             try {
 336                 addSVUID(computeSVUID());
 337             } catch (Throwable e) {
 338                 throw new RuntimeException("Error while computing SVUID for "
 339                         + name, e);
 340             }
 341         }
 342 
 343         super.visitEnd();
 344     }
 345 
 346     // ------------------------------------------------------------------------
 347     // Utility methods
 348     // ------------------------------------------------------------------------
 349 
 350     /**
 351      * Returns true if the class already has a SVUID field. The result of this
 352      * method is only valid when visitEnd is or has been called.
 353      *
 354      * @return true if the class already has a SVUID field.
 355      */
 356     public boolean hasSVUID() {
 357         return hasSVUID;
 358     }
 359 
 360     protected void addSVUID(long svuid) {
 361         FieldVisitor fv = super.visitField(Opcodes.ACC_FINAL
 362                 + Opcodes.ACC_STATIC, "serialVersionUID", "J", null, new Long(
 363                 svuid));
 364         if (fv != null) {
 365             fv.visitEnd();
 366         }
 367     }
 368 
 369     /**
 370      * Computes and returns the value of SVUID.
 371      *
 372      * @return Returns the serial version UID
 373      * @throws IOException
 374      *             if an I/O error occurs
 375      */
 376     protected long computeSVUID() throws IOException {
 377         ByteArrayOutputStream bos;
 378         DataOutputStream dos = null;
 379         long svuid = 0;
 380 
 381         try {
 382             bos = new ByteArrayOutputStream();
 383             dos = new DataOutputStream(bos);
 384 
 385             /*
 386              * 1. The class name written using UTF encoding.
 387              */
 388             dos.writeUTF(name.replace('/', '.'));
 389 
 390             /*
 391              * 2. The class modifiers written as a 32-bit integer.
 392              */
 393             dos.writeInt(access
 394                     & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
 395                             | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
 396 
 397             /*
 398              * 3. The name of each interface sorted by name written using UTF
 399              * encoding.
 400              */
 401             Arrays.sort(interfaces);
 402             for (int i = 0; i < interfaces.length; i++) {
 403                 dos.writeUTF(interfaces[i].replace('/', '.'));
 404             }
 405 
 406             /*
 407              * 4. For each field of the class sorted by field name (except
 408              * private static and private transient fields):
 409              *
 410              * 1. The name of the field in UTF encoding. 2. The modifiers of the
 411              * field written as a 32-bit integer. 3. The descriptor of the field
 412              * in UTF encoding
 413              *
 414              * Note that field signatures are not dot separated. Method and
 415              * constructor signatures are dot separated. Go figure...
 416              */
 417             writeItems(svuidFields, dos, false);
 418 
 419             /*
 420              * 5. If a class initializer exists, write out the following: 1. The
 421              * name of the method, <clinit>, in UTF encoding. 2. The modifier of
 422              * the method, java.lang.reflect.Modifier.STATIC, written as a
 423              * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
 424              * encoding.
 425              */
 426             if (hasStaticInitializer) {
 427                 dos.writeUTF("<clinit>");
 428                 dos.writeInt(Opcodes.ACC_STATIC);
 429                 dos.writeUTF("()V");
 430             } // if..
 431 
 432             /*
 433              * 6. For each non-private constructor sorted by method name and
 434              * signature: 1. The name of the method, <init>, in UTF encoding. 2.
 435              * The modifiers of the method written as a 32-bit integer. 3. The
 436              * descriptor of the method in UTF encoding.
 437              */
 438             writeItems(svuidConstructors, dos, true);
 439 
 440             /*
 441              * 7. For each non-private method sorted by method name and
 442              * signature: 1. The name of the method in UTF encoding. 2. The
 443              * modifiers of the method written as a 32-bit integer. 3. The
 444              * descriptor of the method in UTF encoding.
 445              */
 446             writeItems(svuidMethods, dos, true);
 447 
 448             dos.flush();
 449 
 450             /*
 451              * 8. The SHA-1 algorithm is executed on the stream of bytes
 452              * produced by DataOutputStream and produces five 32-bit values
 453              * sha[0..4].
 454              */
 455             byte[] hashBytes = computeSHAdigest(bos.toByteArray());
 456 
 457             /*
 458              * 9. The hash value is assembled from the first and second 32-bit
 459              * values of the SHA-1 message digest. If the result of the message
 460              * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
 461              * five int values named sha, the hash value would be computed as
 462              * follows:
 463              *
 464              * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF)
 465              * << 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
 466              * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
 467              * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
 468              * 56;
 469              */
 470             for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
 471                 svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
 472             }
 473         } finally {
 474             // close the stream (if open)
 475             if (dos != null) {
 476                 dos.close();
 477             }
 478         }
 479 
 480         return svuid;
 481     }
 482 
 483     /**
 484      * Returns the SHA-1 message digest of the given value.
 485      *
 486      * @param value
 487      *            the value whose SHA message digest must be computed.
 488      * @return the SHA-1 message digest of the given value.
 489      */
 490     protected byte[] computeSHAdigest(final byte[] value) {
 491         try {
 492             return MessageDigest.getInstance("SHA").digest(value);
 493         } catch (Exception e) {
 494             throw new UnsupportedOperationException(e.toString());
 495         }
 496     }
 497 
 498     /**
 499      * Sorts the items in the collection and writes it to the data output stream
 500      *
 501      * @param itemCollection
 502      *            collection of items
 503      * @param dos
 504      *            a <code>DataOutputStream</code> value
 505      * @param dotted
 506      *            a <code>boolean</code> value
 507      * @exception IOException
 508      *                if an error occurs
 509      */
 510     private static void writeItems(final Collection<Item> itemCollection,
 511             final DataOutput dos, final boolean dotted) throws IOException {
 512         int size = itemCollection.size();
 513         Item[] items = itemCollection.toArray(new Item[size]);
 514         Arrays.sort(items);
 515         for (int i = 0; i < size; i++) {
 516             dos.writeUTF(items[i].name);
 517             dos.writeInt(items[i].access);
 518             dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
 519                     : items[i].desc);
 520         }
 521     }
 522 
 523     // ------------------------------------------------------------------------
 524     // Inner classes
 525     // ------------------------------------------------------------------------
 526 
 527     private static class Item implements Comparable<Item> {
 528 
 529         final String name;
 530 
 531         final int access;
 532 
 533         final String desc;
 534 
 535         Item(final String name, final int access, final String desc) {
 536             this.name = name;
 537             this.access = access;
 538             this.desc = desc;
 539         }
 540 
 541         public int compareTo(final Item other) {
 542             int retVal = name.compareTo(other.name);
 543             if (retVal == 0) {
 544                 retVal = desc.compareTo(other.desc);
 545             }
 546             return retVal;
 547         }
 548 
 549         @Override
 550         public boolean equals(final Object o) {
 551             if (o instanceof Item) {
 552                 return compareTo((Item) o) == 0;
 553             }
 554             return false;
 555         }
 556 
 557         @Override
 558         public int hashCode() {
 559             return (name + desc).hashCode();
 560         }
 561     }
 562 }