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