001: /*
002: * ASM: a very small and fast Java bytecode manipulation framework
003: * Copyright (c) 2000-2005 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: */
030: package org.objectweb.asm.commons;
031:
032: import java.io.ByteArrayOutputStream;
033: import java.io.DataOutputStream;
034: import java.io.IOException;
035: import java.security.MessageDigest;
036: import java.util.ArrayList;
037: import java.util.Arrays;
038: import java.util.Collection;
039:
040: import org.objectweb.asm.ClassAdapter;
041: import org.objectweb.asm.ClassVisitor;
042: import org.objectweb.asm.FieldVisitor;
043: import org.objectweb.asm.MethodVisitor;
044: import org.objectweb.asm.Opcodes;
045:
046: /**
047: * A {@link ClassAdapter} 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, <clinit>, 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, <init>, 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] >>> 24) & 0xFF) |
102: * ((sha[0] >>> 16) & 0xFF) << 8 |
103: * ((sha[0] >>> 8) & 0xFF) << 16 |
104: * ((sha[0] >>> 0) & 0xFF) << 24 |
105: * ((sha[1] >>> 24) & 0xFF) << 32 |
106: * ((sha[1] >>> 16) & 0xFF) << 40 |
107: * ((sha[1] >>> 8) & 0xFF) << 48 |
108: * ((sha[1] >>> 0) & 0xFF) << 56;
109: * </pre>
110: *
111: * @author Rajendra Inamdar, Vishal Vishnoi
112: */
113: @SuppressWarnings("unchecked")
114: public class SerialVersionUIDAdder extends ClassAdapter {
115:
116: /**
117: * Flag that indicates if we need to compute SVUID.
118: */
119: protected boolean computeSVUID;
120:
121: /**
122: * Set to true if the class already has SVUID.
123: */
124: protected boolean hasSVUID;
125:
126: /**
127: * Classes access flags.
128: */
129: protected int access;
130:
131: /**
132: * Internal name of the class
133: */
134: protected String name;
135:
136: /**
137: * Interfaces implemented by the class.
138: */
139: protected String[] interfaces;
140:
141: /**
142: * Collection of fields. (except private static and private transient
143: * fields)
144: */
145: protected Collection svuidFields;
146:
147: /**
148: * Set to true if the class has static initializer.
149: */
150: protected boolean hasStaticInitializer;
151:
152: /**
153: * Collection of non-private constructors.
154: */
155: protected Collection svuidConstructors;
156:
157: /**
158: * Collection of non-private methods.
159: */
160: protected Collection svuidMethods;
161:
162: /**
163: * Creates a new {@link SerialVersionUIDAdder}.
164: *
165: * @param cv a {@link ClassVisitor} to which this visitor will delegate
166: * calls.
167: */
168: public SerialVersionUIDAdder(final ClassVisitor cv) {
169: super (cv);
170: svuidFields = new ArrayList();
171: svuidConstructors = new ArrayList();
172: svuidMethods = new ArrayList();
173: }
174:
175: // ------------------------------------------------------------------------
176: // Overriden methods
177: // ------------------------------------------------------------------------
178:
179: /*
180: * Visit class header and get class name, access , and intefraces
181: * informatoin (step 1,2, and 3) for SVUID computation.
182: */@Override
183: public void visit(final int version, final int access,
184: final String name, final String signature,
185: final String super Name, final String[] interfaces) {
186: computeSVUID = (access & Opcodes.ACC_INTERFACE) == 0;
187:
188: if (computeSVUID) {
189: this .name = name;
190: this .access = access;
191: this .interfaces = interfaces;
192: }
193:
194: super .visit(version, access, name, signature, super Name,
195: interfaces);
196: }
197:
198: /*
199: * Visit the methods and get constructor and method information (step 5 and
200: * 7). Also determince if there is a class initializer (step 6).
201: */@Override
202: public MethodVisitor visitMethod(final int access,
203: final String name, final String desc,
204: final String signature, final String[] exceptions) {
205: if (computeSVUID) {
206: if (name.equals("<clinit>")) {
207: hasStaticInitializer = true;
208: }
209: /*
210: * Remembers non private constructors and methods for SVUID
211: * computation For constructor and method modifiers, only the
212: * ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
213: * ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags
214: * are used.
215: */
216: int mods = access
217: & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
218: | Opcodes.ACC_PROTECTED
219: | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
220: | Opcodes.ACC_SYNCHRONIZED
221: | Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_STRICT);
222:
223: // all non private methods
224: if ((access & Opcodes.ACC_PRIVATE) == 0) {
225: if (name.equals("<init>")) {
226: svuidConstructors.add(new Item(name, mods, desc));
227: } else if (!name.equals("<clinit>")) {
228: svuidMethods.add(new Item(name, mods, desc));
229: }
230: }
231: }
232:
233: return cv
234: .visitMethod(access, name, desc, signature, exceptions);
235: }
236:
237: /*
238: * Gets class field information for step 4 of the alogrithm. Also determines
239: * if the class already has a SVUID.
240: */
241: public FieldVisitor visitField(final int access, final String name,
242: final String desc, final String signature,
243: final Object value) {
244: if (computeSVUID) {
245: if (name.equals("serialVersionUID")) {
246: // since the class already has SVUID, we won't be computing it.
247: computeSVUID = false;
248: hasSVUID = true;
249: }
250: /*
251: * Remember field for SVUID computation For field modifiers, only
252: * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
253: * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
254: * computing serialVersionUID values.
255: */
256: int mods = access
257: & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
258: | Opcodes.ACC_PROTECTED
259: | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
260: | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
261:
262: if ((access & Opcodes.ACC_PRIVATE) == 0
263: || (access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0) {
264: svuidFields.add(new Item(name, mods, desc));
265: }
266: }
267:
268: return super .visitField(access, name, desc, signature, value);
269: }
270:
271: /*
272: * Add the SVUID if class doesn't have one
273: */
274: public void visitEnd() {
275: // compute SVUID and add it to the class
276: if (computeSVUID && !hasSVUID) {
277: try {
278: cv.visitField(Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
279: "serialVersionUID", "J", null, new Long(
280: computeSVUID()));
281: } catch (Throwable e) {
282: throw new RuntimeException(
283: "Error while computing SVUID for " + name, e);
284: }
285: }
286:
287: super .visitEnd();
288: }
289:
290: // ------------------------------------------------------------------------
291: // Utility methods
292: // ------------------------------------------------------------------------
293:
294: /**
295: * Returns the value of SVUID if the class doesn't have one already. Please
296: * note that 0 is returned if the class already has SVUID, thus use
297: * <code>isHasSVUID</code> to determine if the class already had an SVUID.
298: *
299: * @return Returns the serial version UID
300: * @throws IOException
301: */
302: protected long computeSVUID() throws IOException {
303: ByteArrayOutputStream bos = null;
304: DataOutputStream dos = null;
305: long svuid = 0;
306:
307: try {
308: bos = new ByteArrayOutputStream();
309: dos = new DataOutputStream(bos);
310:
311: /*
312: * 1. The class name written using UTF encoding.
313: */
314: dos.writeUTF(name.replace('/', '.'));
315:
316: /*
317: * 2. The class modifiers written as a 32-bit integer.
318: */
319: dos
320: .writeInt(access
321: & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
322: | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
323:
324: /*
325: * 3. The name of each interface sorted by name written using UTF
326: * encoding.
327: */
328: Arrays.sort(interfaces);
329: for (int i = 0; i < interfaces.length; i++) {
330: dos.writeUTF(interfaces[i].replace('/', '.'));
331: }
332:
333: /*
334: * 4. For each field of the class sorted by field name (except
335: * private static and private transient fields):
336: *
337: * 1. The name of the field in UTF encoding. 2. The modifiers of the
338: * field written as a 32-bit integer. 3. The descriptor of the field
339: * in UTF encoding
340: *
341: * Note that field signatutes are not dot separated. Method and
342: * constructor signatures are dot separated. Go figure...
343: */
344: writeItems(svuidFields, dos, false);
345:
346: /*
347: * 5. If a class initializer exists, write out the following: 1. The
348: * name of the method, <clinit>, in UTF encoding. 2. The modifier of
349: * the method, java.lang.reflect.Modifier.STATIC, written as a
350: * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
351: * encoding.
352: */
353: if (hasStaticInitializer) {
354: dos.writeUTF("<clinit>");
355: dos.writeInt(Opcodes.ACC_STATIC);
356: dos.writeUTF("()V");
357: } // if..
358:
359: /*
360: * 6. For each non-private constructor sorted by method name and
361: * signature: 1. The name of the method, <init>, in UTF encoding. 2.
362: * The modifiers of the method written as a 32-bit integer. 3. The
363: * descriptor of the method in UTF encoding.
364: */
365: writeItems(svuidConstructors, dos, true);
366:
367: /*
368: * 7. For each non-private method sorted by method name and
369: * signature: 1. The name of the method in UTF encoding. 2. The
370: * modifiers of the method written as a 32-bit integer. 3. The
371: * descriptor of the method in UTF encoding.
372: */
373: writeItems(svuidMethods, dos, true);
374:
375: dos.flush();
376:
377: /*
378: * 8. The SHA-1 algorithm is executed on the stream of bytes
379: * produced by DataOutputStream and produces five 32-bit values
380: * sha[0..4].
381: */
382: byte[] hashBytes = computeSHAdigest(bos.toByteArray());
383:
384: /*
385: * 9. The hash value is assembled from the first and second 32-bit
386: * values of the SHA-1 message digest. If the result of the message
387: * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
388: * five int values named sha, the hash value would be computed as
389: * follows:
390: *
391: * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF) <<
392: * 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
393: * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
394: * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
395: * 56;
396: */
397: for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
398: svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
399: }
400: } finally {
401: // close the stream (if open)
402: if (dos != null) {
403: dos.close();
404: }
405: }
406:
407: return svuid;
408: }
409:
410: /**
411: * Returns the SHA-1 message digest of the given value.
412: *
413: * @param value the value whose SHA message digest must be computed.
414: * @return the SHA-1 message digest of the given value.
415: */
416: protected byte[] computeSHAdigest(final byte[] value) {
417: try {
418: return MessageDigest.getInstance("SHA").digest(value);
419: } catch (Exception e) {
420: throw new UnsupportedOperationException(e);
421: }
422: }
423:
424: /**
425: * Sorts the items in the collection and writes it to the data output stream
426: *
427: * @param itemCollection collection of items
428: * @param dos a <code>DataOutputStream</code> value
429: * @param dotted a <code>boolean</code> value
430: * @exception IOException if an error occurs
431: */
432: private void writeItems(final Collection itemCollection,
433: final DataOutputStream dos, final boolean dotted)
434: throws IOException {
435: int size = itemCollection.size();
436: Item items[] = (Item[]) itemCollection.toArray(new Item[size]);
437: Arrays.sort(items);
438: for (int i = 0; i < size; i++) {
439: dos.writeUTF(items[i].name);
440: dos.writeInt(items[i].access);
441: dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
442: : items[i].desc);
443: }
444: }
445:
446: // ------------------------------------------------------------------------
447: // Inner classes
448: // ------------------------------------------------------------------------
449:
450: static class Item implements Comparable {
451:
452: String name;
453:
454: int access;
455:
456: String desc;
457:
458: Item(final String name, final int access, final String desc) {
459: this .name = name;
460: this .access = access;
461: this .desc = desc;
462: }
463:
464: public int compareTo(final Object o) {
465: Item other = (Item) o;
466: int retVal = name.compareTo(other.name);
467: if (retVal == 0) {
468: retVal = desc.compareTo(other.desc);
469: }
470: return retVal;
471: }
472: }
473: }
|