ObjectStreamClass.java 35 KB
Newer Older
Tom Tromey committed
1 2
/* ObjectStreamClass.java -- Class used to write class information
   about serialized objects.
3
   Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005  Free Software Foundation, Inc.
Tom Tromey committed
4 5 6 7 8 9 10

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
11

Tom Tromey committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.io;

import gnu.java.io.NullOutputStream;
import gnu.java.lang.reflect.TypeSignature;
import gnu.java.security.action.SetAccessibleAction;
import gnu.java.security.provider.Gnu;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.security.Security;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;

63 64 65 66 67 68 69
/**
 * @author Tom Tromey (tromey@redhat.com)
 * @author Jeroen Frijters (jeroen@frijters.net)
 * @author Guilhem Lavaux (guilhem@kaffe.org)
 * @author Michael Koch (konqueror@gmx.de)
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 */
Tom Tromey committed
70 71
public class ObjectStreamClass implements Serializable
{
72 73
  static final ObjectStreamField[] INVALID_FIELDS = new ObjectStreamField[0];

Tom Tromey committed
74 75 76 77 78 79 80 81
  /**
   * Returns the <code>ObjectStreamClass</code> for <code>cl</code>.
   * If <code>cl</code> is null, or is not <code>Serializable</code>,
   * null is returned.  <code>ObjectStreamClass</code>'s are memorized;
   * later calls to this method with the same class will return the
   * same <code>ObjectStreamClass</code> object and no recalculation
   * will be done.
   *
82 83
   * Warning: If this class contains an invalid serialPersistentField arrays
   * lookup will not throw anything. However {@link #getFields()} will return
84
   * an empty array and {@link java.io.ObjectOutputStream#writeObject} will throw an
85 86
   * {@link java.io.InvalidClassException}.
   *
Tom Tromey committed
87 88
   * @see java.io.Serializable
   */
89
  public static ObjectStreamClass lookup(Class<?> cl)
Tom Tromey committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  {
    if (cl == null)
      return null;
    if (! (Serializable.class).isAssignableFrom(cl))
      return null;

    return lookupForClassObject(cl);
  }

  /**
   * This lookup for internal use by ObjectOutputStream.  Suppose
   * we have a java.lang.Class object C for class A, though A is not
   * serializable, but it's okay to serialize C.
   */
  static ObjectStreamClass lookupForClassObject(Class cl)
  {
    if (cl == null)
      return null;

109
    ObjectStreamClass osc = classLookupTable.get(cl);
Tom Tromey committed
110 111 112 113 114

    if (osc != null)
      return osc;
    else
      {
115 116 117
        osc = new ObjectStreamClass(cl);
        classLookupTable.put(cl, osc);
        return osc;
Tom Tromey committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
      }
  }

  /**
   * Returns the name of the class that this
   * <code>ObjectStreamClass</code> represents.
   *
   * @return the name of the class.
   */
  public String getName()
  {
    return name;
  }

  /**
   * Returns the class that this <code>ObjectStreamClass</code>
   * represents.  Null could be returned if this
   * <code>ObjectStreamClass</code> was read from an
   * <code>ObjectInputStream</code> and the class it represents cannot
   * be found or loaded.
   *
   * @see java.io.ObjectInputStream
   */
141
  public Class<?> forClass()
Tom Tromey committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  {
    return clazz;
  }

  /**
   * Returns the serial version stream-unique identifier for the class
   * represented by this <code>ObjectStreamClass</code>.  This SUID is
   * either defined by the class as <code>static final long
   * serialVersionUID</code> or is calculated as specified in
   * Javasoft's "Object Serialization Specification" XXX: add reference
   *
   * @return the serial version UID.
   */
  public long getSerialVersionUID()
  {
    return uid;
  }

  /**
   * Returns the serializable (non-static and non-transient) Fields
   * of the class represented by this ObjectStreamClass.  The Fields
   * are sorted by name.
164 165
   * If fields were obtained using serialPersistentFields and this array
   * is faulty then the returned array of this method will be empty.
Tom Tromey committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
   *
   * @return the fields.
   */
  public ObjectStreamField[] getFields()
  {
    ObjectStreamField[] copy = new ObjectStreamField[ fields.length ];
    System.arraycopy(fields, 0, copy, 0, fields.length);
    return copy;
  }

  // XXX doc
  // Can't do binary search since fields is sorted by name and
  // primitiveness.
  public ObjectStreamField getField (String name)
  {
    for (int i = 0; i < fields.length; i++)
      if (fields[i].getName().equals(name))
183
        return fields[i];
Tom Tromey committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    return null;
  }

  /**
   * Returns a textual representation of this
   * <code>ObjectStreamClass</code> object including the name of the
   * class it represents as well as that class's serial version
   * stream-unique identifier.
   *
   * @see #getSerialVersionUID()
   * @see #getName()
   */
  public String toString()
  {
    return "java.io.ObjectStreamClass< " + name + ", " + uid + " >";
  }

  // Returns true iff the class that this ObjectStreamClass represents
  // has the following method:
  //
  // private void writeObject (ObjectOutputStream)
  //
  // This method is used by the class to override default
  // serialization behavior.
  boolean hasWriteMethod()
  {
    return (flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0;
  }

  // Returns true iff the class that this ObjectStreamClass represents
  // implements Serializable but does *not* implement Externalizable.
  boolean isSerializable()
  {
    return (flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0;
  }


  // Returns true iff the class that this ObjectStreamClass represents
  // implements Externalizable.
  boolean isExternalizable()
  {
    return (flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0;
  }

228 229 230 231 232 233
  // Returns true iff the class that this ObjectStreamClass represents
  // implements Externalizable.
  boolean isEnum()
  {
    return (flags & ObjectStreamConstants.SC_ENUM) != 0;
  }
Tom Tromey committed
234 235 236 237 238 239 240 241 242 243

  // Returns the <code>ObjectStreamClass</code> that represents the
  // class that is the superclass of the class this
  // <code>ObjectStreamClass</code> represents.  If the superclass is
  // not Serializable, null is returned.
  ObjectStreamClass getSuper()
  {
    return superClass;
  }

244 245 246 247 248 249 250 251 252 253 254 255 256 257
  /**
   * returns an array of ObjectStreamClasses that represent the super
   * classes of the class represented by this and the class
   * represented by this itself in order from most super to this.
   * ObjectStreamClass[0] is the highest superclass of this that is
   * serializable.
   *
   * The result of consecutive calls this hierarchy() will be the same
   * array instance.
   *
   * @return an array of ObjectStreamClass representing the
   * super-class hierarchy of serializable classes.
   */
  ObjectStreamClass[] hierarchy()
Tom Tromey committed
258
  {
259
    ObjectStreamClass[] result = hierarchy;
260 261
    if (result == null)
        {
262 263
        int d = 0;

264 265
        for(ObjectStreamClass osc = this; osc != null; osc = osc.getSuper())
          d++;
266

267
        result = new ObjectStreamClass[d];
268

269 270 271 272
        for (ObjectStreamClass osc = this; osc != null; osc = osc.getSuper())
          {
            result[--d] = osc;
          }
273 274

        hierarchy = result;
Tom Tromey committed
275
      }
276
    return result;
Tom Tromey committed
277 278
  }

279 280 281 282
  /**
   * Cache for hierarchy() result.
   */
  private ObjectStreamClass[] hierarchy = null;
Tom Tromey committed
283 284 285 286 287 288 289 290 291 292 293 294

  // Returns an integer that consists of bit-flags that indicate
  // properties of the class represented by this ObjectStreamClass.
  // The bit-flags that could be present are those defined in
  // ObjectStreamConstants that begin with `SC_'
  int getFlags()
  {
    return flags;
  }


  ObjectStreamClass(String name, long uid, byte flags,
295
                    ObjectStreamField[] fields)
Tom Tromey committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  {
    this.name = name;
    this.uid = uid;
    this.flags = flags;
    this.fields = fields;
  }

  /**
   * This method builds the internal description corresponding to a Java Class.
   * As the constructor only assign a name to the current ObjectStreamClass instance,
   * that method sets the serial UID, chose the fields which will be serialized,
   * and compute the position of the fields in the serialized stream.
   *
   * @param cl The Java class which is used as a reference for building the descriptor.
   * @param superClass The descriptor of the super class for this class descriptor.
   * @throws InvalidClassException if an incompatibility between computed UID and
   * already set UID is found.
   */
  void setClass(Class cl, ObjectStreamClass superClass) throws InvalidClassException
315
  {hierarchy = null;
Tom Tromey committed
316 317 318 319 320 321 322 323 324
    this.clazz = cl;

    cacheMethods();

    long class_uid = getClassUID(cl);
    if (uid == 0)
      uid = class_uid;
    else
      {
325 326 327 328 329 330 331 332 333
        // Check that the actual UID of the resolved class matches the UID from
        // the stream. Mismatches for array classes are ignored.
        if (!cl.isArray() && uid != class_uid)
          {
            String msg = cl +
              ": Local class not compatible: stream serialVersionUID="
              + uid + ", local serialVersionUID=" + class_uid;
            throw new InvalidClassException (msg);
          }
Tom Tromey committed
334 335 336 337 338
      }

    isProxyClass = clazz != null && Proxy.isProxyClass(clazz);
    this.superClass = superClass;
    calculateOffsets();
339

Tom Tromey committed
340 341
    try
      {
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        ObjectStreamField[] exportedFields = getSerialPersistentFields (clazz);

        if (exportedFields == null)
          return;

        ObjectStreamField[] newFieldList = new ObjectStreamField[exportedFields.length + fields.length];
        int i, j, k;

        /* We now check the import fields against the exported fields.
         * There should not be contradiction (e.g. int x and String x)
         * but extra virtual fields can be added to the class.
         */

        Arrays.sort(exportedFields);

        i = 0; j = 0; k = 0;
        while (i < fields.length && j < exportedFields.length)
          {
            int comp = fields[i].compareTo(exportedFields[j]);

            if (comp < 0)
              {
                newFieldList[k] = fields[i];
                fields[i].setPersistent(false);
                fields[i].setToSet(false);
                i++;
              }
            else if (comp > 0)
              {
                /* field not found in imported fields. We add it
                 * in the list of supported fields.
                 */
                newFieldList[k] = exportedFields[j];
                newFieldList[k].setPersistent(true);
                newFieldList[k].setToSet(false);
                try
                  {
                    newFieldList[k].lookupField(clazz);
                    newFieldList[k].checkFieldType();
                  }
                catch (NoSuchFieldException _)
                  {
                  }
                j++;
              }
            else
              {
                try
                  {
                    exportedFields[j].lookupField(clazz);
                    exportedFields[j].checkFieldType();
                  }
                catch (NoSuchFieldException _)
                  {
                  }

                if (!fields[i].getType().equals(exportedFields[j].getType()))
                  throw new InvalidClassException
                    ("serialPersistentFields must be compatible with" +
                     " imported fields (about " + fields[i].getName() + ")");
                newFieldList[k] = fields[i];
                fields[i].setPersistent(true);
                i++;
                j++;
              }
            k++;
          }

        if (i < fields.length)
          for (;i<fields.length;i++,k++)
            {
              fields[i].setPersistent(false);
              fields[i].setToSet(false);
              newFieldList[k] = fields[i];
            }
        else
          if (j < exportedFields.length)
            for (;j<exportedFields.length;j++,k++)
              {
                exportedFields[j].setPersistent(true);
                exportedFields[j].setToSet(false);
                newFieldList[k] = exportedFields[j];
              }

        fields = new ObjectStreamField[k];
        System.arraycopy(newFieldList, 0, fields, 0, k);
Tom Tromey committed
428 429 430
      }
    catch (NoSuchFieldException ignore)
      {
431
        return;
Tom Tromey committed
432 433 434
      }
    catch (IllegalAccessException ignore)
      {
435
        return;
Tom Tromey committed
436 437 438 439 440 441
      }
  }

  void setSuperclass (ObjectStreamClass osc)
  {
    superClass = osc;
442
    hierarchy = null;
Tom Tromey committed
443 444 445 446 447 448 449 450 451 452
  }

  void calculateOffsets()
  {
    int i;
    ObjectStreamField field;
    primFieldSize = 0;
    int fcount = fields.length;
    for (i = 0; i < fcount; ++ i)
      {
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        field = fields[i];

        if (! field.isPrimitive())
          break;

        field.setOffset(primFieldSize);
        switch (field.getTypeCode())
          {
          case 'B':
          case 'Z':
            ++ primFieldSize;
            break;
          case 'C':
          case 'S':
            primFieldSize += 2;
            break;
          case 'I':
          case 'F':
            primFieldSize += 4;
            break;
          case 'D':
          case 'J':
            primFieldSize += 8;
            break;
          }
Tom Tromey committed
478 479 480 481 482 483 484
      }

    for (objectFieldCount = 0; i < fcount; ++ i)
      fields[i].setOffset(objectFieldCount++);
  }

  private Method findMethod(Method[] methods, String name, Class[] params,
485
                            Class returnType, boolean mustBePrivate)
Tom Tromey committed
486 487 488 489
  {
outer:
    for (int i = 0; i < methods.length; i++)
    {
490
        final Method m = methods[i];
Tom Tromey committed
491 492 493 494 495 496 497
        int mods = m.getModifiers();
        if (Modifier.isStatic(mods)
            || (mustBePrivate && !Modifier.isPrivate(mods)))
        {
            continue;
        }

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        if (m.getName().equals(name)
           && m.getReturnType() == returnType)
        {
            Class[] mp = m.getParameterTypes();
            if (mp.length == params.length)
            {
                for (int j = 0; j < mp.length; j++)
                {
                    if (mp[j] != params[j])
                    {
                        continue outer;
                    }
                }
                AccessController.doPrivileged(new SetAccessibleAction(m));
                return m;
            }
        }
Tom Tromey committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    }
    return null;
  }

  private static boolean inSamePackage(Class c1, Class c2)
  {
    String name1 = c1.getName();
    String name2 = c2.getName();

    int id1 = name1.lastIndexOf('.');
    int id2 = name2.lastIndexOf('.');

    // Handle the default package
    if (id1 == -1 || id2 == -1)
      return id1 == id2;

    String package1 = name1.substring(0, id1);
    String package2 = name2.substring(0, id2);

    return package1.equals(package2);
  }

  final static Class[] noArgs = new Class[0];

  private static Method findAccessibleMethod(String name, Class from)
  {
    for (Class c = from; c != null; c = c.getSuperclass())
      {
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        try
          {
            Method res = c.getDeclaredMethod(name, noArgs);
            int mods = res.getModifiers();

            if (c == from
                || Modifier.isProtected(mods)
                || Modifier.isPublic(mods)
                || (! Modifier.isPrivate(mods) && inSamePackage(c, from)))
              {
                AccessController.doPrivileged(new SetAccessibleAction(res));
                return res;
              }
          }
        catch (NoSuchMethodException e)
          {
          }
Tom Tromey committed
560 561 562 563 564
      }

    return null;
  }

565 566 567 568 569 570 571 572 573 574 575 576 577 578
  /**
   * Helper routine to check if a class was loaded by boot or
   * application class loader.  Classes for which this is not the case
   * should not be cached since caching prevent class file garbage
   * collection.
   *
   * @param cl a class
   *
   * @return true if cl was loaded by boot or application class loader,
   *         false if cl was loaded by a user class loader.
   */
  private static boolean loadedByBootOrApplicationClassLoader(Class cl)
  {
    ClassLoader l = cl.getClassLoader();
579 580
    return
      (   l == null                             /* boot loader */       )
581
      || (l == ClassLoader.getSystemClassLoader() /* application loader */);
582 583 584
  }

  static Hashtable methodCache = new Hashtable();
585 586 587 588

  static final Class[] readObjectSignature  = { ObjectInputStream.class };
  static final Class[] writeObjectSignature = { ObjectOutputStream.class };

Tom Tromey committed
589 590
  private void cacheMethods()
  {
591 592
    Class cl = forClass();
    Method[] cached = (Method[]) methodCache.get(cl);
593 594 595 596
    if (cached == null)
      {
        cached = new Method[4];
        Method[] methods = cl.getDeclaredMethods();
597

598
        cached[0] = findMethod(methods, "readObject",
599
                               readObjectSignature,
600 601
                               Void.TYPE, true);
        cached[1] = findMethod(methods, "writeObject",
602
                               writeObjectSignature,
603 604 605 606 607 608
                               Void.TYPE, true);

        // readResolve and writeReplace can be in parent classes, as long as they
        // are accessible from this class.
        cached[2] = findAccessibleMethod("readResolve", cl);
        cached[3] = findAccessibleMethod("writeReplace", cl);
609

610 611 612 613 614 615 616 617 618 619 620
        /* put in cache if classes not loaded by user class loader.
         * For a user class loader, the cache may otherwise grow
         * without limit.
         */
        if (loadedByBootOrApplicationClassLoader(cl))
          methodCache.put(cl,cached);
      }
    readObjectMethod   = cached[0];
    writeObjectMethod  = cached[1];
    readResolveMethod  = cached[2];
    writeReplaceMethod = cached[3];
Tom Tromey committed
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  }

  private ObjectStreamClass(Class cl)
  {
    uid = 0;
    flags = 0;
    isProxyClass = Proxy.isProxyClass(cl);

    clazz = cl;
    cacheMethods();
    name = cl.getName();
    setFlags(cl);
    setFields(cl);
    // to those class nonserializable, its uid field is 0
    if ( (Serializable.class).isAssignableFrom(cl) && !isProxyClass)
      uid = getClassUID(cl);
    superClass = lookup(cl.getSuperclass());
  }


  // Sets bits in flags according to features of CL.
  private void setFlags(Class cl)
  {
    if ((java.io.Externalizable.class).isAssignableFrom(cl))
      flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
    else if ((java.io.Serializable.class).isAssignableFrom(cl))
      // only set this bit if CL is NOT Externalizable
      flags |= ObjectStreamConstants.SC_SERIALIZABLE;

    if (writeObjectMethod != null)
      flags |= ObjectStreamConstants.SC_WRITE_METHOD;
652 653 654

    if (cl.isEnum() || cl == Enum.class)
      flags |= ObjectStreamConstants.SC_ENUM;
Tom Tromey committed
655 656
  }

657 658 659 660 661 662 663 664 665 666 667 668 669 670
/* GCJ LOCAL */
  // FIXME: This is a workaround for a fairly obscure bug that happens
  // when reading a Proxy and then writing it back out again.  The
  // result is that the ObjectStreamClass doesn't have its fields set,
  // generating a NullPointerException.  Rather than this kludge we
  // should probably fix the real bug, but it would require a fairly
  // radical reorganization to do so.
  final void ensureFieldsSet(Class cl)
  {
    if (! fieldsSet)
      setFields(cl);
  }
/* END GCJ LOCAL */

Tom Tromey committed
671 672 673 674 675

  // Sets fields to be a sorted array of the serializable fields of
  // clazz.
  private void setFields(Class cl)
  {
676 677 678 679
/* GCJ LOCAL */
    fieldsSet = true;
/* END GCJ LOCAL */

Tom Tromey committed
680 681
    SetAccessibleAction setAccessible = new SetAccessibleAction();

682
    if (!isSerializable() || isExternalizable() || isEnum())
Tom Tromey committed
683
      {
684 685
        fields = NO_FIELDS;
        return;
Tom Tromey committed
686 687 688 689
      }

    try
      {
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        final Field f =
          cl.getDeclaredField("serialPersistentFields");
        setAccessible.setMember(f);
        AccessController.doPrivileged(setAccessible);
        int modifiers = f.getModifiers();

        if (Modifier.isStatic(modifiers)
            && Modifier.isFinal(modifiers)
            && Modifier.isPrivate(modifiers))
          {
            fields = getSerialPersistentFields(cl);
            if (fields != null)
              {
                ObjectStreamField[] fieldsName = new ObjectStreamField[fields.length];
                System.arraycopy(fields, 0, fieldsName, 0, fields.length);

                Arrays.sort (fieldsName, new Comparator() {
                        public int compare(Object o1, Object o2)
                        {
                          ObjectStreamField f1 = (ObjectStreamField)o1;
                          ObjectStreamField f2 = (ObjectStreamField)o2;

                          return f1.getName().compareTo(f2.getName());
                        }
                    });

                for (int i=1; i < fields.length; i++)
                  {
                    if (fieldsName[i-1].getName().equals(fieldsName[i].getName()))
                        {
                            fields = INVALID_FIELDS;
                            return;
                        }
                  }

                Arrays.sort (fields);
                // Retrieve field reference.
                for (int i=0; i < fields.length; i++)
                  {
                    try
                      {
                        fields[i].lookupField(cl);
                      }
                    catch (NoSuchFieldException _)
                      {
                        fields[i].setToSet(false);
                      }
                  }

                calculateOffsets();
                return;
              }
          }
Tom Tromey committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
      }
    catch (NoSuchFieldException ignore)
      {
      }
    catch (IllegalAccessException ignore)
      {
      }

    int num_good_fields = 0;
    Field[] all_fields = cl.getDeclaredFields();

    int modifiers;
    // set non-serializable fields to null in all_fields
    for (int i = 0; i < all_fields.length; i++)
      {
758 759 760 761 762 763
        modifiers = all_fields[i].getModifiers();
        if (Modifier.isTransient(modifiers)
            || Modifier.isStatic(modifiers))
          all_fields[i] = null;
        else
          num_good_fields++;
Tom Tromey committed
764 765 766 767 768 769
      }

    // make a copy of serializable (non-null) fields
    fields = new ObjectStreamField[ num_good_fields ];
    for (int from = 0, to = 0; from < all_fields.length; from++)
      if (all_fields[from] != null)
770 771 772 773 774 775 776
        {
          final Field f = all_fields[from];
          setAccessible.setMember(f);
          AccessController.doPrivileged(setAccessible);
          fields[to] = new ObjectStreamField(all_fields[from]);
          to++;
        }
Tom Tromey committed
777 778 779 780 781 782

    Arrays.sort(fields);
    // Make sure we don't have any duplicate field names
    // (Sun JDK 1.4.1. throws an Internal Error as well)
    for (int i = 1; i < fields.length; i++)
      {
783 784 785
        if(fields[i - 1].getName().equals(fields[i].getName()))
            throw new InternalError("Duplicate field " +
                        fields[i].getName() + " in class " + cl.getName());
Tom Tromey committed
786 787 788 789
      }
    calculateOffsets();
  }

790 791
  static Hashtable uidCache = new Hashtable();

Tom Tromey committed
792 793 794 795
  // Returns the serial version UID defined by class, or if that
  // isn't present, calculates value of serial version UID.
  private long getClassUID(Class cl)
  {
796 797 798
    long result = 0;
    Long cache = (Long) uidCache.get(cl);
    if (cache != null)
799
      result = cache.longValue();
800
    else
Tom Tromey committed
801
      {
802 803 804 805 806 807 808 809
        // Note that we can't use Class.isEnum() here, because that returns
        // false for java.lang.Enum and enum value sub classes.
        if (Enum.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
          {
            // Spec says that enums and dynamic proxies have
            // a serialVersionUID of 0L.
            return 0L;
          }
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        try
          {
            result = getClassUIDFromField(cl);
          }
        catch (NoSuchFieldException ignore)
          {
            try
              {
                result = calculateClassUID(cl);
              }
            catch (NoSuchAlgorithmException e)
              {
                throw new RuntimeException
                  ("The SHA algorithm was not found to use in computing the Serial Version UID for class "
                   + cl.getName(), e);
              }
            catch (IOException ioe)
              {
                throw new RuntimeException(ioe);
              }
          }

        if (loadedByBootOrApplicationClassLoader(cl))
833
          uidCache.put(cl,Long.valueOf(result));
Tom Tromey committed
834
      }
835 836 837 838 839 840 841 842 843 844 845 846
    return result;
  }

  /**
   * Search for a serialVersionUID field in the given class and read
   * its value.
   *
   * @return the contents of the serialVersionUID field
   *
   * @throws NoSuchFieldException if such a field does not exist or is
   * not static, not final, not of type Long or not accessible.
   */
847
  long getClassUIDFromField(Class cl)
848 849 850
    throws NoSuchFieldException
  {
    long result;
851

852
    try
Tom Tromey committed
853
      {
854 855 856 857 858 859 860
        // Use getDeclaredField rather than getField, since serialVersionUID
        // may not be public AND we only want the serialVersionUID of this
        // class, not a superclass or interface.
        final Field suid = cl.getDeclaredField("serialVersionUID");
        SetAccessibleAction setAccessible = new SetAccessibleAction(suid);
        AccessController.doPrivileged(setAccessible);
        int modifiers = suid.getModifiers();
861

862 863 864 865 866 867
        if (Modifier.isStatic(modifiers)
            && Modifier.isFinal(modifiers)
            && suid.getType() == Long.TYPE)
          result = suid.getLong(null);
        else
          throw new NoSuchFieldException();
Tom Tromey committed
868 869 870
      }
    catch (IllegalAccessException ignore)
      {
871
        throw new NoSuchFieldException();
Tom Tromey committed
872 873
      }

874 875
    return result;
  }
Tom Tromey committed
876

877 878 879 880 881 882 883 884 885 886 887 888 889
  /**
   * Calculate class serial version UID for a class that does not
   * define serialVersionUID:
   *
   * @param cl a class
   *
   * @return the calculated serial varsion UID.
   *
   * @throws NoSuchAlgorithmException if SHA algorithm not found
   *
   * @throws IOException if writing to the DigestOutputStream causes
   * an IOException.
   */
890
  long calculateClassUID(Class cl)
891 892
    throws NoSuchAlgorithmException, IOException
  {
893
    long result;
894
    MessageDigest md;
895
    try
896 897
      {
        md = MessageDigest.getInstance("SHA");
Tom Tromey committed
898 899 900
      }
    catch (NoSuchAlgorithmException e)
      {
901 902 903 904 905
        // If a provider already provides SHA, use it; otherwise, use this.
        Gnu gnuProvider = new Gnu();
        Security.addProvider(gnuProvider);
        md = MessageDigest.getInstance("SHA");
      }
906

907 908 909
    DigestOutputStream digest_out =
      new DigestOutputStream(nullOutputStream, md);
    DataOutputStream data_out = new DataOutputStream(digest_out);
910

911
    data_out.writeUTF(cl.getName());
912

913 914 915 916 917
    int modifiers = cl.getModifiers();
    // just look at interesting bits
    modifiers = modifiers & (Modifier.ABSTRACT | Modifier.FINAL
                             | Modifier.INTERFACE | Modifier.PUBLIC);
    data_out.writeInt(modifiers);
918

919 920 921 922 923 924 925 926 927
    // Pretend that an array has no interfaces, because when array
    // serialization was defined (JDK 1.1), arrays didn't have it.
    if (! cl.isArray())
      {
        Class[] interfaces = cl.getInterfaces();
        Arrays.sort(interfaces, interfaceComparator);
        for (int i = 0; i < interfaces.length; i++)
          data_out.writeUTF(interfaces[i].getName());
      }
928

929 930 931 932 933 934 935 936 937 938 939
    Field field;
    Field[] fields = cl.getDeclaredFields();
    Arrays.sort(fields, memberComparator);
    for (int i = 0; i < fields.length; i++)
      {
        field = fields[i];
        modifiers = field.getModifiers();
        if (Modifier.isPrivate(modifiers)
            && (Modifier.isStatic(modifiers)
                || Modifier.isTransient(modifiers)))
          continue;
940

941 942 943 944
        data_out.writeUTF(field.getName());
        data_out.writeInt(modifiers);
        data_out.writeUTF(TypeSignature.getEncodingOfClass (field.getType()));
      }
945

946 947 948 949 950 951
    // write class initializer method if present
    if (VMObjectStreamClass.hasClassInitializer(cl))
      {
        data_out.writeUTF("<clinit>");
        data_out.writeInt(Modifier.STATIC);
        data_out.writeUTF("()V");
Tom Tromey committed
952
      }
953

954 955 956 957 958 959 960 961 962
    Constructor constructor;
    Constructor[] constructors = cl.getDeclaredConstructors();
    Arrays.sort (constructors, memberComparator);
    for (int i = 0; i < constructors.length; i++)
      {
        constructor = constructors[i];
        modifiers = constructor.getModifiers();
        if (Modifier.isPrivate(modifiers))
          continue;
963

964 965
        data_out.writeUTF("<init>");
        data_out.writeInt(modifiers);
966

967 968
        // the replacement of '/' with '.' was needed to make computed
        // SUID's agree with those computed by JDK
969
        data_out.writeUTF
970 971
          (TypeSignature.getEncodingOfConstructor(constructor).replace('/','.'));
      }
972

973 974 975 976
    Method method;
    Method[] methods = cl.getDeclaredMethods();
    Arrays.sort(methods, memberComparator);
    for (int i = 0; i < methods.length; i++)
Tom Tromey committed
977
      {
978 979 980 981
        method = methods[i];
        modifiers = method.getModifiers();
        if (Modifier.isPrivate(modifiers))
          continue;
982

983 984
        data_out.writeUTF(method.getName());
        data_out.writeInt(modifiers);
985

986 987 988 989
        // the replacement of '/' with '.' was needed to make computed
        // SUID's agree with those computed by JDK
        data_out.writeUTF
          (TypeSignature.getEncodingOfMethod(method).replace('/', '.'));
Tom Tromey committed
990
      }
991

992 993 994 995 996 997 998 999
    data_out.close();
    byte[] sha = md.digest();
    result = 0;
    int len = sha.length < 8 ? sha.length : 8;
    for (int i = 0; i < len; i++)
      result += (long) (sha[i] & 0xFF) << (8 * i);

    return result;
Tom Tromey committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  }

  /**
   * Returns the value of CLAZZ's private static final field named
   * `serialPersistentFields'. It performs some sanity checks before
   * returning the real array. Besides, the returned array is a clean
   * copy of the original. So it can be modified.
   *
   * @param clazz Class to retrieve 'serialPersistentFields' from.
   * @return The content of 'serialPersistentFields'.
   */
1011
  private ObjectStreamField[] getSerialPersistentFields(Class clazz)
Tom Tromey committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    throws NoSuchFieldException, IllegalAccessException
  {
    ObjectStreamField[] fieldsArray = null;
    ObjectStreamField[] o;

    // Use getDeclaredField rather than getField for the same reason
    // as above in getDefinedSUID.
    Field f = clazz.getDeclaredField("serialPersistentFields");
    f.setAccessible(true);

    int modifiers = f.getModifiers();
    if (!(Modifier.isStatic(modifiers) &&
1024 1025
          Modifier.isFinal(modifiers) &&
          Modifier.isPrivate(modifiers)))
Tom Tromey committed
1026
      return null;
1027

Tom Tromey committed
1028
    o = (ObjectStreamField[]) f.get(null);
1029

Tom Tromey committed
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    if (o == null)
      return null;

    fieldsArray = new ObjectStreamField[ o.length ];
    System.arraycopy(o, 0, fieldsArray, 0, o.length);

    return fieldsArray;
  }

  /**
   * Returns a new instance of the Class this ObjectStreamClass corresponds
   * to.
   * Note that this should only be used for Externalizable classes.
   *
   * @return A new instance.
   */
  Externalizable newInstance() throws InvalidClassException
  {
    synchronized(this)
    {
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        if (constructor == null)
        {
            try
            {
                final Constructor c = clazz.getConstructor(new Class[0]);

                AccessController.doPrivileged(new PrivilegedAction()
                {
                    public Object run()
                    {
                        c.setAccessible(true);
                        return null;
                    }
                });

                constructor = c;
            }
            catch(NoSuchMethodException x)
            {
                throw new InvalidClassException(clazz.getName(),
                    "No public zero-argument constructor");
            }
        }
Tom Tromey committed
1073 1074 1075 1076
    }

    try
    {
1077
        return (Externalizable)constructor.newInstance();
Tom Tromey committed
1078 1079 1080
    }
    catch(Exception x)
    {
1081 1082 1083
        throw (InvalidClassException)
            new InvalidClassException(clazz.getName(),
                     "Unable to instantiate").initCause(x);
Tom Tromey committed
1084 1085 1086 1087 1088
    }
  }

  public static final ObjectStreamField[] NO_FIELDS = {};

1089 1090
  private static Hashtable<Class,ObjectStreamClass> classLookupTable
    = new Hashtable<Class,ObjectStreamClass>();
Tom Tromey committed
1091 1092 1093 1094 1095 1096 1097
  private static final NullOutputStream nullOutputStream = new NullOutputStream();
  private static final Comparator interfaceComparator = new InterfaceComparator();
  private static final Comparator memberComparator = new MemberComparator();
  private static final
    Class[] writeMethodArgTypes = { java.io.ObjectOutputStream.class };

  private ObjectStreamClass superClass;
1098
  private Class<?> clazz;
Tom Tromey committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  private String name;
  private long uid;
  private byte flags;

  // this field is package protected so that ObjectInputStream and
  // ObjectOutputStream can access it directly
  ObjectStreamField[] fields;

  // these are accessed by ObjectIn/OutputStream
  int primFieldSize = -1;  // -1 if not yet calculated
  int objectFieldCount;

  Method readObjectMethod;
  Method readResolveMethod;
  Method writeReplaceMethod;
  Method writeObjectMethod;
  boolean realClassIsSerializable;
  boolean realClassIsExternalizable;
  ObjectStreamField[] fieldMapping;
  Constructor firstNonSerializableParentConstructor;
  private Constructor constructor;  // default constructor for Externalizable

  boolean isProxyClass = false;

1123 1124 1125 1126 1127
/* GCJ LOCAL */
  // True after setFields() has been called
  private boolean fieldsSet = false;
/* END GCJ LOCAL */

Tom Tromey committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
  // This is probably not necessary because this class is special cased already
  // but it will avoid showing up as a discrepancy when comparing SUIDs.
  private static final long serialVersionUID = -6120832682080437368L;


  // interfaces are compared only by name
  private static final class InterfaceComparator implements Comparator
  {
    public int compare(Object o1, Object o2)
    {
      return ((Class) o1).getName().compareTo(((Class) o2).getName());
    }
  }


  // Members (Methods and Constructors) are compared first by name,
  // conflicts are resolved by comparing type signatures
  private static final class MemberComparator implements Comparator
  {
    public int compare(Object o1, Object o2)
    {
      Member m1 = (Member) o1;
      Member m2 = (Member) o2;

      int comp = m1.getName().compareTo(m2.getName());

      if (comp == 0)
        return TypeSignature.getEncodingOfMember(m1).
1156
          compareTo(TypeSignature.getEncodingOfMember(m2));
Tom Tromey committed
1157 1158 1159 1160 1161
      else
        return comp;
    }
  }
}