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      * @throws IllegalStateException
 199      *             If a subclass calls this constructor.
 200      */
 201     public SerialVersionUIDAdder(final ClassVisitor cv) {
 202         this(Opcodes.ASM5, cv);
 203         if (getClass() != SerialVersionUIDAdder.class) {
 204             throw new IllegalStateException();
 205         }
 206     }
 207 
 208     /**
 209      * Creates a new {@link SerialVersionUIDAdder}.
 210      *
 211      * @param api
 212      *            the ASM API version implemented by this visitor. Must be one
 213      *            of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
 214      * @param cv
 215      *            a {@link ClassVisitor} to which this visitor will delegate
 216      *            calls.
 217      */
 218     protected SerialVersionUIDAdder(final int api, final ClassVisitor cv) {
 219         super(api, cv);
 220         svuidFields = new ArrayList<Item>();
 221         svuidConstructors = new ArrayList<Item>();
 222         svuidMethods = new ArrayList<Item>();
 223     }
 224 
 225     // ------------------------------------------------------------------------
 226     // Overridden methods
 227     // ------------------------------------------------------------------------
 228 
 229     /*
 230      * Visit class header and get class name, access , and interfaces
 231      * information (step 1,2, and 3) for SVUID computation.
 232      */
 233     @Override
 234     public void visit(final int version, final int access, final String name,
 235             final String signature, final String superName,
 236             final String[] interfaces) {
 237         computeSVUID = (access & Opcodes.ACC_INTERFACE) == 0;
 238 
 239         if (computeSVUID) {
 240             this.name = name;
 241             this.access = access;
 242             this.interfaces = Arrays.copyOf(interfaces, interfaces.length);
 243         }
 244 
 245         super.visit(version, access, name, signature, superName, interfaces);
 246     }
 247 
 248     /*
 249      * Visit the methods and get constructor and method information (step 5 and
 250      * 7). Also determine if there is a class initializer (step 6).
 251      */
 252     @Override
 253     public MethodVisitor visitMethod(final int access, final String name,
 254             final String desc, final String signature, final String[] exceptions) {
 255         if (computeSVUID) {
 256             if ("<clinit>".equals(name)) {
 257                 hasStaticInitializer = true;
 258             }
 259             /*
 260              * Remembers non private constructors and methods for SVUID
 261              * computation For constructor and method modifiers, only the
 262              * ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
 263              * ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags
 264              * are used.
 265              */
 266             int mods = access
 267                     & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
 268                             | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
 269                             | Opcodes.ACC_FINAL | Opcodes.ACC_SYNCHRONIZED
 270                             | Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_STRICT);
 271 
 272             // all non private methods
 273             if ((access & Opcodes.ACC_PRIVATE) == 0) {
 274                 if ("<init>".equals(name)) {
 275                     svuidConstructors.add(new Item(name, mods, desc));
 276                 } else if (!"<clinit>".equals(name)) {
 277                     svuidMethods.add(new Item(name, mods, desc));
 278                 }
 279             }
 280         }
 281 
 282         return super.visitMethod(access, name, desc, signature, exceptions);
 283     }
 284 
 285     /*
 286      * Gets class field information for step 4 of the algorithm. Also determines
 287      * if the class already has a SVUID.
 288      */
 289     @Override
 290     public FieldVisitor visitField(final int access, final String name,
 291             final String desc, final String signature, final Object value) {
 292         if (computeSVUID) {
 293             if ("serialVersionUID".equals(name)) {
 294                 // since the class already has SVUID, we won't be computing it.
 295                 computeSVUID = false;
 296                 hasSVUID = true;
 297             }
 298             /*
 299              * Remember field for SVUID computation For field modifiers, only
 300              * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
 301              * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
 302              * computing serialVersionUID values.
 303              */
 304             if ((access & Opcodes.ACC_PRIVATE) == 0
 305                     || (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
 306                 int mods = access
 307                         & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
 308                                 | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
 309                                 | Opcodes.ACC_FINAL | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
 310                 svuidFields.add(new Item(name, mods, desc));
 311             }
 312         }
 313 
 314         return super.visitField(access, name, desc, signature, value);
 315     }
 316 
 317     /**
 318      * Handle a bizarre special case. Nested classes (static classes declared
 319      * inside another class) that are protected have their access bit set to
 320      * public in their class files to deal with some odd reflection situation.
 321      * Our SVUID computation must do as the JVM does and ignore access bits in
 322      * the class file in favor of the access bits InnerClass attribute.
 323      */
 324     @Override
 325     public void visitInnerClass(final String aname, final String outerName,
 326             final String innerName, final int attr_access) {
 327         if ((name != null) && name.equals(aname)) {
 328             this.access = attr_access;
 329         }
 330         super.visitInnerClass(aname, outerName, innerName, attr_access);
 331     }
 332 
 333     /*
 334      * Add the SVUID if class doesn't have one
 335      */
 336     @Override
 337     public void visitEnd() {
 338         // compute SVUID and add it to the class
 339         if (computeSVUID && !hasSVUID) {
 340             try {
 341                 addSVUID(computeSVUID());
 342             } catch (Throwable e) {
 343                 throw new RuntimeException("Error while computing SVUID for "
 344                         + name, e);
 345             }
 346         }
 347 
 348         super.visitEnd();
 349     }
 350 
 351     // ------------------------------------------------------------------------
 352     // Utility methods
 353     // ------------------------------------------------------------------------
 354 
 355     /**
 356      * Returns true if the class already has a SVUID field. The result of this
 357      * method is only valid when visitEnd is or has been called.
 358      *
 359      * @return true if the class already has a SVUID field.
 360      */
 361     public boolean hasSVUID() {
 362         return hasSVUID;
 363     }
 364 
 365     protected void addSVUID(long svuid) {
 366         FieldVisitor fv = super.visitField(Opcodes.ACC_FINAL
 367                 + Opcodes.ACC_STATIC, "serialVersionUID", "J", null, new Long(
 368                 svuid));
 369         if (fv != null) {
 370             fv.visitEnd();
 371         }
 372     }
 373 
 374     /**
 375      * Computes and returns the value of SVUID.
 376      *
 377      * @return Returns the serial version UID
 378      * @throws IOException
 379      *             if an I/O error occurs
 380      */
 381     protected long computeSVUID() throws IOException {
 382         ByteArrayOutputStream bos;
 383         DataOutputStream dos = null;
 384         long svuid = 0;
 385 
 386         try {
 387             bos = new ByteArrayOutputStream();
 388             dos = new DataOutputStream(bos);
 389 
 390             /*
 391              * 1. The class name written using UTF encoding.
 392              */
 393             dos.writeUTF(name.replace('/', '.'));
 394 
 395             /*
 396              * 2. The class modifiers written as a 32-bit integer.
 397              */
 398             dos.writeInt(access
 399                     & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
 400                             | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
 401 
 402             /*
 403              * 3. The name of each interface sorted by name written using UTF
 404              * encoding.
 405              */
 406             Arrays.sort(interfaces);
 407             for (int i = 0; i < interfaces.length; i++) {
 408                 dos.writeUTF(interfaces[i].replace('/', '.'));
 409             }
 410 
 411             /*
 412              * 4. For each field of the class sorted by field name (except
 413              * private static and private transient fields):
 414              *
 415              * 1. The name of the field in UTF encoding. 2. The modifiers of the
 416              * field written as a 32-bit integer. 3. The descriptor of the field
 417              * in UTF encoding
 418              *
 419              * Note that field signatures are not dot separated. Method and
 420              * constructor signatures are dot separated. Go figure...
 421              */
 422             writeItems(svuidFields, dos, false);
 423 
 424             /*
 425              * 5. If a class initializer exists, write out the following: 1. The
 426              * name of the method, <clinit>, in UTF encoding. 2. The modifier of
 427              * the method, java.lang.reflect.Modifier.STATIC, written as a
 428              * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
 429              * encoding.
 430              */
 431             if (hasStaticInitializer) {
 432                 dos.writeUTF("<clinit>");
 433                 dos.writeInt(Opcodes.ACC_STATIC);
 434                 dos.writeUTF("()V");
 435             } // if..
 436 
 437             /*
 438              * 6. For each non-private constructor sorted by method name and
 439              * signature: 1. The name of the method, <init>, in UTF encoding. 2.
 440              * The modifiers of the method written as a 32-bit integer. 3. The
 441              * descriptor of the method in UTF encoding.
 442              */
 443             writeItems(svuidConstructors, dos, true);
 444 
 445             /*
 446              * 7. For each non-private method sorted by method name and
 447              * signature: 1. The name of the method in UTF encoding. 2. The
 448              * modifiers of the method written as a 32-bit integer. 3. The
 449              * descriptor of the method in UTF encoding.
 450              */
 451             writeItems(svuidMethods, dos, true);
 452 
 453             dos.flush();
 454 
 455             /*
 456              * 8. The SHA-1 algorithm is executed on the stream of bytes
 457              * produced by DataOutputStream and produces five 32-bit values
 458              * sha[0..4].
 459              */
 460             byte[] hashBytes = computeSHAdigest(bos.toByteArray());
 461 
 462             /*
 463              * 9. The hash value is assembled from the first and second 32-bit
 464              * values of the SHA-1 message digest. If the result of the message
 465              * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
 466              * five int values named sha, the hash value would be computed as
 467              * follows:
 468              *
 469              * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF)
 470              * << 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
 471              * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
 472              * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
 473              * 56;
 474              */
 475             for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
 476                 svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
 477             }
 478         } finally {
 479             // close the stream (if open)
 480             if (dos != null) {
 481                 dos.close();
 482             }
 483         }
 484 
 485         return svuid;
 486     }
 487 
 488     /**
 489      * Returns the SHA-1 message digest of the given value.
 490      *
 491      * @param value
 492      *            the value whose SHA message digest must be computed.
 493      * @return the SHA-1 message digest of the given value.
 494      */
 495     protected byte[] computeSHAdigest(final byte[] value) {
 496         try {
 497             return MessageDigest.getInstance("SHA").digest(value);
 498         } catch (Exception e) {
 499             throw new UnsupportedOperationException(e.toString());
 500         }
 501     }
 502 
 503     /**
 504      * Sorts the items in the collection and writes it to the data output stream
 505      *
 506      * @param itemCollection
 507      *            collection of items
 508      * @param dos
 509      *            a <code>DataOutputStream</code> value
 510      * @param dotted
 511      *            a <code>boolean</code> value
 512      * @exception IOException
 513      *                if an error occurs
 514      */
 515     private static void writeItems(final Collection<Item> itemCollection,
 516             final DataOutput dos, final boolean dotted) throws IOException {
 517         int size = itemCollection.size();
 518         Item[] items = itemCollection.toArray(new Item[size]);
 519         Arrays.sort(items);
 520         for (int i = 0; i < size; i++) {
 521             dos.writeUTF(items[i].name);
 522             dos.writeInt(items[i].access);
 523             dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
 524                     : items[i].desc);
 525         }
 526     }
 527 
 528     // ------------------------------------------------------------------------
 529     // Inner classes
 530     // ------------------------------------------------------------------------
 531 
 532     private static class Item implements Comparable<Item> {
 533 
 534         final String name;
 535 
 536         final int access;
 537 
 538         final String desc;
 539 
 540         Item(final String name, final int access, final String desc) {
 541             this.name = name;
 542             this.access = access;
 543             this.desc = desc;
 544         }
 545 
 546         public int compareTo(final Item other) {
 547             int retVal = name.compareTo(other.name);
 548             if (retVal == 0) {
 549                 retVal = desc.compareTo(other.desc);
 550             }
 551             return retVal;
 552         }
 553 
 554         @Override
 555         public boolean equals(final Object o) {
 556             if (o instanceof Item) {
 557                 return compareTo((Item) o) == 0;
 558             }
 559             return false;
 560         }
 561 
 562         @Override
 563         public int hashCode() {
 564             return (name + desc).hashCode();
 565         }
 566     }
 567 }