001: /*
002: * Copyright 1994-2006 Sun Microsystems, Inc. All Rights Reserved.
003: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004: *
005: * This code is free software; you can redistribute it and/or modify it
006: * under the terms of the GNU General Public License version 2 only, as
007: * published by the Free Software Foundation. Sun designates this
008: * particular file as subject to the "Classpath" exception as provided
009: * by Sun in the LICENSE file that accompanied this code.
010: *
011: * This code is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * version 2 for more details (a copy is included in the LICENSE file that
015: * accompanied this code).
016: *
017: * You should have received a copy of the GNU General Public License version
018: * 2 along with this work; if not, write to the Free Software Foundation,
019: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020: *
021: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022: * CA 95054 USA or visit www.sun.com if you need additional information or
023: * have any questions.
024: */
025:
026: package sun.tools.java;
027:
028: import java.io.IOException;
029: import java.io.DataInputStream;
030: import java.io.OutputStream;
031: import java.io.DataOutputStream;
032: import java.io.ByteArrayInputStream;
033: import java.util.Hashtable;
034: import java.util.Vector;
035: import java.util.Enumeration;
036:
037: /**
038: * WARNING: The contents of this source file are not part of any
039: * supported API. Code that depends on them does so at its own risk:
040: * they are subject to change or removal without notice.
041: */
042: public final class BinaryClass extends ClassDefinition implements
043: Constants {
044: BinaryConstantPool cpool;
045: BinaryAttribute atts;
046: Vector dependencies;
047: private boolean haveLoadedNested = false;
048:
049: /**
050: * Constructor
051: */
052: public BinaryClass(Object source, ClassDeclaration declaration,
053: int modifiers, ClassDeclaration super Class,
054: ClassDeclaration interfaces[], Vector dependencies) {
055: super (source, 0, declaration, modifiers, null, null);
056: this .dependencies = dependencies;
057: this .super Class = super Class;
058: this .interfaces = interfaces;
059: }
060:
061: /**
062: * Flags used by basicCheck() to avoid duplicate calls.
063: * (Part of fix for 4105911)
064: */
065: private boolean basicCheckDone = false;
066: private boolean basicChecking = false;
067:
068: /**
069: * Ready a BinaryClass for further checking. Note that, until recently,
070: * BinaryClass relied on the default basicCheck() provided by
071: * ClassDefinition. The definition here has been added to ensure that
072: * the information generated by collectInheritedMethods is available
073: * for BinaryClasses.
074: */
075: protected void basicCheck(Environment env) throws ClassNotFound {
076: if (tracing)
077: env.dtEnter("BinaryClass.basicCheck: " + getName());
078:
079: // We need to guard against duplicate calls to basicCheck(). They
080: // can lead to calling collectInheritedMethods() for this class
081: // from within a previous call to collectInheritedMethods() for
082: // this class. That is not allowed.
083: // (Part of fix for 4105911)
084: if (basicChecking || basicCheckDone) {
085: if (tracing)
086: env.dtExit("BinaryClass.basicCheck: OK " + getName());
087: return;
088: }
089:
090: if (tracing)
091: env
092: .dtEvent("BinaryClass.basicCheck: CHECKING "
093: + getName());
094: basicChecking = true;
095:
096: super .basicCheck(env);
097:
098: // Collect inheritance information.
099: if (doInheritanceChecks) {
100: collectInheritedMethods(env);
101: }
102:
103: basicCheckDone = true;
104: basicChecking = false;
105: if (tracing)
106: env.dtExit("BinaryClass.basicCheck: " + getName());
107: }
108:
109: /**
110: * Load a binary class
111: */
112: public static BinaryClass load(Environment env, DataInputStream in)
113: throws IOException {
114: return load(env, in, ~(ATT_CODE | ATT_ALLCLASSES));
115: }
116:
117: public static BinaryClass load(Environment env, DataInputStream in,
118: int mask) throws IOException {
119: // Read the header
120: int magic = in.readInt(); // JVM 4.1 ClassFile.magic
121: if (magic != JAVA_MAGIC) {
122: throw new ClassFormatError("wrong magic: " + magic
123: + ", expected " + JAVA_MAGIC);
124: }
125: int minor_version = in.readUnsignedShort(); // JVM 4.1 ClassFile.minor_version
126: int version = in.readUnsignedShort(); // JVM 4.1 ClassFile.major_version
127: if (version < JAVA_MIN_SUPPORTED_VERSION) {
128: throw new ClassFormatError(sun.tools.javac.Main.getText(
129: "javac.err.version.too.old", String
130: .valueOf(version)));
131: } else if ((version > JAVA_MAX_SUPPORTED_VERSION)
132: || (version == JAVA_MAX_SUPPORTED_VERSION && minor_version > JAVA_MAX_SUPPORTED_MINOR_VERSION)) {
133: throw new ClassFormatError(sun.tools.javac.Main.getText(
134: "javac.err.version.too.recent", version + "."
135: + minor_version));
136: }
137:
138: // Read the constant pool
139: BinaryConstantPool cpool = new BinaryConstantPool(in);
140:
141: // The dependencies of this class
142: Vector dependencies = cpool.getDependencies(env);
143:
144: // Read modifiers
145: int classMod = in.readUnsignedShort() & ACCM_CLASS; // JVM 4.1 ClassFile.access_flags
146:
147: // Read the class name - from JVM 4.1 ClassFile.this_class
148: ClassDeclaration classDecl = cpool.getDeclaration(env, in
149: .readUnsignedShort());
150:
151: // Read the super class name (may be null) - from JVM 4.1 ClassFile.super_class
152: ClassDeclaration super ClassDecl = cpool.getDeclaration(env, in
153: .readUnsignedShort());
154:
155: // Read the interface names - from JVM 4.1 ClassFile.interfaces_count
156: ClassDeclaration interfaces[] = new ClassDeclaration[in
157: .readUnsignedShort()];
158: for (int i = 0; i < interfaces.length; i++) {
159: // JVM 4.1 ClassFile.interfaces[]
160: interfaces[i] = cpool.getDeclaration(env, in
161: .readUnsignedShort());
162: }
163:
164: // Allocate the class
165: BinaryClass c = new BinaryClass(null, classDecl, classMod,
166: super ClassDecl, interfaces, dependencies);
167: c.cpool = cpool;
168:
169: // Add any additional dependencies
170: c.addDependency(super ClassDecl);
171:
172: // Read the fields
173: int nfields = in.readUnsignedShort(); // JVM 4.1 ClassFile.fields_count
174: for (int i = 0; i < nfields; i++) {
175: // JVM 4.5 field_info.access_flags
176: int fieldMod = in.readUnsignedShort() & ACCM_FIELD;
177: // JVM 4.5 field_info.name_index
178: Identifier fieldName = cpool.getIdentifier(in
179: .readUnsignedShort());
180: // JVM 4.5 field_info.descriptor_index
181: Type fieldType = cpool.getType(in.readUnsignedShort());
182: BinaryAttribute atts = BinaryAttribute
183: .load(in, cpool, mask);
184: c.addMember(new BinaryMember(c, fieldMod, fieldType,
185: fieldName, atts));
186: }
187:
188: // Read the methods
189: int nmethods = in.readUnsignedShort(); // JVM 4.1 ClassFile.methods_count
190: for (int i = 0; i < nmethods; i++) {
191: // JVM 4.6 method_info.access_flags
192: int methMod = in.readUnsignedShort() & ACCM_METHOD;
193: // JVM 4.6 method_info.name_index
194: Identifier methName = cpool.getIdentifier(in
195: .readUnsignedShort());
196: // JVM 4.6 method_info.descriptor_index
197: Type methType = cpool.getType(in.readUnsignedShort());
198: BinaryAttribute atts = BinaryAttribute
199: .load(in, cpool, mask);
200: c.addMember(new BinaryMember(c, methMod, methType,
201: methName, atts));
202: }
203:
204: // Read the class attributes
205: c.atts = BinaryAttribute.load(in, cpool, mask);
206:
207: // See if the SourceFile is known
208: byte data[] = c.getAttribute(idSourceFile);
209: if (data != null) {
210: DataInputStream dataStream = new DataInputStream(
211: new ByteArrayInputStream(data));
212: // JVM 4.7.2 SourceFile_attribute.sourcefile_index
213: c.source = cpool.getString(dataStream.readUnsignedShort());
214: }
215:
216: // See if the Documentation is know
217: data = c.getAttribute(idDocumentation);
218: if (data != null) {
219: c.documentation = new DataInputStream(
220: new ByteArrayInputStream(data)).readUTF();
221: }
222:
223: // Was it compiled as deprecated?
224: if (c.getAttribute(idDeprecated) != null) {
225: c.modifiers |= M_DEPRECATED;
226: }
227:
228: // Was it synthesized by the compiler?
229: if (c.getAttribute(idSynthetic) != null) {
230: c.modifiers |= M_SYNTHETIC;
231: }
232:
233: return c;
234: }
235:
236: /**
237: * Called when an environment ties a binary definition to a declaration.
238: * At this point, auxiliary definitions may be loaded.
239: */
240:
241: public void loadNested(Environment env) {
242: loadNested(env, 0);
243: }
244:
245: public void loadNested(Environment env, int flags) {
246: // Sanity check.
247: if (haveLoadedNested) {
248: // Duplicate calls most likely should not occur, but they do
249: // in javap. Be tolerant of them for the time being.
250: // throw new CompilerError("multiple loadNested");
251: if (tracing)
252: env.dtEvent("loadNested: DUPLICATE CALL SKIPPED");
253: return;
254: }
255: haveLoadedNested = true;
256: // Read class-nesting information.
257: try {
258: byte data[];
259: data = getAttribute(idInnerClasses);
260: if (data != null) {
261: initInnerClasses(env, data, flags);
262: }
263: } catch (IOException ee) {
264: // The inner classes attribute is not well-formed.
265: // It may, for example, contain no data. Report this.
266: // We used to throw a CompilerError here (bug 4095108).
267: env.error(0, "malformed.attribute", getClassDeclaration(),
268: idInnerClasses);
269: if (tracing)
270: env
271: .dtEvent("loadNested: MALFORMED ATTRIBUTE (InnerClasses)");
272: }
273: }
274:
275: private void initInnerClasses(Environment env, byte data[],
276: int flags) throws IOException {
277: DataInputStream ds = new DataInputStream(
278: new ByteArrayInputStream(data));
279: int nrec = ds.readUnsignedShort(); // InnerClasses_attribute.number_of_classes
280: for (int i = 0; i < nrec; i++) {
281: // For each inner class name transformation, we have a record
282: // with the following fields:
283: //
284: // u2 inner_class_info_index; // CONSTANT_Class_info index
285: // u2 outer_class_info_index; // CONSTANT_Class_info index
286: // u2 inner_name_index; // CONSTANT_Utf8_info index
287: // u2 inner_class_access_flags; // access_flags bitmask
288: //
289: // The spec states that outer_class_info_index is 0 iff
290: // the inner class is not a member of its enclosing class (i.e.
291: // it is a local or anonymous class). The spec also states
292: // that if a class is anonymous then inner_name_index should
293: // be 0.
294: //
295: // Prior to jdk1.2, javac did not implement the spec. Instead
296: // it <em>always</em> set outer_class_info_index to the
297: // enclosing outer class and if the class was anonymous,
298: // it set inner_name_index to be the index of a CONSTANT_Utf8
299: // entry containing the null string "" (idNull). This code is
300: // designed to handle either kind of class file.
301: //
302: // See also the compileClass() method in SourceClass.java.
303:
304: // Read in the inner_class_info
305: // InnerClasses_attribute.classes.inner_class_info_index
306: int inner_index = ds.readUnsignedShort();
307: // could check for zero.
308: ClassDeclaration inner = cpool.getDeclaration(env,
309: inner_index);
310:
311: // Read in the outer_class_info. Note that the index will be
312: // zero if the class is "not a member".
313: ClassDeclaration outer = null;
314: // InnerClasses_attribute.classes.outer_class_info_index
315: int outer_index = ds.readUnsignedShort();
316: if (outer_index != 0) {
317: outer = cpool.getDeclaration(env, outer_index);
318: }
319:
320: // Read in the inner_name_index. This may be zero. An anonymous
321: // class will either have an inner_nm_index of zero (as the spec
322: // dictates) or it will have an inner_nm of idNull (for classes
323: // generated by pre-1.2 compilers). Handle both.
324: Identifier inner_nm = idNull;
325: // InnerClasses_attribute.classes.inner_name_index
326: int inner_nm_index = ds.readUnsignedShort();
327: if (inner_nm_index != 0) {
328: inner_nm = Identifier.lookup(cpool
329: .getString(inner_nm_index));
330: }
331:
332: // Read in the modifiers for the inner class.
333: // InnerClasses_attribute.classes.inner_name_index
334: int mods = ds.readUnsignedShort();
335:
336: // Is the class accessible?
337: // The old code checked for
338: //
339: // (!inner_nm.equals(idNull) && (mods & M_PRIVATE) == 0)
340: //
341: // which we will preserve to keep it working for class files
342: // generated by 1.1 compilers. In addition we check for
343: //
344: // (outer != null)
345: //
346: // as an additional check that only makes sense with 1.2
347: // generated files. Note that it is entirely possible that
348: // the M_PRIVATE bit is always enough. We are being
349: // conservative here.
350: //
351: // The ATT_ALLCLASSES flag causes the M_PRIVATE modifier
352: // to be ignored, and is used by tools such as 'javap' that
353: // wish to examine all classes regardless of the normal access
354: // controls that apply during compilation. Note that anonymous
355: // and local classes are still not considered accessible, though
356: // named local classes in jdk1.1 may slip through. Note that
357: // this accessibility test is an optimization, and it is safe to
358: // err on the side of greater accessibility.
359: boolean accessible = (outer != null)
360: && (!inner_nm.equals(idNull))
361: && ((mods & M_PRIVATE) == 0 || (flags & ATT_ALLCLASSES) != 0);
362:
363: // The reader should note that there has been a significant change
364: // in the way that the InnerClasses attribute is being handled.
365: // In particular, previously the compiler called initInner() for
366: // <em>every</em> inner class. Now the compiler does not call
367: // initInner() if the inner class is inaccessible. This means
368: // that inaccessible inner classes don't have any of the processing
369: // from initInner() done for them: fixing the access flags,
370: // setting outerClass, setting outerMember in their outerClass,
371: // etc. We believe this is fine: if the class is inaccessible
372: // and binary, then everyone who needs to see its internals
373: // has already been compiled. Hopefully.
374:
375: if (accessible) {
376: Identifier nm = Identifier.lookupInner(outer.getName(),
377: inner_nm);
378:
379: // Tell the type module about the nesting relation:
380: Type.tClass(nm);
381:
382: if (inner.equals(getClassDeclaration())) {
383: // The inner class in the record is this class.
384: try {
385: ClassDefinition outerClass = outer
386: .getClassDefinition(env);
387: initInner(outerClass, mods);
388: } catch (ClassNotFound e) {
389: // report the error elsewhere
390: }
391: } else if (outer.equals(getClassDeclaration())) {
392: // The outer class in the record is this class.
393: try {
394: ClassDefinition innerClass = inner
395: .getClassDefinition(env);
396: initOuter(innerClass, mods);
397: } catch (ClassNotFound e) {
398: // report the error elsewhere
399: }
400: }
401: }
402: }
403: }
404:
405: private void initInner(ClassDefinition outerClass, int mods) {
406: if (getOuterClass() != null)
407: return; // already done
408: /******
409: // Maybe set static, protected, or private.
410: if ((modifiers & M_PUBLIC) != 0)
411: mods &= M_STATIC;
412: else
413: mods &= M_PRIVATE | M_PROTECTED | M_STATIC;
414: modifiers |= mods;
415: ******/
416: // For an inner class, the class access may have been weakened
417: // from that originally declared the source. We must take the
418: // actual access permissions against which we check any source
419: // we are currently compiling from the InnerClasses attribute.
420: // We attempt to guard here against bogus combinations of modifiers.
421: if ((mods & M_PRIVATE) != 0) {
422: // Private cannot be combined with public or protected.
423: mods &= ~(M_PUBLIC | M_PROTECTED);
424: } else if ((mods & M_PROTECTED) != 0) {
425: // Protected cannot be combined with public.
426: mods &= ~M_PUBLIC;
427: }
428: if ((mods & M_INTERFACE) != 0) {
429: // All interfaces are implicitly abstract.
430: // All interfaces that are members of a type are implicitly static.
431: mods |= (M_ABSTRACT | M_STATIC);
432: }
433: if (outerClass.isInterface()) {
434: // All types that are members of interfaces are implicitly
435: // public and static.
436: mods |= (M_PUBLIC | M_STATIC);
437: mods &= ~(M_PRIVATE | M_PROTECTED);
438: }
439: modifiers = mods;
440:
441: setOuterClass(outerClass);
442:
443: for (MemberDefinition field = getFirstMember(); field != null; field = field
444: .getNextMember()) {
445: if (field.isUplevelValue()
446: && outerClass.getType().equals(field.getType())
447: && field.getName().toString()
448: .startsWith(prefixThis)) {
449: setOuterMember(field);
450: }
451: }
452: }
453:
454: private void initOuter(ClassDefinition innerClass, int mods) {
455: if (innerClass instanceof BinaryClass)
456: ((BinaryClass) innerClass).initInner(this , mods);
457: addMember(new BinaryMember(innerClass));
458: }
459:
460: /**
461: * Write the class out to a given stream. This function mirrors the loader.
462: */
463: public void write(Environment env, OutputStream out)
464: throws IOException {
465: DataOutputStream data = new DataOutputStream(out);
466:
467: // write out the header
468: data.writeInt(JAVA_MAGIC);
469: data.writeShort(env.getMinorVersion());
470: data.writeShort(env.getMajorVersion());
471:
472: // Write out the constant pool
473: cpool.write(data, env);
474:
475: // Write class information
476: data.writeShort(getModifiers() & ACCM_CLASS);
477: data.writeShort(cpool.indexObject(getClassDeclaration(), env));
478: data.writeShort((getSuperClass() != null) ? cpool.indexObject(
479: getSuperClass(), env) : 0);
480: data.writeShort(interfaces.length);
481: for (int i = 0; i < interfaces.length; i++) {
482: data.writeShort(cpool.indexObject(interfaces[i], env));
483: }
484:
485: // count the fields and the methods
486: int fieldCount = 0, methodCount = 0;
487: for (MemberDefinition f = firstMember; f != null; f = f
488: .getNextMember())
489: if (f.isMethod())
490: methodCount++;
491: else
492: fieldCount++;
493:
494: // write out each the field count, and then each field
495: data.writeShort(fieldCount);
496: for (MemberDefinition f = firstMember; f != null; f = f
497: .getNextMember()) {
498: if (!f.isMethod()) {
499: data.writeShort(f.getModifiers() & ACCM_FIELD);
500: String name = f.getName().toString();
501: String signature = f.getType().getTypeSignature();
502: data.writeShort(cpool.indexString(name, env));
503: data.writeShort(cpool.indexString(signature, env));
504: BinaryAttribute.write(((BinaryMember) f).atts, data,
505: cpool, env);
506: }
507: }
508:
509: // write out each method count, and then each method
510: data.writeShort(methodCount);
511: for (MemberDefinition f = firstMember; f != null; f = f
512: .getNextMember()) {
513: if (f.isMethod()) {
514: data.writeShort(f.getModifiers() & ACCM_METHOD);
515: String name = f.getName().toString();
516: String signature = f.getType().getTypeSignature();
517: data.writeShort(cpool.indexString(name, env));
518: data.writeShort(cpool.indexString(signature, env));
519: BinaryAttribute.write(((BinaryMember) f).atts, data,
520: cpool, env);
521: }
522: }
523:
524: // write out the class attributes
525: BinaryAttribute.write(atts, data, cpool, env);
526: data.flush();
527: }
528:
529: /**
530: * Get the dependencies
531: */
532: public Enumeration getDependencies() {
533: return dependencies.elements();
534: }
535:
536: /**
537: * Add a dependency
538: */
539: public void addDependency(ClassDeclaration c) {
540: if ((c != null) && !dependencies.contains(c)) {
541: dependencies.addElement(c);
542: }
543: }
544:
545: /**
546: * Get the constant pool
547: */
548: public BinaryConstantPool getConstants() {
549: return cpool;
550: }
551:
552: /**
553: * Get a class attribute
554: */
555: public byte getAttribute(Identifier name)[] {
556: for (BinaryAttribute att = atts; att != null; att = att.next) {
557: if (att.name.equals(name)) {
558: return att.data;
559: }
560: }
561: return null;
562: }
563: }
|