001/***
002 * ASM: a very small and fast Java bytecode manipulation framework
003 * Copyright (c) 2000-2011 INRIA, France Telecom
004 * All rights reserved.
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions
008 * are met:
009 * 1. Redistributions of source code must retain the above copyright
010 *    notice, this list of conditions and the following disclaimer.
011 * 2. Redistributions in binary form must reproduce the above copyright
012 *    notice, this list of conditions and the following disclaimer in the
013 *    documentation and/or other materials provided with the distribution.
014 * 3. Neither the name of the copyright holders nor the names of its
015 *    contributors may be used to endorse or promote products derived from
016 *    this software without specific prior written permission.
017 *
018 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
019 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
020 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
021 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
022 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
023 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
024 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
025 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
026 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
027 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
028 * THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package io.ebean.enhance.asm.commons;
031
032import io.ebean.enhance.asm.ClassVisitor;
033import io.ebean.enhance.asm.FieldVisitor;
034import io.ebean.enhance.asm.MethodVisitor;
035import io.ebean.enhance.asm.Opcodes;
036
037import java.io.ByteArrayOutputStream;
038import java.io.DataOutput;
039import java.io.DataOutputStream;
040import java.io.IOException;
041import java.security.MessageDigest;
042import java.util.ArrayList;
043import java.util.Arrays;
044import java.util.Collection;
045
046/**
047 * A {@link ClassVisitor} that adds a serial version unique identifier to a
048 * class if missing. Here is typical usage of this class:
049 * 
050 * <pre>
051 *   ClassWriter cw = new ClassWriter(...);
052 *   ClassVisitor sv = new SerialVersionUIDAdder(cw);
053 *   ClassVisitor ca = new MyClassAdapter(sv);
054 *   new ClassReader(orginalClass).accept(ca, false);
055 * </pre>
056 * 
057 * The SVUID algorithm can be found <a href=
058 * "http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html"
059 * >http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html</a>:
060 * 
061 * <pre>
062 * The serialVersionUID is computed using the signature of a stream of bytes
063 * that reflect the class definition. The National Institute of Standards and
064 * Technology (NIST) Secure Hash Algorithm (SHA-1) is used to compute a
065 * signature for the stream. The first two 32-bit quantities are used to form a
066 * 64-bit hash. A java.lang.DataOutputStream is used to convert primitive data
067 * types to a sequence of bytes. The values input to the stream are defined by
068 * the Java Virtual Machine (VM) specification for classes.
069 * 
070 * The sequence of items in the stream is as follows:
071 * 
072 * 1. The class name written using UTF encoding.
073 * 2. The class modifiers written as a 32-bit integer.
074 * 3. The name of each interface sorted by name written using UTF encoding.
075 * 4. For each field of the class sorted by field name (except private static
076 * and private transient fields):
077 * 1. The name of the field in UTF encoding.
078 * 2. The modifiers of the field written as a 32-bit integer.
079 * 3. The descriptor of the field in UTF encoding
080 * 5. If a class initializer exists, write out the following:
081 * 1. The name of the method, &lt;clinit&gt;, in UTF encoding.
082 * 2. The modifier of the method, java.lang.reflect.Modifier.STATIC,
083 * written as a 32-bit integer.
084 * 3. The descriptor of the method, ()V, in UTF encoding.
085 * 6. For each non-private constructor sorted by method name and signature:
086 * 1. The name of the method, &lt;init&gt;, in UTF encoding.
087 * 2. The modifiers of the method written as a 32-bit integer.
088 * 3. The descriptor of the method in UTF encoding.
089 * 7. For each non-private method sorted by method name and signature:
090 * 1. The name of the method in UTF encoding.
091 * 2. The modifiers of the method written as a 32-bit integer.
092 * 3. The descriptor of the method in UTF encoding.
093 * 8. The SHA-1 algorithm is executed on the stream of bytes produced by
094 * DataOutputStream and produces five 32-bit values sha[0..4].
095 * 
096 * 9. The hash value is assembled from the first and second 32-bit values of
097 * the SHA-1 message digest. If the result of the message digest, the five
098 * 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named
099 * sha, the hash value would be computed as follows:
100 * 
101 * long hash = ((sha[0] &gt;&gt;&gt; 24) &amp; 0xFF) |
102 * ((sha[0] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 8 |
103 * ((sha[0] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 16 |
104 * ((sha[0] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 24 |
105 * ((sha[1] &gt;&gt;&gt; 24) &amp; 0xFF) &lt;&lt; 32 |
106 * ((sha[1] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 40 |
107 * ((sha[1] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 48 |
108 * ((sha[1] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 56;
109 * </pre>
110 * 
111 * @author Rajendra Inamdar, Vishal Vishnoi
112 */
113public class SerialVersionUIDAdder extends ClassVisitor {
114
115    /**
116     * Flag that indicates if we need to compute SVUID.
117     */
118    private boolean computeSVUID;
119
120    /**
121     * Set to true if the class already has SVUID.
122     */
123    private boolean hasSVUID;
124
125    /**
126     * Classes access flags.
127     */
128    private int access;
129
130    /**
131     * Internal name of the class
132     */
133    private String name;
134
135    /**
136     * Interfaces implemented by the class.
137     */
138    private String[] interfaces;
139
140    /**
141     * Collection of fields. (except private static and private transient
142     * fields)
143     */
144    private Collection<Item> svuidFields;
145
146    /**
147     * Set to true if the class has static initializer.
148     */
149    private boolean hasStaticInitializer;
150
151    /**
152     * Collection of non-private constructors.
153     */
154    private Collection<Item> svuidConstructors;
155
156    /**
157     * Collection of non-private methods.
158     */
159    private Collection<Item> svuidMethods;
160
161    /**
162     * Creates a new {@link SerialVersionUIDAdder}. <i>Subclasses must not use
163     * this constructor</i>. Instead, they must use the
164     * {@link #SerialVersionUIDAdder(int, ClassVisitor)} version.
165     * 
166     * @param cv
167     *            a {@link ClassVisitor} to which this visitor will delegate
168     *            calls.
169     * @throws IllegalStateException
170     *             If a subclass calls this constructor.
171     */
172    public SerialVersionUIDAdder(final ClassVisitor cv) {
173        this(Opcodes.ASM6, cv);
174        if (getClass() != SerialVersionUIDAdder.class) {
175            throw new IllegalStateException();
176        }
177    }
178
179    /**
180     * Creates a new {@link SerialVersionUIDAdder}.
181     * 
182     * @param api
183     *            the ASM API version implemented by this visitor. Must be one
184     *            of {@link Opcodes#ASM4}, {@link Opcodes#ASM5} or {@link Opcodes#ASM6}.
185     * @param cv
186     *            a {@link ClassVisitor} to which this visitor will delegate
187     *            calls.
188     */
189    protected SerialVersionUIDAdder(final int api, final ClassVisitor cv) {
190        super(api, cv);
191        svuidFields = new ArrayList<Item>();
192        svuidConstructors = new ArrayList<Item>();
193        svuidMethods = new ArrayList<Item>();
194    }
195
196    // ------------------------------------------------------------------------
197    // Overridden methods
198    // ------------------------------------------------------------------------
199
200    /*
201     * Visit class header and get class name, access , and interfaces
202     * information (step 1,2, and 3) for SVUID computation.
203     */
204    @Override
205    public void visit(final int version, final int access, final String name,
206            final String signature, final String superName,
207            final String[] interfaces) {
208        computeSVUID = (access & Opcodes.ACC_ENUM) == 0;
209
210        if (computeSVUID) {
211            this.name = name;
212            this.access = access;
213            this.interfaces = new String[interfaces.length];
214            System.arraycopy(interfaces, 0, this.interfaces, 0,
215                    interfaces.length);
216        }
217
218        super.visit(version, access, name, signature, superName, interfaces);
219    }
220
221    /*
222     * Visit the methods and get constructor and method information (step 5 and
223     * 7). Also determine if there is a class initializer (step 6).
224     */
225    @Override
226    public MethodVisitor visitMethod(final int access, final String name,
227                                     final String desc, final String signature, final String[] exceptions) {
228        if (computeSVUID) {
229            if ("<clinit>".equals(name)) {
230                hasStaticInitializer = true;
231            }
232            /*
233             * Remembers non private constructors and methods for SVUID
234             * computation For constructor and method modifiers, only the
235             * ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
236             * ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags
237             * are used.
238             */
239            int mods = access
240                    & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
241                            | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
242                            | Opcodes.ACC_FINAL | Opcodes.ACC_SYNCHRONIZED
243                            | Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_STRICT);
244
245            // all non private methods
246            if ((access & Opcodes.ACC_PRIVATE) == 0) {
247                if ("<init>".equals(name)) {
248                    svuidConstructors.add(new Item(name, mods, desc));
249                } else if (!"<clinit>".equals(name)) {
250                    svuidMethods.add(new Item(name, mods, desc));
251                }
252            }
253        }
254
255        return super.visitMethod(access, name, desc, signature, exceptions);
256    }
257
258    /*
259     * Gets class field information for step 4 of the algorithm. Also determines
260     * if the class already has a SVUID.
261     */
262    @Override
263    public FieldVisitor visitField(final int access, final String name,
264                                   final String desc, final String signature, final Object value) {
265        if (computeSVUID) {
266            if ("serialVersionUID".equals(name)) {
267                // since the class already has SVUID, we won't be computing it.
268                computeSVUID = false;
269                hasSVUID = true;
270            }
271            /*
272             * Remember field for SVUID computation For field modifiers, only
273             * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
274             * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
275             * computing serialVersionUID values.
276             */
277            if ((access & Opcodes.ACC_PRIVATE) == 0
278                    || (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
279                int mods = access
280                        & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
281                                | Opcodes.ACC_PROTECTED | Opcodes.ACC_STATIC
282                                | Opcodes.ACC_FINAL | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
283                svuidFields.add(new Item(name, mods, desc));
284            }
285        }
286
287        return super.visitField(access, name, desc, signature, value);
288    }
289
290    /**
291     * Handle a bizarre special case. Nested classes (static classes declared
292     * inside another class) that are protected have their access bit set to
293     * public in their class files to deal with some odd reflection situation.
294     * Our SVUID computation must do as the JVM does and ignore access bits in
295     * the class file in favor of the access bits InnerClass attribute.
296     */
297    @Override
298    public void visitInnerClass(final String aname, final String outerName,
299            final String innerName, final int attr_access) {
300        if ((name != null) && name.equals(aname)) {
301            this.access = attr_access;
302        }
303        super.visitInnerClass(aname, outerName, innerName, attr_access);
304    }
305
306    /*
307     * Add the SVUID if class doesn't have one
308     */
309    @Override
310    public void visitEnd() {
311        // compute SVUID and add it to the class
312        if (computeSVUID && !hasSVUID) {
313            try {
314                addSVUID(computeSVUID());
315            } catch (Throwable e) {
316                throw new RuntimeException("Error while computing SVUID for "
317                        + name, e);
318            }
319        }
320
321        super.visitEnd();
322    }
323
324    // ------------------------------------------------------------------------
325    // Utility methods
326    // ------------------------------------------------------------------------
327
328    /**
329     * Returns true if the class already has a SVUID field. The result of this
330     * method is only valid when visitEnd is or has been called.
331     * 
332     * @return true if the class already has a SVUID field.
333     */
334    public boolean hasSVUID() {
335        return hasSVUID;
336    }
337
338    protected void addSVUID(long svuid) {
339        FieldVisitor fv = super.visitField(Opcodes.ACC_FINAL
340                + Opcodes.ACC_STATIC, "serialVersionUID", "J", null, svuid);
341        if (fv != null) {
342            fv.visitEnd();
343        }
344    }
345
346    /**
347     * Computes and returns the value of SVUID.
348     * 
349     * @return Returns the serial version UID
350     * @throws IOException
351     *             if an I/O error occurs
352     */
353    protected long computeSVUID() throws IOException {
354        ByteArrayOutputStream bos;
355        DataOutputStream dos = null;
356        long svuid = 0;
357
358        try {
359            bos = new ByteArrayOutputStream();
360            dos = new DataOutputStream(bos);
361
362            /*
363             * 1. The class name written using UTF encoding.
364             */
365            dos.writeUTF(name.replace('/', '.'));
366
367            /*
368             * 2. The class modifiers written as a 32-bit integer.
369             */
370            int access = this.access;
371            if ((access & Opcodes.ACC_INTERFACE) != 0) {
372                access = (svuidMethods.size() > 0) ? (access | Opcodes.ACC_ABSTRACT)
373                        : (access & ~Opcodes.ACC_ABSTRACT);
374            }
375            dos.writeInt(access
376                    & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
377                            | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
378
379            /*
380             * 3. The name of each interface sorted by name written using UTF
381             * encoding.
382             */
383            Arrays.sort(interfaces);
384            for (int i = 0; i < interfaces.length; i++) {
385                dos.writeUTF(interfaces[i].replace('/', '.'));
386            }
387
388            /*
389             * 4. For each field of the class sorted by field name (except
390             * private static and private transient fields):
391             * 
392             * 1. The name of the field in UTF encoding. 2. The modifiers of the
393             * field written as a 32-bit integer. 3. The descriptor of the field
394             * in UTF encoding
395             * 
396             * Note that field signatures are not dot separated. Method and
397             * constructor signatures are dot separated. Go figure...
398             */
399            writeItems(svuidFields, dos, false);
400
401            /*
402             * 5. If a class initializer exists, write out the following: 1. The
403             * name of the method, <clinit>, in UTF encoding. 2. The modifier of
404             * the method, java.lang.reflect.Modifier.STATIC, written as a
405             * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
406             * encoding.
407             */
408            if (hasStaticInitializer) {
409                dos.writeUTF("<clinit>");
410                dos.writeInt(Opcodes.ACC_STATIC);
411                dos.writeUTF("()V");
412            } // if..
413
414            /*
415             * 6. For each non-private constructor sorted by method name and
416             * signature: 1. The name of the method, <init>, in UTF encoding. 2.
417             * The modifiers of the method written as a 32-bit integer. 3. The
418             * descriptor of the method in UTF encoding.
419             */
420            writeItems(svuidConstructors, dos, true);
421
422            /*
423             * 7. For each non-private method sorted by method name and
424             * signature: 1. The name of the method in UTF encoding. 2. The
425             * modifiers of the method written as a 32-bit integer. 3. The
426             * descriptor of the method in UTF encoding.
427             */
428            writeItems(svuidMethods, dos, true);
429
430            dos.flush();
431
432            /*
433             * 8. The SHA-1 algorithm is executed on the stream of bytes
434             * produced by DataOutputStream and produces five 32-bit values
435             * sha[0..4].
436             */
437            byte[] hashBytes = computeSHAdigest(bos.toByteArray());
438
439            /*
440             * 9. The hash value is assembled from the first and second 32-bit
441             * values of the SHA-1 message digest. If the result of the message
442             * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
443             * five int values named sha, the hash value would be computed as
444             * follows:
445             * 
446             * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF)
447             * << 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
448             * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
449             * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
450             * 56;
451             */
452            for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
453                svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
454            }
455        } finally {
456            // close the stream (if open)
457            if (dos != null) {
458                dos.close();
459            }
460        }
461
462        return svuid;
463    }
464
465    /**
466     * Returns the SHA-1 message digest of the given value.
467     * 
468     * @param value
469     *            the value whose SHA message digest must be computed.
470     * @return the SHA-1 message digest of the given value.
471     */
472    protected byte[] computeSHAdigest(final byte[] value) {
473        try {
474            return MessageDigest.getInstance("SHA").digest(value);
475        } catch (Exception e) {
476            throw new UnsupportedOperationException(e.toString());
477        }
478    }
479
480    /**
481     * Sorts the items in the collection and writes it to the data output stream
482     * 
483     * @param itemCollection
484     *            collection of items
485     * @param dos
486     *            a <code>DataOutputStream</code> value
487     * @param dotted
488     *            a <code>boolean</code> value
489     * @exception IOException
490     *                if an error occurs
491     */
492    private static void writeItems(final Collection<Item> itemCollection,
493            final DataOutput dos, final boolean dotted) throws IOException {
494        int size = itemCollection.size();
495        Item[] items = itemCollection.toArray(new Item[size]);
496        Arrays.sort(items);
497        for (int i = 0; i < size; i++) {
498            dos.writeUTF(items[i].name);
499            dos.writeInt(items[i].access);
500            dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
501                    : items[i].desc);
502        }
503    }
504
505    // ------------------------------------------------------------------------
506    // Inner classes
507    // ------------------------------------------------------------------------
508
509    private static class Item implements Comparable<Item> {
510
511        final String name;
512
513        final int access;
514
515        final String desc;
516
517        Item(final String name, final int access, final String desc) {
518            this.name = name;
519            this.access = access;
520            this.desc = desc;
521        }
522
523        public int compareTo(final Item other) {
524            int retVal = name.compareTo(other.name);
525            if (retVal == 0) {
526                retVal = desc.compareTo(other.desc);
527            }
528            return retVal;
529        }
530
531        @Override
532        public boolean equals(final Object o) {
533            if (o instanceof Item) {
534                return compareTo((Item) o) == 0;
535            }
536            return false;
537        }
538
539        @Override
540        public int hashCode() {
541            return (name + desc).hashCode();
542        }
543    }
544}