feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
/**
* The exception thrown when an agent fails to initialize in the target
* Java virtual machine.
*
* <p> This exception is thrown by {@link
* com.sun.tools.attach.VirtualMachine#loadAgent VirtualMachine.loadAgent},
* {@link com.sun.tools.attach.VirtualMachine#loadAgentLibrary
* VirtualMachine.loadAgentLibrary}, {@link
* com.sun.tools.attach.VirtualMachine#loadAgentPath VirtualMachine.loadAgentPath}
* methods if an agent, or agent library, cannot be initialized.
* When thrown by <tt>VirtualMachine.loadAgentLibrary</tt>, or
* <tt>VirtualMachine.loadAgentPath</tt> then the exception encapsulates
* the error returned by the agent's <code>Agent_OnAttach</code> function.
* This error code can be obtained by invoking the {@link #returnValue() returnValue} method.
*/
@jdk.Exported
public class AgentInitializationException extends Exception {
/** use serialVersionUID for interoperability */
static final long serialVersionUID = -1508756333332806353L;
private int returnValue;
/**
* Constructs an <code>AgentInitializationException</code> with
* no detail message.
*/
public AgentInitializationException() {
super();
this.returnValue = 0;
}
/**
* Constructs an <code>AgentInitializationException</code> with
* the specified detail message.
*
* @param s the detail message.
*/
public AgentInitializationException(String s) {
super(s);
this.returnValue = 0;
}
/**
* Constructs an <code>AgentInitializationException</code> with
* the specified detail message and the return value from the
* execution of the agent's <code>Agent_OnAttach</code> function.
*
* @param s the detail message.
* @param returnValue the return value
*/
public AgentInitializationException(String s, int returnValue) {
super(s);
this.returnValue = returnValue;
}
/**
* If the exception was created with the return value from the agent
* <code>Agent_OnAttach</code> function then this returns that value,
* otherwise returns <code>0</code>. </p>
*
* @return the return value
*/
public int returnValue() {
return returnValue;
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
/**
* The exception thrown when an agent cannot be loaded into the target
* Java virtual machine.
*
* <p> This exception is thrown by {@link
* com.sun.tools.attach.VirtualMachine#loadAgent VirtualMachine.loadAgent} or
* {@link com.sun.tools.attach.VirtualMachine#loadAgentLibrary
* VirtualMachine.loadAgentLibrary}, {@link
* com.sun.tools.attach.VirtualMachine#loadAgentPath loadAgentPath} methods
* if the agent, or agent library, cannot be loaded.
*/
@jdk.Exported
public class AgentLoadException extends Exception {
/** use serialVersionUID for interoperability */
static final long serialVersionUID = 688047862952114238L;
/**
* Constructs an <code>AgentLoadException</code> with
* no detail message.
*/
public AgentLoadException() {
super();
}
/**
* Constructs an <code>AgentLoadException</code> with
* the specified detail message.
*
* @param s the detail message.
*/
public AgentLoadException(String s) {
super(s);
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import com.sun.tools.attach.spi.AttachProvider; // for javadoc
/**
* Thrown by {@link com.sun.tools.attach.VirtualMachine#attach
* VirtalMachine.attach} when attempting to attach to a Java virtual machine
* for which a compatible {@link com.sun.tools.attach.spi.AttachProvider
* AttachProvider} does not exist. It is also thrown by {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine
* AttachProvider.attachVirtualMachine} if the provider attempts to
* attach to a Java virtual machine with which it not comptatible.
*/
@jdk.Exported
public class AttachNotSupportedException extends Exception {
/** use serialVersionUID for interoperability */
static final long serialVersionUID = 3391824968260177264L;
/**
* Constructs an <code>AttachNotSupportedException</code> with
* no detail message.
*/
public AttachNotSupportedException() {
super();
}
/**
* Constructs an <code>AttachNotSupportedException</code> with
* the specified detail message.
*
* @param s the detail message.
*/
public AttachNotSupportedException(String s) {
super(s);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import java.io.IOException;
/**
* Exception type to signal that an attach operation failed in the target VM.
*
* <p> This exception can be thrown by the various operations of
* {@link com.sun.tools.attach.VirtualMachine} when the operation
* fails in the target VM. If there is a communication error,
* a regular IOException will be thrown.
*
* @since 1.9
*/
@jdk.Exported
public class AttachOperationFailedException extends IOException {
private static final long serialVersionUID = 2140308168167478043L;
/**
* Constructs an <code>AttachOperationFailedException</code> with
* the specified detail message.
*
* @param s the detail message.
*/
public AttachOperationFailedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
/**
* When a {@link java.lang.SecurityManager SecurityManager} set, this
* is the permission which will be checked when code invokes {@link
* VirtualMachine#attach VirtalMachine.attach} to attach to a target virtual
* machine.
* This permission is also checked when an {@link
* com.sun.tools.attach.spi.AttachProvider AttachProvider} is created. </p>
*
* <p> An <code>AttachPermission</code> object contains a name (also referred
* to as a "target name") but no actions list; you either have the
* named permission or you don't.
* The following table provides a summary description of what the
* permission allows, and discusses the risks of granting code the
* permission.
* <P>
* <table border=1 cellpadding=5 summary="Table shows permission
* target name, what the permission allows, and associated risks">
* <tr>
* <th>Permission Target Name</th>
* <th>What the Permission Allows</th>
* <th>Risks of Allowing this Permission</th>
* </tr>
*
* <tr>
* <td>attachVirtualMachine</td>
* <td>Ability to attach to another Java virtual machine and load agents
* into that VM.
* </td>
* <td>This allows an attacker to control the target VM which can potentially
* cause it to misbehave.
* </td>
* </tr>
*
* <tr>
* <td>createAttachProvider</td>
* <td>Ability to create an <code>AttachProvider</code> instance.
* </td>
* <td>This allows an attacker to create an AttachProvider which can
* potentially be used to attach to other Java virtual machines.
* </td>
* </tr>
*
* </table>
* <p>
* Programmers do not normally create AttachPermission objects directly.
* Instead they are created by the security policy code based on reading
* the security policy file.
*
* @see com.sun.tools.attach.VirtualMachine
* @see com.sun.tools.attach.spi.AttachProvider
*/
@jdk.Exported
public final class AttachPermission extends java.security.BasicPermission {
/** use serialVersionUID for interoperability */
static final long serialVersionUID = -4619447669752976181L;
/**
* Constructs a new AttachPermission object.
*
* @param name Permission name. Must be either "attachVirtualMachine",
* or "createAttachProvider".
*
* @throws NullPointerException if name is <code>null</code>.
* @throws IllegalArgumentException if the name is invalid.
*/
public AttachPermission(String name) {
super(name);
if (!name.equals("attachVirtualMachine") && !name.equals("createAttachProvider")) {
throw new IllegalArgumentException("name: " + name);
}
}
/**
* Constructs a new AttachPermission object.
*
* @param name Permission name. Must be either "attachVirtualMachine",
* or "createAttachProvider".
*
* @param actions Not used and should be <code>null</code>, or
* the empty string.
*
* @throws NullPointerException if name is <code>null</code>.
* @throws IllegalArgumentException if arguments are invalid.
*/
public AttachPermission(String name, String actions) {
super(name);
if (!name.equals("attachVirtualMachine") && !name.equals("createAttachProvider")) {
throw new IllegalArgumentException("name: " + name);
}
if (actions != null && actions.length() > 0) {
throw new IllegalArgumentException("actions: " + actions);
}
}
}

View File

@@ -0,0 +1,723 @@
/*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import com.sun.tools.attach.spi.AttachProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.io.IOException;
/**
* A Java virtual machine.
*
* <p> A <code>VirtualMachine</code> represents a Java virtual machine to which this
* Java virtual machine has attached. The Java virtual machine to which it is
* attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>.
* An application (typically a tool such as a managemet console or profiler) uses a
* VirtualMachine to load an agent into the target VM. For example, a profiler tool
* written in the Java Language might attach to a running application and load its
* profiler agent to profile the running application. </p>
*
* <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method
* with an identifier that identifies the target virtual machine. The identifier is
* implementation-dependent but is typically the process identifier (or pid) in
* environments where each Java virtual machine runs in its own operating system process.
* Alternatively, a <code>VirtualMachine</code> instance is obtained by invoking the
* {@link #attach(VirtualMachineDescriptor) attach} method with a {@link
* com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained
* from the list of virtual machine descriptors returned by the {@link #list list} method.
* Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent},
* {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath}
* methods are used to load agents into target virtual machine. The {@link
* #loadAgent loadAgent} method is used to load agents that are written in the Java
* Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See
* {@link java.lang.instrument} for a detailed description on how these agents
* are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and
* {@link #loadAgentPath loadAgentPath} methods are used to load agents that
* are deployed either in a dynamic library or statically linked into the VM and make use of the <a
* href="../../../../../../../../technotes/guides/jvmti/index.html">JVM Tools
* Interface</a>. </p>
*
* <p> In addition to loading agents a VirtualMachine provides read access to the
* {@link java.lang.System#getProperties() system properties} in the target VM.
* This can be useful in some environments where properties such as
* <code>java.home</code>, <code>os.name</code>, or <code>os.arch</code> are
* used to construct the path to agent that will be loaded into the target VM.
*
* <p> The following example demonstrates how VirtualMachine may be used:</p>
*
* <pre>
*
* // attach to target VM
* VirtualMachine vm = VirtualMachine.attach("2177");
*
* // start management agent
* Properties props = new Properties();
* props.put("com.sun.management.jmxremote.port", "5000");
* vm.startManagementAgent(props);
*
* // detach
* vm.detach();
*
* </pre>
*
* <p> In this example we attach to a Java virtual machine that is identified by
* the process identifier <code>2177</code>. Then the JMX management agent is
* started in the target process using the supplied arguments. Finally, the
* client detaches from the target VM. </p>
*
* <p> A VirtualMachine is safe for use by multiple concurrent threads. </p>
*
* @since 1.6
*/
@jdk.Exported
public abstract class VirtualMachine {
private AttachProvider provider;
private String id;
private volatile int hash; // 0 => not computed
/**
* Initializes a new instance of this class.
*
* @param provider
* The attach provider creating this class.
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @throws NullPointerException
* If <code>provider</code> or <code>id</code> is <code>null</code>.
*/
protected VirtualMachine(AttachProvider provider, String id) {
if (provider == null) {
throw new NullPointerException("provider cannot be null");
}
if (id == null) {
throw new NullPointerException("id cannot be null");
}
this.provider = provider;
this.id = id;
}
/**
* Return a list of Java virtual machines.
*
* <p> This method returns a list of Java {@link
* com.sun.tools.attach.VirtualMachineDescriptor} elements.
* The list is an aggregation of the virtual machine
* descriptor lists obtained by invoking the {@link
* com.sun.tools.attach.spi.AttachProvider#listVirtualMachines
* listVirtualMachines} method of all installed
* {@link com.sun.tools.attach.spi.AttachProvider attach providers}.
* If there are no Java virtual machines known to any provider
* then an empty list is returned.
*
* @return The list of virtual machine descriptors.
*/
public static List<VirtualMachineDescriptor> list() {
ArrayList<VirtualMachineDescriptor> l =
new ArrayList<VirtualMachineDescriptor>();
List<AttachProvider> providers = AttachProvider.providers();
for (AttachProvider provider: providers) {
l.addAll(provider.listVirtualMachines());
}
return l;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method obtains the list of attach providers by invoking the
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} method. It then iterates overs the list
* and invokes each provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String)
* attachVirtualMachine} method in turn. If a provider successfully
* attaches then the iteration terminates, and the VirtualMachine created
* by the provider that successfully attached is returned by this method.
* If the <code>attachVirtualMachine</code> method of all providers throws
* {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}
* then this method also throws <code>AttachNotSupportedException</code>.
* This means that <code>AttachNotSupportedException</code> is thrown when
* the identifier provided to this method is invalid, or the identifier
* corresponds to a Java virtual machine that does not exist, or none
* of the providers can attach to it. This exception is also thrown if
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} returns an empty list. </p>
*
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the <code>attachVirtualmachine</code> method of all installed
* providers throws <code>AttachNotSupportedException</code>, or
* there aren't any providers installed.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>id</code> is <code>null</code>.
*/
public static VirtualMachine attach(String id)
throws AttachNotSupportedException, IOException
{
if (id == null) {
throw new NullPointerException("id cannot be null");
}
List<AttachProvider> providers = AttachProvider.providers();
if (providers.size() == 0) {
throw new AttachNotSupportedException("no providers installed");
}
AttachNotSupportedException lastExc = null;
for (AttachProvider provider: providers) {
try {
return provider.attachVirtualMachine(id);
} catch (AttachNotSupportedException x) {
lastExc = x;
}
}
throw lastExc;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method first invokes the {@link
* com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
* of the given virtual machine descriptor to obtain the attach provider. It
* then invokes the attach provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor)
* attachVirtualMachine} to attach to the target VM.
*
* @param vmd
* The virtual machine descriptor.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the attach provider's <code>attachVirtualmachine</code>
* throws <code>AttachNotSupportedException</code>.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>vmd</code> is <code>null</code>.
*/
public static VirtualMachine attach(VirtualMachineDescriptor vmd)
throws AttachNotSupportedException, IOException
{
return vmd.provider().attachVirtualMachine(vmd);
}
/**
* Detach from the virtual machine.
*
* <p> After detaching from the virtual machine, any further attempt to invoke
* operations on that virtual machine will cause an {@link java.io.IOException
* IOException} to be thrown. If an operation (such as {@link #loadAgent
* loadAgent} for example) is in progress when this method is invoked then
* the behaviour is implementation dependent. In other words, it is
* implementation specific if the operation completes or throws
* <tt>IOException</tt>.
*
* <p> If already detached from the virtual machine then invoking this
* method has no effect. </p>
*
* @throws IOException
* If an I/O error occurs
*/
public abstract void detach() throws IOException;
/**
* Returns the provider that created this virtual machine.
*
* @return The provider that created this virtual machine.
*/
public final AttachProvider provider() {
return provider;
}
/**
* Returns the identifier for this Java virtual machine.
*
* @return The identifier for this Java virtual machine.
*/
public final String id() {
return id;
}
/**
* Loads an agent library.
*
* <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM
* TI</a> client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, it may be statically linked into the VM.
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the <code>Agent_OnAttach</code> function
* or, for a statically linked agent named 'L', the <code>Agent_OnAttach_L</code> function
* as specified in the
* <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools
* Interface</a> specification. Note that the <code>Agent_OnAttach[_L]</code>
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the name of the agent library. It is interpreted
* in the target virtual machine in an implementation-dependent manner. Typically an
* implementation will expand the library name into an operating system specific file
* name. For example, on UNIX systems, the name <tt>L</tt> might be expanded to
* <tt>libL.so</tt>, and located using the search path specified by the
* <tt>LD_LIBRARY_PATH</tt> environment variable. If the agent named 'L' is
* statically linked into the VM then the VM must export a function named
* <code>Agent_OnAttach_L</code>.</p>
*
* <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentLibrary
* The name of the agent library.
*
* @param options
* The options to provide to the <code>Agent_OnAttach[_L]</code>
* function (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentLibrary</code> is <code>null</code>.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentLibrary(String agentLibrary, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent library.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary,&nbsp;null);
* </tt></blockquote>
*
* @param agentLibrary
* The name of the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentLibrary</code> is <code>null</code>.
*/
public void loadAgentLibrary(String agentLibrary)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentLibrary(agentLibrary, null);
}
/**
* Load a native agent library by full pathname.
*
* <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM
* TI</a> client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, the native
* library specified by the agentPath parameter may be statically
* linked with the VM. The parsing of the agentPath parameter into
* a statically linked library name is done in a platform
* specific manner in the VM. For example, in UNIX, an agentPath parameter
* of <code>/a/b/libL.so</code> would name a library 'L'.
*
* See the JVM TI Specification for more details.
*
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the <code>Agent_OnAttach</code>
* function or, for a statically linked agent named 'L', the
* <code>Agent_OnAttach_L</code> function as specified in the
* <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools
* Interface</a> specification.
* Note that the <code>Agent_OnAttach[_L]</code>
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the absolute path from which to load the
* agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name
* is not expanded in the target virtual machine. </p>
*
* <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentPath
* The full path of the agent library.
*
* @param options
* The options to provide to the <code>Agent_OnAttach[_L]</code>
* function (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentPath</code> is <code>null</code>.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentPath(String agentPath, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Load a native agent library by full pathname.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary,&nbsp;null);
* </tt></blockquote>
*
* @param agentPath
* The full path to the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentPath</code> is <code>null</code>.
*/
public void loadAgentPath(String agentPath)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentPath(agentPath, null);
}
/**
* Loads an agent.
*
* <p> The agent provided to this method is a path name to a JAR file on the file
* system of the target virtual machine. This path is passed to the target virtual
* machine where it is interpreted. The target virtual machine attempts to start
* the agent as specified by the {@link java.lang.instrument} specification.
* That is, the specified JAR file is added to the system class path (of the target
* virtual machine), and the <code>agentmain</code> method of the agent class, specified
* by the <code>Agent-Class</code> attribute in the JAR manifest, is invoked. This
* method completes when the <code>agentmain</code> method completes.
*
* @param agent
* Path to the JAR file containing the agent.
*
* @param options
* The options to provide to the agent's <code>agentmain</code>
* method (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the <code>agentmain</code> throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agent</code> is <code>null</code>.
*/
public abstract void loadAgent(String agent, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgent(String, String) loadAgent}(agent,&nbsp;null);
* </tt></blockquote>
*
* @param agent
* Path to the JAR file containing the agent.
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the <code>agentmain</code> throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agent</code> is <code>null</code>.
*/
public void loadAgent(String agent)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgent(agent, null);
}
/**
* Returns the current system properties in the target virtual machine.
*
* <p> This method returns the system properties in the target virtual
* machine. Properties whose key or value is not a <tt>String</tt> are
* omitted. The method is approximately equivalent to the invocation of the
* method {@link java.lang.System#getProperties System.getProperties}
* in the target virtual machine except that properties with a key or
* value that is not a <tt>String</tt> are not included.
*
* <p> This method is typically used to decide which agent to load into
* the target virtual machine with {@link #loadAgent loadAgent}, or
* {@link #loadAgentLibrary loadAgentLibrary}. For example, the
* <code>java.home</code> or <code>user.dir</code> properties might be
* use to create the path to the agent library or JAR file.
*
* @return The system properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @see java.lang.System#getProperties
* @see #loadAgentLibrary
* @see #loadAgent
*/
public abstract Properties getSystemProperties() throws IOException;
/**
* Returns the current <i>agent properties</i> in the target virtual
* machine.
*
* <p> The target virtual machine can maintain a list of properties on
* behalf of agents. The manner in which this is done, the names of the
* properties, and the types of values that are allowed, is implementation
* specific. Agent properties are typically used to store communication
* end-points and other agent configuration details. For example, a debugger
* agent might create an agent property for its transport address.
*
* <p> This method returns the agent properties whose key and value is a
* <tt>String</tt>. Properties whose key or value is not a <tt>String</tt>
* are omitted. If there are no agent properties maintained in the target
* virtual machine then an empty property list is returned.
*
* @return The agent properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*/
public abstract Properties getAgentProperties() throws IOException;
/**
* Starts the JMX management agent in the target virtual machine.
*
* <p> The configuration properties are the same as those specified on
* the command line when starting the JMX management agent. In the same
* way as on the command line, you need to specify at least the
* {@code com.sun.management.jmxremote.port} property.
*
* <p> See the online documentation for <a
* href="../../../../../../../../technotes/guides/management/agent.html">
* Monitoring and Management Using JMX Technology</a> for further details.
*
* @param agentProperties
* A Properties object containing the configuration properties
* for the agent.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @throws IllegalArgumentException
* If keys or values in agentProperties are invalid.
*
* @throws NullPointerException
* If agentProperties is null.
*
* @since 1.8
*/
public abstract void startManagementAgent(Properties agentProperties) throws IOException;
/**
* Starts the local JMX management agent in the target virtual machine.
*
* <p> See the online documentation for <a
* href="../../../../../../../../technotes/guides/management/agent.html">
* Monitoring and Management Using JMX Technology</a> for further details.
*
* @return The String representation of the local connector's service address.
* The value can be parsed by the
* {@link javax.management.remote.JMXServiceURL#JMXServiceURL(String)}
* constructor.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @since 1.8
*/
public abstract String startLocalManagementAgent() throws IOException;
/**
* Returns a hash-code value for this VirtualMachine. The hash
* code is based upon the VirtualMachine's components, and satifies
* the general contract of the {@link java.lang.Object#hashCode()
* Object.hashCode} method.
*
* @return A hash-code value for this virtual machine
*/
public int hashCode() {
if (hash != 0) {
return hash;
}
hash = provider.hashCode() * 127 + id.hashCode();
return hash;
}
/**
* Tests this VirtualMachine for equality with another object.
*
* <p> If the given object is not a VirtualMachine then this
* method returns <tt>false</tt>. For two VirtualMachines to
* be considered equal requires that they both reference the same
* provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p>
*
* <p> This method satisfies the general contract of the {@link
* java.lang.Object#equals(Object) Object.equals} method. </p>
*
* @param ob The object to which this object is to be compared
*
* @return <tt>true</tt> if, and only if, the given object is
* a VirtualMachine that is equal to this
* VirtualMachine.
*/
public boolean equals(Object ob) {
if (ob == this)
return true;
if (!(ob instanceof VirtualMachine))
return false;
VirtualMachine other = (VirtualMachine)ob;
if (other.provider() != this.provider()) {
return false;
}
if (!other.id().equals(this.id())) {
return false;
}
return true;
}
/**
* Returns the string representation of the <code>VirtualMachine</code>.
*/
public String toString() {
return provider.toString() + ": " + id;
}
}

View File

@@ -0,0 +1,204 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import com.sun.tools.attach.spi.AttachProvider;
/**
* Describes a Java virtual machine.
*
* <p> A <code>VirtualMachineDescriptor</code> is a container class used to
* describe a Java virtual machine. It encapsulates an identifier that identifies
* a target virtual machine, and a reference to the {@link
* com.sun.tools.attach.spi.AttachProvider AttachProvider} that should be used
* when attempting to attach to the virtual machine. The identifier is
* implementation-dependent but is typically the process identifier (or pid)
* environments where each Java virtual machine runs in its own operating system
* process. </p>
*
* <p> A <code>VirtualMachineDescriptor</code> also has a {@link #displayName() displayName}.
* The display name is typically a human readable string that a tool might
* display to a user. For example, a tool that shows a list of Java
* virtual machines running on a system might use the display name rather
* than the identifier. A <code>VirtualMachineDescriptor</code> may be
* created without a <i>display name</i>. In that case the identifier is
* used as the <i>display name</i>.
*
* <p> <code>VirtualMachineDescriptor</code> instances are typically created by
* invoking the {@link com.sun.tools.attach.VirtualMachine#list VirtualMachine.list()}
* method. This returns the complete list of descriptors to describe the
* Java virtual machines known to all installed {@link
* com.sun.tools.attach.spi.AttachProvider attach providers}.
*
* @since 1.6
*/
@jdk.Exported
public class VirtualMachineDescriptor {
private AttachProvider provider;
private String id;
private String displayName;
private volatile int hash; // 0 => not computed
/**
* Creates a virtual machine descriptor from the given components.
*
* @param provider The AttachProvider to attach to the Java virtual machine.
* @param id The virtual machine identifier.
* @param displayName The display name.
*
* @throws NullPointerException
* If any of the arguments are <code>null</code>
*/
public VirtualMachineDescriptor(AttachProvider provider, String id, String displayName) {
if (provider == null) {
throw new NullPointerException("provider cannot be null");
}
if (id == null) {
throw new NullPointerException("identifier cannot be null");
}
if (displayName == null) {
throw new NullPointerException("display name cannot be null");
}
this.provider = provider;
this.id = id;
this.displayName = displayName;
}
/**
* Creates a virtual machine descriptor from the given components.
*
* <p> This convenience constructor works as if by invoking the
* three-argument constructor as follows:
*
* <blockquote><tt>
* new&nbsp;{@link #VirtualMachineDescriptor(AttachProvider, String, String)
* VirtualMachineDescriptor}(provider, &nbsp;id, &nbsp;id);
* </tt></blockquote>
*
* <p> That is, it creates a virtual machine descriptor such that
* the <i>display name</i> is the same as the virtual machine
* identifier.
*
* @param provider The AttachProvider to attach to the Java virtual machine.
* @param id The virtual machine identifier.
*
* @throws NullPointerException
* If <tt>provider</tt> or <tt>id</tt> is <tt>null</tt>.
*/
public VirtualMachineDescriptor(AttachProvider provider, String id) {
this(provider, id, id);
}
/**
* Return the <code>AttachProvider</code> that this descriptor references.
*
* @return The <code>AttachProvider</code> that this descriptor references.
*/
public AttachProvider provider() {
return provider;
}
/**
* Return the identifier component of this descriptor.
*
* @return The identifier component of this descriptor.
*/
public String id() {
return id;
}
/**
* Return the <i>display name</i> component of this descriptor.
*
* @return The display name component of this descriptor.
*/
public String displayName() {
return displayName;
}
/**
* Returns a hash-code value for this VirtualMachineDescriptor. The hash
* code is based upon the descriptor's components, and satifies
* the general contract of the {@link java.lang.Object#hashCode()
* Object.hashCode} method.
*
* @return A hash-code value for this descriptor.
*/
public int hashCode() {
if (hash != 0) {
return hash;
}
hash = provider.hashCode() * 127 + id.hashCode();
return hash;
}
/**
* Tests this VirtualMachineDescriptor for equality with another object.
*
* <p> If the given object is not a VirtualMachineDescriptor then this
* method returns <tt>false</tt>. For two VirtualMachineDescriptors to
* be considered equal requires that they both reference the same
* provider, and their {@link #id() identifiers} are equal. </p>
*
* <p> This method satisfies the general contract of the {@link
* java.lang.Object#equals(Object) Object.equals} method. </p>
*
* @param ob The object to which this object is to be compared
*
* @return <tt>true</tt> if, and only if, the given object is
* a VirtualMachineDescriptor that is equal to this
* VirtualMachineDescriptor.
*/
public boolean equals(Object ob) {
if (ob == this)
return true;
if (!(ob instanceof VirtualMachineDescriptor))
return false;
VirtualMachineDescriptor other = (VirtualMachineDescriptor)ob;
if (other.provider() != this.provider()) {
return false;
}
if (!other.id().equals(this.id())) {
return false;
}
return true;
}
/**
* Returns the string representation of the <code>VirtualMachineDescriptor</code>.
*/
public String toString() {
String s = provider.toString() + ": " + id;
if (displayName != id) {
s += " " + displayName;
}
return s;
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Provides the API to attach to a Java<sup><font size=-2>TM</font></sup>
* virtual machine.
* <p>
* A tool, written in the Java Language, uses this API to attach to a target
* virtual machine (VM) and load its tool agent into the target VM. For
* example, a management console might have a management agent which it uses
* to obtain management information from instrumented objects in a Java
* virtual machine. If the management console is required to manage
* an application that is running in a virtual machine that does not include
* the management agent, then this API can be used to attach to the target
* VM and load the agent.
*
* @since 1.6
*/
@jdk.Exported
package com.sun.tools.attach;

View File

@@ -0,0 +1,274 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach.spi;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import com.sun.tools.attach.AttachPermission;
import com.sun.tools.attach.AttachNotSupportedException;
import java.util.ServiceLoader;
/**
* Attach provider class for attaching to a Java virtual machine.
*
* <p> An attach provider is a concrete subclass of this class that has a
* zero-argument constructor and implements the abstract methods specified
* below. </p>
*
* <p> An attach provider implementation is typically tied to a Java virtual
* machine implementation, version, or even mode of operation. That is, a specific
* provider implementation will typically only be capable of attaching to
* a specific Java virtual machine implementation or version. For example, Sun's
* JDK implementation ships with provider implementations that can only attach to
* Sun's <i>HotSpot</i> virtual machine. In general, if an environment
* consists of Java virtual machines of different versions and from different
* vendors then there will be an attach provider implementation for each
* <i>family</i> of implementations or versions. </p>
*
* <p> An attach provider is identified by its {@link #name <i>name</i>} and
* {@link #type <i>type</i>}. The <i>name</i> is typically, but not required to
* be, a name that corresponds to the VM vendor. The Sun JDK implementation,
* for example, ships with attach providers that use the name <i>"sun"</i>. The
* <i>type</i> typically corresponds to the attach mechanism. For example, an
* implementation that uses the Doors inter-process communication mechanism
* might use the type <i>"doors"</i>. The purpose of the name and type is to
* identify providers in environments where there are multiple providers
* installed. </p>
*
* <p> AttachProvider implementations are loaded and instantiated at the first
* invocation of the {@link #providers() providers} method. This method
* attempts to load all provider implementations that are installed on the
* platform. </p>
*
* <p> All of the methods in this class are safe for use by multiple
* concurrent threads. </p>
*
* @since 1.6
*/
@jdk.Exported
public abstract class AttachProvider {
private static final Object lock = new Object();
private static List<AttachProvider> providers = null;
/**
* Initializes a new instance of this class. </p>
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("createAttachProvider")</tt>
*/
protected AttachProvider() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new AttachPermission("createAttachProvider"));
}
/**
* Return this provider's name. </p>
*
* @return The name of this provider
*/
public abstract String name();
/**
* Return this provider's type. </p>
*
* @return The type of this provider
*/
public abstract String type();
/**
* Attaches to a Java virtual machine.
*
* <p> A Java virtual machine is identified by an abstract identifier. The
* nature of this identifier is platform dependent but in many cases it will be the
* string representation of the process identifier (or pid). </p>
*
* <p> This method parses the identifier and maps the identifier to a Java
* virtual machine (in an implementation dependent manner). If the identifier
* cannot be parsed by the provider then an {@link
* com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}
* is thrown. Once parsed this method attempts to attach to the Java virtual machine.
* If the provider detects that the identifier corresponds to a Java virtual machine
* that does not exist, or it corresponds to a Java virtual machine that does not support
* the attach mechanism implemented by this provider, or it detects that the
* Java virtual machine is a version to which this provider cannot attach, then
* an <code>AttachNotSupportedException</code> is thrown. </p>
*
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @return VirtualMachine representing the target virtual machine.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or other permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the identifier cannot be parsed, or it corresponds to
* to a Java virtual machine that does not exist, or it
* corresponds to a Java virtual machine which this
* provider cannot attach.
*
* @throws IOException
* If some other I/O error occurs
*
* @throws NullPointerException
* If <code>id</code> is <code>null</code>
*/
public abstract VirtualMachine attachVirtualMachine(String id)
throws AttachNotSupportedException, IOException;
/**
* Attaches to a Java virtual machine.
*
* <p> A Java virtual machine can be described using a {@link
* com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor}.
* This method invokes the descriptor's {@link
* com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
* to check that it is equal to this provider. It then attempts to attach to the
* Java virtual machine.
*
* @param vmd
* The virtual machine descriptor
*
* @return VirtualMachine representing the target virtual machine.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or other permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the descriptor's {@link
* com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
* returns a provider that is not this provider, or it does not correspond
* to a Java virtual machine to which this provider can attach.
*
* @throws IOException
* If some other I/O error occurs
*
* @throws NullPointerException
* If <code>vmd</code> is <code>null</code>
*/
public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd)
throws AttachNotSupportedException, IOException
{
if (vmd.provider() != this) {
throw new AttachNotSupportedException("provider mismatch");
}
return attachVirtualMachine(vmd.id());
}
/**
* Lists the Java virtual machines known to this provider.
*
* <p> This method returns a list of {@link
* com.sun.tools.attach.VirtualMachineDescriptor} elements. Each
* <code>VirtualMachineDescriptor</code> describes a Java virtual machine
* to which this provider can <i>potentially</i> attach. There isn't any
* guarantee that invoking {@link #attachVirtualMachine(VirtualMachineDescriptor)
* attachVirtualMachine} on each descriptor in the list will succeed.
*
* @return The list of virtual machine descriptors which describe the
* Java virtual machines known to this provider (may be empty).
*/
public abstract List<VirtualMachineDescriptor> listVirtualMachines();
/**
* Returns a list of the installed attach providers.
*
* <p> An AttachProvider is installed on the platform if:
*
* <ul>
* <li><p>It is installed in a JAR file that is visible to the defining
* class loader of the AttachProvider type (usually, but not required
* to be, the {@link java.lang.ClassLoader#getSystemClassLoader system
* class loader}).</p></li>
*
* <li><p>The JAR file contains a provider configuration named
* <tt>com.sun.tools.attach.spi.AttachProvider</tt> in the resource directory
* <tt>META-INF/services</tt>. </p></li>
*
* <li><p>The provider configuration file lists the full-qualified class
* name of the AttachProvider implementation. </p></li>
* </ul>
*
* <p> The format of the provider configuration file is one fully-qualified
* class name per line. Space and tab characters surrounding each class name,
* as well as blank lines are ignored. The comment character is
* <tt>'#'</tt> (<tt>0x23</tt>), and on each line all characters following
* the first comment character are ignored. The file must be encoded in
* UTF-8. </p>
*
* <p> AttachProvider implementations are loaded and instantiated
* (using the zero-arg constructor) at the first invocation of this method.
* The list returned by the first invocation of this method is the list
* of providers. Subsequent invocations of this method return a list of the same
* providers. The list is unmodifable.</p>
*
* @return A list of the installed attach providers.
*/
public static List<AttachProvider> providers() {
synchronized (lock) {
if (providers == null) {
providers = new ArrayList<AttachProvider>();
ServiceLoader<AttachProvider> providerLoader =
ServiceLoader.load(AttachProvider.class,
AttachProvider.class.getClassLoader());
Iterator<AttachProvider> i = providerLoader.iterator();
while (i.hasNext()) {
try {
providers.add(i.next());
} catch (Throwable t) {
if (t instanceof ThreadDeath) {
ThreadDeath td = (ThreadDeath)t;
throw td;
}
// Ignore errors and exceptions
System.err.println(t);
}
}
}
return Collections.unmodifiableList(providers);
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Only developers who are defining new attach providers should need to make
* direct use of this package.
*
* @since 1.6
*/
@jdk.Exported
package com.sun.tools.attach.spi;

View File

@@ -0,0 +1,258 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* See JVMS, sections 4.2, 4.6, 4.7.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class AccessFlags {
public static final int ACC_PUBLIC = 0x0001; // class, inner, field, method
public static final int ACC_PRIVATE = 0x0002; // inner, field, method
public static final int ACC_PROTECTED = 0x0004; // inner, field, method
public static final int ACC_STATIC = 0x0008; // inner, field, method
public static final int ACC_FINAL = 0x0010; // class, inner, field, method
public static final int ACC_SUPER = 0x0020; // class
public static final int ACC_SYNCHRONIZED = 0x0020; // method
public static final int ACC_VOLATILE = 0x0040; // field
public static final int ACC_BRIDGE = 0x0040; // method
public static final int ACC_TRANSIENT = 0x0080; // field
public static final int ACC_VARARGS = 0x0080; // method
public static final int ACC_NATIVE = 0x0100; // method
public static final int ACC_INTERFACE = 0x0200; // class, inner
public static final int ACC_ABSTRACT = 0x0400; // class, inner, method
public static final int ACC_STRICT = 0x0800; // method
public static final int ACC_SYNTHETIC = 0x1000; // class, inner, field, method
public static final int ACC_ANNOTATION = 0x2000; // class, inner
public static final int ACC_ENUM = 0x4000; // class, inner, field
public static final int ACC_MANDATED = 0x8000; // class, inner, field, method
public static enum Kind { Class, InnerClass, Field, Method};
AccessFlags(ClassReader cr) throws IOException {
this(cr.readUnsignedShort());
}
public AccessFlags(int flags) {
this.flags = flags;
}
public AccessFlags ignore(int mask) {
return new AccessFlags(flags & ~mask);
}
public boolean is(int mask) {
return (flags & mask) != 0;
}
public int byteLength() {
return 2;
}
private static final int[] classModifiers = {
ACC_PUBLIC, ACC_FINAL, ACC_ABSTRACT
};
private static final int[] classFlags = {
ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_INTERFACE, ACC_ABSTRACT,
ACC_SYNTHETIC, ACC_ANNOTATION, ACC_ENUM
};
public Set<String> getClassModifiers() {
int f = ((flags & ACC_INTERFACE) != 0 ? flags & ~ACC_ABSTRACT : flags);
return getModifiers(f, classModifiers, Kind.Class);
}
public Set<String> getClassFlags() {
return getFlags(classFlags, Kind.Class);
}
private static final int[] innerClassModifiers = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
ACC_ABSTRACT
};
private static final int[] innerClassFlags = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_SUPER,
ACC_INTERFACE, ACC_ABSTRACT, ACC_SYNTHETIC, ACC_ANNOTATION, ACC_ENUM
};
public Set<String> getInnerClassModifiers() {
int f = ((flags & ACC_INTERFACE) != 0 ? flags & ~ACC_ABSTRACT : flags);
return getModifiers(f, innerClassModifiers, Kind.InnerClass);
}
public Set<String> getInnerClassFlags() {
return getFlags(innerClassFlags, Kind.InnerClass);
}
private static final int[] fieldModifiers = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
ACC_VOLATILE, ACC_TRANSIENT
};
private static final int[] fieldFlags = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
ACC_VOLATILE, ACC_TRANSIENT, ACC_SYNTHETIC, ACC_ENUM
};
public Set<String> getFieldModifiers() {
return getModifiers(fieldModifiers, Kind.Field);
}
public Set<String> getFieldFlags() {
return getFlags(fieldFlags, Kind.Field);
}
private static final int[] methodModifiers = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT
};
private static final int[] methodFlags = {
ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
ACC_SYNCHRONIZED, ACC_BRIDGE, ACC_VARARGS, ACC_NATIVE, ACC_ABSTRACT,
ACC_STRICT, ACC_SYNTHETIC
};
public Set<String> getMethodModifiers() {
return getModifiers(methodModifiers, Kind.Method);
}
public Set<String> getMethodFlags() {
return getFlags(methodFlags, Kind.Method);
}
private Set<String> getModifiers(int[] modifierFlags, Kind t) {
return getModifiers(flags, modifierFlags, t);
}
private static Set<String> getModifiers(int flags, int[] modifierFlags, Kind t) {
Set<String> s = new LinkedHashSet<String>();
for (int m: modifierFlags) {
if ((flags & m) != 0)
s.add(flagToModifier(m, t));
}
return s;
}
private Set<String> getFlags(int[] expectedFlags, Kind t) {
Set<String> s = new LinkedHashSet<String>();
int f = flags;
for (int e: expectedFlags) {
if ((f & e) != 0) {
s.add(flagToName(e, t));
f = f & ~e;
}
}
while (f != 0) {
int bit = Integer.highestOneBit(f);
s.add("0x" + Integer.toHexString(bit));
f = f & ~bit;
}
return s;
}
private static String flagToModifier(int flag, Kind t) {
switch (flag) {
case ACC_PUBLIC:
return "public";
case ACC_PRIVATE:
return "private";
case ACC_PROTECTED:
return "protected";
case ACC_STATIC:
return "static";
case ACC_FINAL:
return "final";
case ACC_SYNCHRONIZED:
return "synchronized";
case 0x80:
return (t == Kind.Field ? "transient" : null);
case ACC_VOLATILE:
return "volatile";
case ACC_NATIVE:
return "native";
case ACC_ABSTRACT:
return "abstract";
case ACC_STRICT:
return "strictfp";
case ACC_MANDATED:
return "mandated";
default:
return null;
}
}
private static String flagToName(int flag, Kind t) {
switch (flag) {
case ACC_PUBLIC:
return "ACC_PUBLIC";
case ACC_PRIVATE:
return "ACC_PRIVATE";
case ACC_PROTECTED:
return "ACC_PROTECTED";
case ACC_STATIC:
return "ACC_STATIC";
case ACC_FINAL:
return "ACC_FINAL";
case 0x20:
return (t == Kind.Class ? "ACC_SUPER" : "ACC_SYNCHRONIZED");
case 0x40:
return (t == Kind.Field ? "ACC_VOLATILE" : "ACC_BRIDGE");
case 0x80:
return (t == Kind.Field ? "ACC_TRANSIENT" : "ACC_VARARGS");
case ACC_NATIVE:
return "ACC_NATIVE";
case ACC_INTERFACE:
return "ACC_INTERFACE";
case ACC_ABSTRACT:
return "ACC_ABSTRACT";
case ACC_STRICT:
return "ACC_STRICT";
case ACC_SYNTHETIC:
return "ACC_SYNTHETIC";
case ACC_ANNOTATION:
return "ACC_ANNOTATION";
case ACC_ENUM:
return "ACC_ENUM";
case ACC_MANDATED:
return "ACC_MANDATED";
default:
return null;
}
}
public final int flags;
}

View File

@@ -0,0 +1,244 @@
/*
* Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.16.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Annotation {
static class InvalidAnnotation extends AttributeException {
private static final long serialVersionUID = -4620480740735772708L;
InvalidAnnotation(String msg) {
super(msg);
}
}
Annotation(ClassReader cr) throws IOException, InvalidAnnotation {
type_index = cr.readUnsignedShort();
num_element_value_pairs = cr.readUnsignedShort();
element_value_pairs = new element_value_pair[num_element_value_pairs];
for (int i = 0; i < element_value_pairs.length; i++)
element_value_pairs[i] = new element_value_pair(cr);
}
public Annotation(ConstantPool constant_pool,
int type_index,
element_value_pair[] element_value_pairs) {
this.type_index = type_index;
num_element_value_pairs = element_value_pairs.length;
this.element_value_pairs = element_value_pairs;
}
public int length() {
int n = 2 /*type_index*/ + 2 /*num_element_value_pairs*/;
for (element_value_pair pair: element_value_pairs)
n += pair.length();
return n;
}
public final int type_index;
public final int num_element_value_pairs;
public final element_value_pair element_value_pairs[];
/**
* See JVMS, section 4.8.16.1.
*/
public static abstract class element_value {
public static element_value read(ClassReader cr)
throws IOException, InvalidAnnotation {
int tag = cr.readUnsignedByte();
switch (tag) {
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
case 's':
return new Primitive_element_value(cr, tag);
case 'e':
return new Enum_element_value(cr, tag);
case 'c':
return new Class_element_value(cr, tag);
case '@':
return new Annotation_element_value(cr, tag);
case '[':
return new Array_element_value(cr, tag);
default:
throw new InvalidAnnotation("unrecognized tag: " + tag);
}
}
protected element_value(int tag) {
this.tag = tag;
}
public abstract int length();
public abstract <R,P> R accept(Visitor<R,P> visitor, P p);
public interface Visitor<R,P> {
R visitPrimitive(Primitive_element_value ev, P p);
R visitEnum(Enum_element_value ev, P p);
R visitClass(Class_element_value ev, P p);
R visitAnnotation(Annotation_element_value ev, P p);
R visitArray(Array_element_value ev, P p);
}
public final int tag;
}
public static class Primitive_element_value extends element_value {
Primitive_element_value(ClassReader cr, int tag) throws IOException {
super(tag);
const_value_index = cr.readUnsignedShort();
}
@Override
public int length() {
return 2;
}
public <R,P> R accept(Visitor<R,P> visitor, P p) {
return visitor.visitPrimitive(this, p);
}
public final int const_value_index;
}
public static class Enum_element_value extends element_value {
Enum_element_value(ClassReader cr, int tag) throws IOException {
super(tag);
type_name_index = cr.readUnsignedShort();
const_name_index = cr.readUnsignedShort();
}
@Override
public int length() {
return 4;
}
public <R,P> R accept(Visitor<R,P> visitor, P p) {
return visitor.visitEnum(this, p);
}
public final int type_name_index;
public final int const_name_index;
}
public static class Class_element_value extends element_value {
Class_element_value(ClassReader cr, int tag) throws IOException {
super(tag);
class_info_index = cr.readUnsignedShort();
}
@Override
public int length() {
return 2;
}
public <R,P> R accept(Visitor<R,P> visitor, P p) {
return visitor.visitClass(this, p);
}
public final int class_info_index;
}
public static class Annotation_element_value extends element_value {
Annotation_element_value(ClassReader cr, int tag)
throws IOException, InvalidAnnotation {
super(tag);
annotation_value = new Annotation(cr);
}
@Override
public int length() {
return annotation_value.length();
}
public <R,P> R accept(Visitor<R,P> visitor, P p) {
return visitor.visitAnnotation(this, p);
}
public final Annotation annotation_value;
}
public static class Array_element_value extends element_value {
Array_element_value(ClassReader cr, int tag)
throws IOException, InvalidAnnotation {
super(tag);
num_values = cr.readUnsignedShort();
values = new element_value[num_values];
for (int i = 0; i < values.length; i++)
values[i] = element_value.read(cr);
}
@Override
public int length() {
int n = 2;
for (int i = 0; i < values.length; i++)
n += values[i].length();
return n;
}
public <R,P> R accept(Visitor<R,P> visitor, P p) {
return visitor.visitArray(this, p);
}
public final int num_values;
public final element_value[] values;
}
public static class element_value_pair {
element_value_pair(ClassReader cr)
throws IOException, InvalidAnnotation {
element_name_index = cr.readUnsignedShort();
value = element_value.read(cr);
}
public int length() {
return 2 + value.length();
}
public final int element_name_index;
public final element_value value;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.15.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class AnnotationDefault_attribute extends Attribute {
AnnotationDefault_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
default_value = Annotation.element_value.read(cr);
}
public AnnotationDefault_attribute(ConstantPool constant_pool, Annotation.element_value default_value)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.AnnotationDefault), default_value);
}
public AnnotationDefault_attribute(int name_index, Annotation.element_value default_value) {
super(name_index, default_value.length());
this.default_value = default_value;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitAnnotationDefault(this, data);
}
public final Annotation.element_value default_value;
}

View File

@@ -0,0 +1,192 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class Attribute {
public static final String AnnotationDefault = "AnnotationDefault";
public static final String BootstrapMethods = "BootstrapMethods";
public static final String CharacterRangeTable = "CharacterRangeTable";
public static final String Code = "Code";
public static final String ConstantValue = "ConstantValue";
public static final String CompilationID = "CompilationID";
public static final String Deprecated = "Deprecated";
public static final String EnclosingMethod = "EnclosingMethod";
public static final String Exceptions = "Exceptions";
public static final String InnerClasses = "InnerClasses";
public static final String LineNumberTable = "LineNumberTable";
public static final String LocalVariableTable = "LocalVariableTable";
public static final String LocalVariableTypeTable = "LocalVariableTypeTable";
public static final String MethodParameters = "MethodParameters";
public static final String RuntimeVisibleAnnotations = "RuntimeVisibleAnnotations";
public static final String RuntimeInvisibleAnnotations = "RuntimeInvisibleAnnotations";
public static final String RuntimeVisibleParameterAnnotations = "RuntimeVisibleParameterAnnotations";
public static final String RuntimeInvisibleParameterAnnotations = "RuntimeInvisibleParameterAnnotations";
public static final String RuntimeVisibleTypeAnnotations = "RuntimeVisibleTypeAnnotations";
public static final String RuntimeInvisibleTypeAnnotations = "RuntimeInvisibleTypeAnnotations";
public static final String Signature = "Signature";
public static final String SourceDebugExtension = "SourceDebugExtension";
public static final String SourceFile = "SourceFile";
public static final String SourceID = "SourceID";
public static final String StackMap = "StackMap";
public static final String StackMapTable = "StackMapTable";
public static final String Synthetic = "Synthetic";
public static class Factory {
public Factory() {
// defer init of standardAttributeClasses until after options set up
}
public Attribute createAttribute(ClassReader cr, int name_index, byte[] data)
throws IOException {
if (standardAttributes == null) {
init();
}
ConstantPool cp = cr.getConstantPool();
String reasonForDefaultAttr;
try {
String name = cp.getUTF8Value(name_index);
Class<? extends Attribute> attrClass = standardAttributes.get(name);
if (attrClass != null) {
try {
Class<?>[] constrArgTypes = {ClassReader.class, int.class, int.class};
Constructor<? extends Attribute> constr = attrClass.getDeclaredConstructor(constrArgTypes);
return constr.newInstance(new Object[] { cr, name_index, data.length });
} catch (Throwable t) {
reasonForDefaultAttr = t.toString();
// fall through and use DefaultAttribute
// t.printStackTrace();
}
} else {
reasonForDefaultAttr = "unknown attribute";
}
} catch (ConstantPoolException e) {
reasonForDefaultAttr = e.toString();
// fall through and use DefaultAttribute
}
return new DefaultAttribute(cr, name_index, data, reasonForDefaultAttr);
}
protected void init() {
standardAttributes = new HashMap<String,Class<? extends Attribute>>();
standardAttributes.put(AnnotationDefault, AnnotationDefault_attribute.class);
standardAttributes.put(BootstrapMethods, BootstrapMethods_attribute.class);
standardAttributes.put(CharacterRangeTable, CharacterRangeTable_attribute.class);
standardAttributes.put(Code, Code_attribute.class);
standardAttributes.put(CompilationID, CompilationID_attribute.class);
standardAttributes.put(ConstantValue, ConstantValue_attribute.class);
standardAttributes.put(Deprecated, Deprecated_attribute.class);
standardAttributes.put(EnclosingMethod, EnclosingMethod_attribute.class);
standardAttributes.put(Exceptions, Exceptions_attribute.class);
standardAttributes.put(InnerClasses, InnerClasses_attribute.class);
standardAttributes.put(LineNumberTable, LineNumberTable_attribute.class);
standardAttributes.put(LocalVariableTable, LocalVariableTable_attribute.class);
standardAttributes.put(LocalVariableTypeTable, LocalVariableTypeTable_attribute.class);
standardAttributes.put(MethodParameters, MethodParameters_attribute.class);
standardAttributes.put(RuntimeInvisibleAnnotations, RuntimeInvisibleAnnotations_attribute.class);
standardAttributes.put(RuntimeInvisibleParameterAnnotations, RuntimeInvisibleParameterAnnotations_attribute.class);
standardAttributes.put(RuntimeVisibleAnnotations, RuntimeVisibleAnnotations_attribute.class);
standardAttributes.put(RuntimeVisibleParameterAnnotations, RuntimeVisibleParameterAnnotations_attribute.class);
standardAttributes.put(RuntimeVisibleTypeAnnotations, RuntimeVisibleTypeAnnotations_attribute.class);
standardAttributes.put(RuntimeInvisibleTypeAnnotations, RuntimeInvisibleTypeAnnotations_attribute.class);
standardAttributes.put(Signature, Signature_attribute.class);
standardAttributes.put(SourceDebugExtension, SourceDebugExtension_attribute.class);
standardAttributes.put(SourceFile, SourceFile_attribute.class);
standardAttributes.put(SourceID, SourceID_attribute.class);
standardAttributes.put(StackMap, StackMap_attribute.class);
standardAttributes.put(StackMapTable, StackMapTable_attribute.class);
standardAttributes.put(Synthetic, Synthetic_attribute.class);
}
private Map<String,Class<? extends Attribute>> standardAttributes;
}
public static Attribute read(ClassReader cr) throws IOException {
return cr.readAttribute();
}
protected Attribute(int name_index, int length) {
attribute_name_index = name_index;
attribute_length = length;
}
public String getName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(attribute_name_index);
}
public abstract <R,D> R accept(Attribute.Visitor<R,D> visitor, D data);
public int byteLength() {
return 6 + attribute_length;
}
public final int attribute_name_index;
public final int attribute_length;
public interface Visitor<R,P> {
R visitBootstrapMethods(BootstrapMethods_attribute attr, P p);
R visitDefault(DefaultAttribute attr, P p);
R visitAnnotationDefault(AnnotationDefault_attribute attr, P p);
R visitCharacterRangeTable(CharacterRangeTable_attribute attr, P p);
R visitCode(Code_attribute attr, P p);
R visitCompilationID(CompilationID_attribute attr, P p);
R visitConstantValue(ConstantValue_attribute attr, P p);
R visitDeprecated(Deprecated_attribute attr, P p);
R visitEnclosingMethod(EnclosingMethod_attribute attr, P p);
R visitExceptions(Exceptions_attribute attr, P p);
R visitInnerClasses(InnerClasses_attribute attr, P p);
R visitLineNumberTable(LineNumberTable_attribute attr, P p);
R visitLocalVariableTable(LocalVariableTable_attribute attr, P p);
R visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, P p);
R visitMethodParameters(MethodParameters_attribute attr, P p);
R visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, P p);
R visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, P p);
R visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, P p);
R visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, P p);
R visitRuntimeVisibleTypeAnnotations(RuntimeVisibleTypeAnnotations_attribute attr, P p);
R visitRuntimeInvisibleTypeAnnotations(RuntimeInvisibleTypeAnnotations_attribute attr, P p);
R visitSignature(Signature_attribute attr, P p);
R visitSourceDebugExtension(SourceDebugExtension_attribute attr, P p);
R visitSourceFile(SourceFile_attribute attr, P p);
R visitSourceID(SourceID_attribute attr, P p);
R visitStackMap(StackMap_attribute attr, P p);
R visitStackMapTable(StackMapTable_attribute attr, P p);
R visitSynthetic(Synthetic_attribute attr, P p);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class AttributeException extends Exception {
private static final long serialVersionUID = -4231486387714867770L;
AttributeException() { }
AttributeException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Attributes implements Iterable<Attribute> {
Attributes(ClassReader cr) throws IOException {
map = new HashMap<String,Attribute>();
int attrs_count = cr.readUnsignedShort();
attrs = new Attribute[attrs_count];
for (int i = 0; i < attrs_count; i++) {
Attribute attr = Attribute.read(cr);
attrs[i] = attr;
try {
map.put(attr.getName(cr.getConstantPool()), attr);
} catch (ConstantPoolException e) {
// don't enter invalid names in map
}
}
}
public Attributes(ConstantPool constant_pool, Attribute[] attrs) {
this.attrs = attrs;
map = new HashMap<String,Attribute>();
for (int i = 0; i < attrs.length; i++) {
Attribute attr = attrs[i];
try {
map.put(attr.getName(constant_pool), attr);
} catch (ConstantPoolException e) {
// don't enter invalid names in map
}
}
}
public Iterator<Attribute> iterator() {
return Arrays.asList(attrs).iterator();
}
public Attribute get(int index) {
return attrs[index];
}
public Attribute get(String name) {
return map.get(name);
}
public int getIndex(ConstantPool constant_pool, String name) {
for (int i = 0; i < attrs.length; i++) {
Attribute attr = attrs[i];
try {
if (attr != null && attr.getName(constant_pool).equals(name))
return i;
} catch (ConstantPoolException e) {
// ignore invalid entries
}
}
return -1;
}
public int size() {
return attrs.length;
}
public int byteLength() {
int length = 2;
for (Attribute a: attrs)
length += a.byteLength();
return length;
}
public final Attribute[] attrs;
public final Map<String, Attribute> map;
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS 4.7.21
* https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.21
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class BootstrapMethods_attribute extends Attribute {
public final BootstrapMethodSpecifier[] bootstrap_method_specifiers;
BootstrapMethods_attribute(ClassReader cr, int name_index, int length)
throws IOException, AttributeException {
super(name_index, length);
int bootstrap_method_count = cr.readUnsignedShort();
bootstrap_method_specifiers = new BootstrapMethodSpecifier[bootstrap_method_count];
for (int i = 0; i < bootstrap_method_specifiers.length; i++)
bootstrap_method_specifiers[i] = new BootstrapMethodSpecifier(cr);
}
public BootstrapMethods_attribute(int name_index, BootstrapMethodSpecifier[] bootstrap_method_specifiers) {
super(name_index, length(bootstrap_method_specifiers));
this.bootstrap_method_specifiers = bootstrap_method_specifiers;
}
public static int length(BootstrapMethodSpecifier[] bootstrap_method_specifiers) {
int n = 2;
for (BootstrapMethodSpecifier b : bootstrap_method_specifiers)
n += b.length();
return n;
}
@Override
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitBootstrapMethods(this, p);
}
public static class BootstrapMethodSpecifier {
public int bootstrap_method_ref;
public int[] bootstrap_arguments;
public BootstrapMethodSpecifier(int bootstrap_method_ref, int[] bootstrap_arguments) {
this.bootstrap_method_ref = bootstrap_method_ref;
this.bootstrap_arguments = bootstrap_arguments;
}
BootstrapMethodSpecifier(ClassReader cr) throws IOException {
bootstrap_method_ref = cr.readUnsignedShort();
int method_count = cr.readUnsignedShort();
bootstrap_arguments = new int[method_count];
for (int i = 0; i < bootstrap_arguments.length; i++) {
bootstrap_arguments[i] = cr.readUnsignedShort();
}
}
int length() {
// u2 (method_ref) + u2 (argc) + u2 * argc
return 2 + 2 + (bootstrap_arguments.length * 2);
}
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CharacterRangeTable_attribute extends Attribute {
public static final int CRT_STATEMENT = 0x0001;
public static final int CRT_BLOCK = 0x0002;
public static final int CRT_ASSIGNMENT = 0x0004;
public static final int CRT_FLOW_CONTROLLER = 0x0008;
public static final int CRT_FLOW_TARGET = 0x0010;
public static final int CRT_INVOKE = 0x0020;
public static final int CRT_CREATE = 0x0040;
public static final int CRT_BRANCH_TRUE = 0x0080;
public static final int CRT_BRANCH_FALSE = 0x0100;
CharacterRangeTable_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
int character_range_table_length = cr.readUnsignedShort();
character_range_table = new Entry[character_range_table_length];
for (int i = 0; i < character_range_table_length; i++)
character_range_table[i] = new Entry(cr);
}
public CharacterRangeTable_attribute(ConstantPool constant_pool, Entry[] character_range_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.CharacterRangeTable), character_range_table);
}
public CharacterRangeTable_attribute(int name_index, Entry[] character_range_table) {
super(name_index, 2 + character_range_table.length * Entry.length());
this.character_range_table = character_range_table;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitCharacterRangeTable(this, data);
}
public final Entry[] character_range_table;
public static class Entry {
Entry(ClassReader cr) throws IOException {
start_pc = cr.readUnsignedShort();
end_pc = cr.readUnsignedShort();
character_range_start = cr.readInt();
character_range_end = cr.readInt();
flags = cr.readUnsignedShort();
}
public static int length() {
return 14;
}
public final int start_pc;
public final int end_pc;
public final int character_range_start;
public final int character_range_end;
public final int flags;
};
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import static com.sun.tools.classfile.AccessFlags.*;
/**
* See JVMS, section 4.2.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClassFile {
public static ClassFile read(File file)
throws IOException, ConstantPoolException {
return read(file.toPath(), new Attribute.Factory());
}
public static ClassFile read(Path input)
throws IOException, ConstantPoolException {
return read(input, new Attribute.Factory());
}
public static ClassFile read(Path input, Attribute.Factory attributeFactory)
throws IOException, ConstantPoolException {
try (InputStream in = Files.newInputStream(input)) {
return new ClassFile(in, attributeFactory);
}
}
public static ClassFile read(File file, Attribute.Factory attributeFactory)
throws IOException, ConstantPoolException {
return read(file.toPath(), attributeFactory);
}
public static ClassFile read(InputStream in)
throws IOException, ConstantPoolException {
return new ClassFile(in, new Attribute.Factory());
}
public static ClassFile read(InputStream in, Attribute.Factory attributeFactory)
throws IOException, ConstantPoolException {
return new ClassFile(in, attributeFactory);
}
ClassFile(InputStream in, Attribute.Factory attributeFactory) throws IOException, ConstantPoolException {
ClassReader cr = new ClassReader(this, in, attributeFactory);
magic = cr.readInt();
minor_version = cr.readUnsignedShort();
major_version = cr.readUnsignedShort();
constant_pool = new ConstantPool(cr);
access_flags = new AccessFlags(cr);
this_class = cr.readUnsignedShort();
super_class = cr.readUnsignedShort();
int interfaces_count = cr.readUnsignedShort();
interfaces = new int[interfaces_count];
for (int i = 0; i < interfaces_count; i++)
interfaces[i] = cr.readUnsignedShort();
int fields_count = cr.readUnsignedShort();
fields = new Field[fields_count];
for (int i = 0; i < fields_count; i++)
fields[i] = new Field(cr);
int methods_count = cr.readUnsignedShort();
methods = new Method[methods_count];
for (int i = 0; i < methods_count; i++)
methods[i] = new Method(cr);
attributes = new Attributes(cr);
}
public ClassFile(int magic, int minor_version, int major_version,
ConstantPool constant_pool, AccessFlags access_flags,
int this_class, int super_class, int[] interfaces,
Field[] fields, Method[] methods, Attributes attributes) {
this.magic = magic;
this.minor_version = minor_version;
this.major_version = major_version;
this.constant_pool = constant_pool;
this.access_flags = access_flags;
this.this_class = this_class;
this.super_class = super_class;
this.interfaces = interfaces;
this.fields = fields;
this.methods = methods;
this.attributes = attributes;
}
public String getName() throws ConstantPoolException {
return constant_pool.getClassInfo(this_class).getName();
}
public String getSuperclassName() throws ConstantPoolException {
return constant_pool.getClassInfo(super_class).getName();
}
public String getInterfaceName(int i) throws ConstantPoolException {
return constant_pool.getClassInfo(interfaces[i]).getName();
}
public Attribute getAttribute(String name) {
return attributes.get(name);
}
public boolean isClass() {
return !isInterface();
}
public boolean isInterface() {
return access_flags.is(ACC_INTERFACE);
}
public int byteLength() {
return 4 + // magic
2 + // minor
2 + // major
constant_pool.byteLength() +
2 + // access flags
2 + // this_class
2 + // super_class
byteLength(interfaces) +
byteLength(fields) +
byteLength(methods) +
attributes.byteLength();
}
private int byteLength(int[] indices) {
return 2 + 2 * indices.length;
}
private int byteLength(Field[] fields) {
int length = 2;
for (Field f: fields)
length += f.byteLength();
return length;
}
private int byteLength(Method[] methods) {
int length = 2;
for (Method m: methods)
length += m.byteLength();
return length;
}
public final int magic;
public final int minor_version;
public final int major_version;
public final ConstantPool constant_pool;
public final AccessFlags access_flags;
public final int this_class;
public final int super_class;
public final int[] interfaces;
public final Field[] fields;
public final Method[] methods;
public final Attributes attributes;
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClassReader {
ClassReader(ClassFile classFile, InputStream in, Attribute.Factory attributeFactory) throws IOException {
// null checks
classFile.getClass();
attributeFactory.getClass();
this.classFile = classFile;
this.in = new DataInputStream(new BufferedInputStream(in));
this.attributeFactory = attributeFactory;
}
ClassFile getClassFile() {
return classFile;
}
ConstantPool getConstantPool() {
return classFile.constant_pool;
}
public Attribute readAttribute() throws IOException {
int name_index = readUnsignedShort();
int length = readInt();
byte[] data = new byte[length];
readFully(data);
DataInputStream prev = in;
in = new DataInputStream(new ByteArrayInputStream(data));
try {
return attributeFactory.createAttribute(this, name_index, data);
} finally {
in = prev;
}
}
public void readFully(byte[] b) throws IOException {
in.readFully(b);
}
public int readUnsignedByte() throws IOException {
return in.readUnsignedByte();
}
public int readUnsignedShort() throws IOException {
return in.readUnsignedShort();
}
public int readInt() throws IOException {
return in.readInt();
}
public long readLong() throws IOException {
return in.readLong();
}
public float readFloat() throws IOException {
return in.readFloat();
}
public double readDouble() throws IOException {
return in.readDouble();
}
public String readUTF() throws IOException {
return in.readUTF();
}
private DataInputStream in;
private ClassFile classFile;
private Attribute.Factory attributeFactory;
}

View File

@@ -0,0 +1,410 @@
/*
* Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.Map;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Double_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Fieldref_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Float_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Integer_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_InterfaceMethodref_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_InvokeDynamic_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Long_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_MethodHandle_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_MethodType_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Methodref_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_NameAndType_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_String_info;
import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info;
import com.sun.tools.classfile.ConstantPool.CPInfo;
/**
* Rewrites a class file using a map of translations.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClassTranslator
implements ConstantPool.Visitor<ConstantPool.CPInfo,Map<Object,Object>> {
/**
* Create a new ClassFile from {@code cf}, such that for all entries
* {@code k&nbsp;-\&gt;&nbsp;v} in {@code translations},
* each occurrence of {@code k} in {@code cf} will be replaced by {@code v}.
* in
* @param cf the class file to be processed
* @param translations the set of translations to be applied
* @return a copy of {@code} with the values in {@code translations} substituted
*/
public ClassFile translate(ClassFile cf, Map<Object,Object> translations) {
ClassFile cf2 = (ClassFile) translations.get(cf);
if (cf2 == null) {
ConstantPool constant_pool2 = translate(cf.constant_pool, translations);
Field[] fields2 = translate(cf.fields, cf.constant_pool, translations);
Method[] methods2 = translateMethods(cf.methods, cf.constant_pool, translations);
Attributes attributes2 = translateAttributes(cf.attributes, cf.constant_pool,
translations);
if (constant_pool2 == cf.constant_pool &&
fields2 == cf.fields &&
methods2 == cf.methods &&
attributes2 == cf.attributes)
cf2 = cf;
else
cf2 = new ClassFile(
cf.magic,
cf.minor_version,
cf.major_version,
constant_pool2,
cf.access_flags,
cf.this_class,
cf.super_class,
cf.interfaces,
fields2,
methods2,
attributes2);
translations.put(cf, cf2);
}
return cf2;
}
ConstantPool translate(ConstantPool cp, Map<Object,Object> translations) {
ConstantPool cp2 = (ConstantPool) translations.get(cp);
if (cp2 == null) {
ConstantPool.CPInfo[] pool2 = new ConstantPool.CPInfo[cp.size()];
boolean eq = true;
for (int i = 0; i < cp.size(); ) {
ConstantPool.CPInfo cpInfo;
try {
cpInfo = cp.get(i);
} catch (ConstantPool.InvalidIndex e) {
throw new IllegalStateException(e);
}
ConstantPool.CPInfo cpInfo2 = translate(cpInfo, translations);
eq &= (cpInfo == cpInfo2);
pool2[i] = cpInfo2;
if (cpInfo.getTag() != cpInfo2.getTag())
throw new IllegalStateException();
i += cpInfo.size();
}
if (eq)
cp2 = cp;
else
cp2 = new ConstantPool(pool2);
translations.put(cp, cp2);
}
return cp2;
}
ConstantPool.CPInfo translate(ConstantPool.CPInfo cpInfo, Map<Object,Object> translations) {
ConstantPool.CPInfo cpInfo2 = (ConstantPool.CPInfo) translations.get(cpInfo);
if (cpInfo2 == null) {
cpInfo2 = cpInfo.accept(this, translations);
translations.put(cpInfo, cpInfo2);
}
return cpInfo2;
}
Field[] translate(Field[] fields, ConstantPool constant_pool, Map<Object,Object> translations) {
Field[] fields2 = (Field[]) translations.get(fields);
if (fields2 == null) {
fields2 = new Field[fields.length];
for (int i = 0; i < fields.length; i++)
fields2[i] = translate(fields[i], constant_pool, translations);
if (equal(fields, fields2))
fields2 = fields;
translations.put(fields, fields2);
}
return fields2;
}
Field translate(Field field, ConstantPool constant_pool, Map<Object,Object> translations) {
Field field2 = (Field) translations.get(field);
if (field2 == null) {
Attributes attributes2 = translateAttributes(field.attributes, constant_pool,
translations);
if (attributes2 == field.attributes)
field2 = field;
else
field2 = new Field(
field.access_flags,
field.name_index,
field.descriptor,
attributes2);
translations.put(field, field2);
}
return field2;
}
Method[] translateMethods(Method[] methods, ConstantPool constant_pool, Map<Object,Object> translations) {
Method[] methods2 = (Method[]) translations.get(methods);
if (methods2 == null) {
methods2 = new Method[methods.length];
for (int i = 0; i < methods.length; i++)
methods2[i] = translate(methods[i], constant_pool, translations);
if (equal(methods, methods2))
methods2 = methods;
translations.put(methods, methods2);
}
return methods2;
}
Method translate(Method method, ConstantPool constant_pool, Map<Object,Object> translations) {
Method method2 = (Method) translations.get(method);
if (method2 == null) {
Attributes attributes2 = translateAttributes(method.attributes, constant_pool,
translations);
if (attributes2 == method.attributes)
method2 = method;
else
method2 = new Method(
method.access_flags,
method.name_index,
method.descriptor,
attributes2);
translations.put(method, method2);
}
return method2;
}
Attributes translateAttributes(Attributes attributes,
ConstantPool constant_pool, Map<Object,Object> translations) {
Attributes attributes2 = (Attributes) translations.get(attributes);
if (attributes2 == null) {
Attribute[] attrArray2 = new Attribute[attributes.size()];
ConstantPool constant_pool2 = translate(constant_pool, translations);
boolean attrsEqual = true;
for (int i = 0; i < attributes.size(); i++) {
Attribute attr = attributes.get(i);
Attribute attr2 = translate(attr, translations);
if (attr2 != attr)
attrsEqual = false;
attrArray2[i] = attr2;
}
if ((constant_pool2 == constant_pool) && attrsEqual)
attributes2 = attributes;
else
attributes2 = new Attributes(constant_pool2, attrArray2);
translations.put(attributes, attributes2);
}
return attributes2;
}
Attribute translate(Attribute attribute, Map<Object,Object> translations) {
Attribute attribute2 = (Attribute) translations.get(attribute);
if (attribute2 == null) {
attribute2 = attribute; // don't support translation within attributes yet
// (what about Code attribute)
translations.put(attribute, attribute2);
}
return attribute2;
}
private static <T> boolean equal(T[] a1, T[] a2) {
if (a1 == null || a2 == null)
return (a1 == a2);
if (a1.length != a2.length)
return false;
for (int i = 0; i < a1.length; i++) {
if (a1[i] != a2[i])
return false;
}
return true;
}
public CPInfo visitClass(CONSTANT_Class_info info, Map<Object, Object> translations) {
CONSTANT_Class_info info2 = (CONSTANT_Class_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_Class_info(cp2, info.name_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitDouble(CONSTANT_Double_info info, Map<Object, Object> translations) {
CONSTANT_Double_info info2 = (CONSTANT_Double_info) translations.get(info);
if (info2 == null) {
info2 = info;
translations.put(info, info2);
}
return info;
}
public CPInfo visitFieldref(CONSTANT_Fieldref_info info, Map<Object, Object> translations) {
CONSTANT_Fieldref_info info2 = (CONSTANT_Fieldref_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_Fieldref_info(cp2, info.class_index, info.name_and_type_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitFloat(CONSTANT_Float_info info, Map<Object, Object> translations) {
CONSTANT_Float_info info2 = (CONSTANT_Float_info) translations.get(info);
if (info2 == null) {
info2 = info;
translations.put(info, info2);
}
return info;
}
public CPInfo visitInteger(CONSTANT_Integer_info info, Map<Object, Object> translations) {
CONSTANT_Integer_info info2 = (CONSTANT_Integer_info) translations.get(info);
if (info2 == null) {
info2 = info;
translations.put(info, info2);
}
return info;
}
public CPInfo visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, Map<Object, Object> translations) {
CONSTANT_InterfaceMethodref_info info2 = (CONSTANT_InterfaceMethodref_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_InterfaceMethodref_info(cp2, info.class_index, info.name_and_type_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, Map<Object, Object> translations) {
CONSTANT_InvokeDynamic_info info2 = (CONSTANT_InvokeDynamic_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp) {
info2 = info;
} else {
info2 = new CONSTANT_InvokeDynamic_info(cp2, info.bootstrap_method_attr_index, info.name_and_type_index);
}
translations.put(info, info2);
}
return info;
}
public CPInfo visitLong(CONSTANT_Long_info info, Map<Object, Object> translations) {
CONSTANT_Long_info info2 = (CONSTANT_Long_info) translations.get(info);
if (info2 == null) {
info2 = info;
translations.put(info, info2);
}
return info;
}
public CPInfo visitNameAndType(CONSTANT_NameAndType_info info, Map<Object, Object> translations) {
CONSTANT_NameAndType_info info2 = (CONSTANT_NameAndType_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_NameAndType_info(cp2, info.name_index, info.type_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitMethodref(CONSTANT_Methodref_info info, Map<Object, Object> translations) {
CONSTANT_Methodref_info info2 = (CONSTANT_Methodref_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_Methodref_info(cp2, info.class_index, info.name_and_type_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitMethodHandle(CONSTANT_MethodHandle_info info, Map<Object, Object> translations) {
CONSTANT_MethodHandle_info info2 = (CONSTANT_MethodHandle_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp) {
info2 = info;
} else {
info2 = new CONSTANT_MethodHandle_info(cp2, info.reference_kind, info.reference_index);
}
translations.put(info, info2);
}
return info;
}
public CPInfo visitMethodType(CONSTANT_MethodType_info info, Map<Object, Object> translations) {
CONSTANT_MethodType_info info2 = (CONSTANT_MethodType_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp) {
info2 = info;
} else {
info2 = new CONSTANT_MethodType_info(cp2, info.descriptor_index);
}
translations.put(info, info2);
}
return info;
}
public CPInfo visitString(CONSTANT_String_info info, Map<Object, Object> translations) {
CONSTANT_String_info info2 = (CONSTANT_String_info) translations.get(info);
if (info2 == null) {
ConstantPool cp2 = translate(info.cp, translations);
if (cp2 == info.cp)
info2 = info;
else
info2 = new CONSTANT_String_info(cp2, info.string_index);
translations.put(info, info2);
}
return info;
}
public CPInfo visitUtf8(CONSTANT_Utf8_info info, Map<Object, Object> translations) {
CONSTANT_Utf8_info info2 = (CONSTANT_Utf8_info) translations.get(info);
if (info2 == null) {
info2 = info;
translations.put(info, info2);
}
return info;
}
}

View File

@@ -0,0 +1,811 @@
/*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static com.sun.tools.classfile.Annotation.*;
import static com.sun.tools.classfile.ConstantPool.*;
import static com.sun.tools.classfile.StackMapTable_attribute.*;
import static com.sun.tools.classfile.StackMapTable_attribute.verification_type_info.*;
/**
* Write a ClassFile data structure to a file or stream.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ClassWriter {
public ClassWriter() {
attributeWriter = new AttributeWriter();
constantPoolWriter = new ConstantPoolWriter();
out = new ClassOutputStream();
}
/**
* Write a ClassFile data structure to a file.
*/
public void write(ClassFile classFile, File f) throws IOException {
FileOutputStream f_out = new FileOutputStream(f);
try {
write(classFile, f_out);
} finally {
f_out.close();
}
}
/**
* Write a ClassFile data structure to a stream.
*/
public void write(ClassFile classFile, OutputStream s) throws IOException {
this.classFile = classFile;
out.reset();
write();
out.writeTo(s);
}
protected void write() throws IOException {
writeHeader();
writeConstantPool();
writeAccessFlags(classFile.access_flags);
writeClassInfo();
writeFields();
writeMethods();
writeAttributes(classFile.attributes);
}
protected void writeHeader() {
out.writeInt(classFile.magic);
out.writeShort(classFile.minor_version);
out.writeShort(classFile.major_version);
}
protected void writeAccessFlags(AccessFlags flags) {
out.writeShort(flags.flags);
}
protected void writeAttributes(Attributes attributes) {
int size = attributes.size();
out.writeShort(size);
for (Attribute attr: attributes)
attributeWriter.write(attr, out);
}
protected void writeClassInfo() {
out.writeShort(classFile.this_class);
out.writeShort(classFile.super_class);
int[] interfaces = classFile.interfaces;
out.writeShort(interfaces.length);
for (int i: interfaces)
out.writeShort(i);
}
protected void writeDescriptor(Descriptor d) {
out.writeShort(d.index);
}
protected void writeConstantPool() {
ConstantPool pool = classFile.constant_pool;
int size = pool.size();
out.writeShort(size);
for (CPInfo cpInfo: pool.entries())
constantPoolWriter.write(cpInfo, out);
}
protected void writeFields() throws IOException {
Field[] fields = classFile.fields;
out.writeShort(fields.length);
for (Field f: fields)
writeField(f);
}
protected void writeField(Field f) throws IOException {
writeAccessFlags(f.access_flags);
out.writeShort(f.name_index);
writeDescriptor(f.descriptor);
writeAttributes(f.attributes);
}
protected void writeMethods() throws IOException {
Method[] methods = classFile.methods;
out.writeShort(methods.length);
for (Method m: methods) {
writeMethod(m);
}
}
protected void writeMethod(Method m) throws IOException {
writeAccessFlags(m.access_flags);
out.writeShort(m.name_index);
writeDescriptor(m.descriptor);
writeAttributes(m.attributes);
}
protected ClassFile classFile;
protected ClassOutputStream out;
protected AttributeWriter attributeWriter;
protected ConstantPoolWriter constantPoolWriter;
/**
* Subtype of ByteArrayOutputStream with the convenience methods of
* a DataOutputStream. Since ByteArrayOutputStream does not throw
* IOException, there are no exceptions from the additional
* convenience methods either,
*/
protected static class ClassOutputStream extends ByteArrayOutputStream {
public ClassOutputStream() {
d = new DataOutputStream(this);
}
public void writeByte(int value) {
try {
d.writeByte(value);
} catch (IOException ignore) {
}
}
public void writeShort(int value) {
try {
d.writeShort(value);
} catch (IOException ignore) {
}
}
public void writeInt(int value) {
try {
d.writeInt(value);
} catch (IOException ignore) {
}
}
public void writeLong(long value) {
try {
d.writeLong(value);
} catch (IOException ignore) {
}
}
public void writeFloat(float value) {
try {
d.writeFloat(value);
} catch (IOException ignore) {
}
}
public void writeDouble(double value) {
try {
d.writeDouble(value);
} catch (IOException ignore) {
}
}
public void writeUTF(String value) {
try {
d.writeUTF(value);
} catch (IOException ignore) {
}
}
public void writeTo(ClassOutputStream s) {
try {
super.writeTo(s);
} catch (IOException ignore) {
}
}
private DataOutputStream d;
}
/**
* Writer for the entries in the constant pool.
*/
protected static class ConstantPoolWriter
implements ConstantPool.Visitor<Integer,ClassOutputStream> {
protected int write(CPInfo info, ClassOutputStream out) {
out.writeByte(info.getTag());
return info.accept(this, out);
}
public Integer visitClass(CONSTANT_Class_info info, ClassOutputStream out) {
out.writeShort(info.name_index);
return 1;
}
public Integer visitDouble(CONSTANT_Double_info info, ClassOutputStream out) {
out.writeDouble(info.value);
return 2;
}
public Integer visitFieldref(CONSTANT_Fieldref_info info, ClassOutputStream out) {
writeRef(info, out);
return 1;
}
public Integer visitFloat(CONSTANT_Float_info info, ClassOutputStream out) {
out.writeFloat(info.value);
return 1;
}
public Integer visitInteger(CONSTANT_Integer_info info, ClassOutputStream out) {
out.writeInt(info.value);
return 1;
}
public Integer visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, ClassOutputStream out) {
writeRef(info, out);
return 1;
}
public Integer visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, ClassOutputStream out) {
out.writeShort(info.bootstrap_method_attr_index);
out.writeShort(info.name_and_type_index);
return 1;
}
public Integer visitLong(CONSTANT_Long_info info, ClassOutputStream out) {
out.writeLong(info.value);
return 2;
}
public Integer visitNameAndType(CONSTANT_NameAndType_info info, ClassOutputStream out) {
out.writeShort(info.name_index);
out.writeShort(info.type_index);
return 1;
}
public Integer visitMethodHandle(CONSTANT_MethodHandle_info info, ClassOutputStream out) {
out.writeByte(info.reference_kind.tag);
out.writeShort(info.reference_index);
return 1;
}
public Integer visitMethodType(CONSTANT_MethodType_info info, ClassOutputStream out) {
out.writeShort(info.descriptor_index);
return 1;
}
public Integer visitMethodref(CONSTANT_Methodref_info info, ClassOutputStream out) {
return writeRef(info, out);
}
public Integer visitString(CONSTANT_String_info info, ClassOutputStream out) {
out.writeShort(info.string_index);
return 1;
}
public Integer visitUtf8(CONSTANT_Utf8_info info, ClassOutputStream out) {
out.writeUTF(info.value);
return 1;
}
protected Integer writeRef(CPRefInfo info, ClassOutputStream out) {
out.writeShort(info.class_index);
out.writeShort(info.name_and_type_index);
return 1;
}
}
/**
* Writer for the different types of attribute.
*/
protected static class AttributeWriter implements Attribute.Visitor<Void,ClassOutputStream> {
public void write(Attributes attributes, ClassOutputStream out) {
int size = attributes.size();
out.writeShort(size);
for (Attribute a: attributes)
write(a, out);
}
// Note: due to the use of shared resources, this method is not reentrant.
public void write(Attribute attr, ClassOutputStream out) {
out.writeShort(attr.attribute_name_index);
sharedOut.reset();
attr.accept(this, sharedOut);
out.writeInt(sharedOut.size());
sharedOut.writeTo(out);
}
protected ClassOutputStream sharedOut = new ClassOutputStream();
protected AnnotationWriter annotationWriter = new AnnotationWriter();
public Void visitDefault(DefaultAttribute attr, ClassOutputStream out) {
out.write(attr.info, 0, attr.info.length);
return null;
}
public Void visitAnnotationDefault(AnnotationDefault_attribute attr, ClassOutputStream out) {
annotationWriter.write(attr.default_value, out);
return null;
}
public Void visitBootstrapMethods(BootstrapMethods_attribute attr, ClassOutputStream out) {
out.writeShort(attr.bootstrap_method_specifiers.length);
for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsm : attr.bootstrap_method_specifiers) {
out.writeShort(bsm.bootstrap_method_ref);
int bsm_args_count = bsm.bootstrap_arguments.length;
out.writeShort(bsm_args_count);
for (int i : bsm.bootstrap_arguments) {
out.writeShort(i);
}
}
return null;
}
public Void visitCharacterRangeTable(CharacterRangeTable_attribute attr, ClassOutputStream out) {
out.writeShort(attr.character_range_table.length);
for (CharacterRangeTable_attribute.Entry e: attr.character_range_table)
writeCharacterRangeTableEntry(e, out);
return null;
}
protected void writeCharacterRangeTableEntry(CharacterRangeTable_attribute.Entry entry, ClassOutputStream out) {
out.writeShort(entry.start_pc);
out.writeShort(entry.end_pc);
out.writeInt(entry.character_range_start);
out.writeInt(entry.character_range_end);
out.writeShort(entry.flags);
}
public Void visitCode(Code_attribute attr, ClassOutputStream out) {
out.writeShort(attr.max_stack);
out.writeShort(attr.max_locals);
out.writeInt(attr.code.length);
out.write(attr.code, 0, attr.code.length);
out.writeShort(attr.exception_table.length);
for (Code_attribute.Exception_data e: attr.exception_table)
writeExceptionTableEntry(e, out);
new AttributeWriter().write(attr.attributes, out);
return null;
}
protected void writeExceptionTableEntry(Code_attribute.Exception_data exception_data, ClassOutputStream out) {
out.writeShort(exception_data.start_pc);
out.writeShort(exception_data.end_pc);
out.writeShort(exception_data.handler_pc);
out.writeShort(exception_data.catch_type);
}
public Void visitCompilationID(CompilationID_attribute attr, ClassOutputStream out) {
out.writeShort(attr.compilationID_index);
return null;
}
public Void visitConstantValue(ConstantValue_attribute attr, ClassOutputStream out) {
out.writeShort(attr.constantvalue_index);
return null;
}
public Void visitDeprecated(Deprecated_attribute attr, ClassOutputStream out) {
return null;
}
public Void visitEnclosingMethod(EnclosingMethod_attribute attr, ClassOutputStream out) {
out.writeShort(attr.class_index);
out.writeShort(attr.method_index);
return null;
}
public Void visitExceptions(Exceptions_attribute attr, ClassOutputStream out) {
out.writeShort(attr.exception_index_table.length);
for (int i: attr.exception_index_table)
out.writeShort(i);
return null;
}
public Void visitInnerClasses(InnerClasses_attribute attr, ClassOutputStream out) {
out.writeShort(attr.classes.length);
for (InnerClasses_attribute.Info info: attr.classes)
writeInnerClassesInfo(info, out);
return null;
}
protected void writeInnerClassesInfo(InnerClasses_attribute.Info info, ClassOutputStream out) {
out.writeShort(info.inner_class_info_index);
out.writeShort(info.outer_class_info_index);
out.writeShort(info.inner_name_index);
writeAccessFlags(info.inner_class_access_flags, out);
}
public Void visitLineNumberTable(LineNumberTable_attribute attr, ClassOutputStream out) {
out.writeShort(attr.line_number_table.length);
for (LineNumberTable_attribute.Entry e: attr.line_number_table)
writeLineNumberTableEntry(e, out);
return null;
}
protected void writeLineNumberTableEntry(LineNumberTable_attribute.Entry entry, ClassOutputStream out) {
out.writeShort(entry.start_pc);
out.writeShort(entry.line_number);
}
public Void visitLocalVariableTable(LocalVariableTable_attribute attr, ClassOutputStream out) {
out.writeShort(attr.local_variable_table.length);
for (LocalVariableTable_attribute.Entry e: attr.local_variable_table)
writeLocalVariableTableEntry(e, out);
return null;
}
protected void writeLocalVariableTableEntry(LocalVariableTable_attribute.Entry entry, ClassOutputStream out) {
out.writeShort(entry.start_pc);
out.writeShort(entry.length);
out.writeShort(entry.name_index);
out.writeShort(entry.descriptor_index);
out.writeShort(entry.index);
}
public Void visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, ClassOutputStream out) {
out.writeShort(attr.local_variable_table.length);
for (LocalVariableTypeTable_attribute.Entry e: attr.local_variable_table)
writeLocalVariableTypeTableEntry(e, out);
return null;
}
protected void writeLocalVariableTypeTableEntry(LocalVariableTypeTable_attribute.Entry entry, ClassOutputStream out) {
out.writeShort(entry.start_pc);
out.writeShort(entry.length);
out.writeShort(entry.name_index);
out.writeShort(entry.signature_index);
out.writeShort(entry.index);
}
public Void visitMethodParameters(MethodParameters_attribute attr, ClassOutputStream out) {
out.writeByte(attr.method_parameter_table.length);
for (MethodParameters_attribute.Entry e : attr.method_parameter_table) {
out.writeShort(e.name_index);
out.writeShort(e.flags);
}
return null;
}
public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, ClassOutputStream out) {
annotationWriter.write(attr.annotations, out);
return null;
}
public Void visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, ClassOutputStream out) {
annotationWriter.write(attr.annotations, out);
return null;
}
public Void visitRuntimeVisibleTypeAnnotations(RuntimeVisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
annotationWriter.write(attr.annotations, out);
return null;
}
public Void visitRuntimeInvisibleTypeAnnotations(RuntimeInvisibleTypeAnnotations_attribute attr, ClassOutputStream out) {
annotationWriter.write(attr.annotations, out);
return null;
}
public Void visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
out.writeByte(attr.parameter_annotations.length);
for (Annotation[] annos: attr.parameter_annotations)
annotationWriter.write(annos, out);
return null;
}
public Void visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, ClassOutputStream out) {
out.writeByte(attr.parameter_annotations.length);
for (Annotation[] annos: attr.parameter_annotations)
annotationWriter.write(annos, out);
return null;
}
public Void visitSignature(Signature_attribute attr, ClassOutputStream out) {
out.writeShort(attr.signature_index);
return null;
}
public Void visitSourceDebugExtension(SourceDebugExtension_attribute attr, ClassOutputStream out) {
out.write(attr.debug_extension, 0, attr.debug_extension.length);
return null;
}
public Void visitSourceFile(SourceFile_attribute attr, ClassOutputStream out) {
out.writeShort(attr.sourcefile_index);
return null;
}
public Void visitSourceID(SourceID_attribute attr, ClassOutputStream out) {
out.writeShort(attr.sourceID_index);
return null;
}
public Void visitStackMap(StackMap_attribute attr, ClassOutputStream out) {
if (stackMapWriter == null)
stackMapWriter = new StackMapTableWriter();
out.writeShort(attr.entries.length);
for (stack_map_frame f: attr.entries)
stackMapWriter.write(f, out);
return null;
}
public Void visitStackMapTable(StackMapTable_attribute attr, ClassOutputStream out) {
if (stackMapWriter == null)
stackMapWriter = new StackMapTableWriter();
out.writeShort(attr.entries.length);
for (stack_map_frame f: attr.entries)
stackMapWriter.write(f, out);
return null;
}
public Void visitSynthetic(Synthetic_attribute attr, ClassOutputStream out) {
return null;
}
protected void writeAccessFlags(AccessFlags flags, ClassOutputStream p) {
sharedOut.writeShort(flags.flags);
}
protected StackMapTableWriter stackMapWriter;
}
/**
* Writer for the frames of StackMap and StackMapTable attributes.
*/
protected static class StackMapTableWriter
implements stack_map_frame.Visitor<Void,ClassOutputStream> {
public void write(stack_map_frame frame, ClassOutputStream out) {
out.write(frame.frame_type);
frame.accept(this, out);
}
public Void visit_same_frame(same_frame frame, ClassOutputStream p) {
return null;
}
public Void visit_same_locals_1_stack_item_frame(same_locals_1_stack_item_frame frame, ClassOutputStream out) {
writeVerificationTypeInfo(frame.stack[0], out);
return null;
}
public Void visit_same_locals_1_stack_item_frame_extended(same_locals_1_stack_item_frame_extended frame, ClassOutputStream out) {
out.writeShort(frame.offset_delta);
writeVerificationTypeInfo(frame.stack[0], out);
return null;
}
public Void visit_chop_frame(chop_frame frame, ClassOutputStream out) {
out.writeShort(frame.offset_delta);
return null;
}
public Void visit_same_frame_extended(same_frame_extended frame, ClassOutputStream out) {
out.writeShort(frame.offset_delta);
return null;
}
public Void visit_append_frame(append_frame frame, ClassOutputStream out) {
out.writeShort(frame.offset_delta);
for (verification_type_info l: frame.locals)
writeVerificationTypeInfo(l, out);
return null;
}
public Void visit_full_frame(full_frame frame, ClassOutputStream out) {
out.writeShort(frame.offset_delta);
out.writeShort(frame.locals.length);
for (verification_type_info l: frame.locals)
writeVerificationTypeInfo(l, out);
out.writeShort(frame.stack.length);
for (verification_type_info s: frame.stack)
writeVerificationTypeInfo(s, out);
return null;
}
protected void writeVerificationTypeInfo(verification_type_info info,
ClassOutputStream out) {
out.write(info.tag);
switch (info.tag) {
case ITEM_Top:
case ITEM_Integer:
case ITEM_Float:
case ITEM_Long:
case ITEM_Double:
case ITEM_Null:
case ITEM_UninitializedThis:
break;
case ITEM_Object:
Object_variable_info o = (Object_variable_info) info;
out.writeShort(o.cpool_index);
break;
case ITEM_Uninitialized:
Uninitialized_variable_info u = (Uninitialized_variable_info) info;
out.writeShort(u.offset);
break;
default:
throw new Error();
}
}
}
/**
* Writer for annotations and the values they contain.
*/
protected static class AnnotationWriter
implements Annotation.element_value.Visitor<Void,ClassOutputStream> {
public void write(Annotation[] annos, ClassOutputStream out) {
out.writeShort(annos.length);
for (Annotation anno: annos)
write(anno, out);
}
public void write(TypeAnnotation[] annos, ClassOutputStream out) {
out.writeShort(annos.length);
for (TypeAnnotation anno: annos)
write(anno, out);
}
public void write(Annotation anno, ClassOutputStream out) {
out.writeShort(anno.type_index);
out.writeShort(anno.element_value_pairs.length);
for (element_value_pair p: anno.element_value_pairs)
write(p, out);
}
public void write(TypeAnnotation anno, ClassOutputStream out) {
write(anno.position, out);
write(anno.annotation, out);
}
public void write(element_value_pair pair, ClassOutputStream out) {
out.writeShort(pair.element_name_index);
write(pair.value, out);
}
public void write(element_value ev, ClassOutputStream out) {
out.writeByte(ev.tag);
ev.accept(this, out);
}
public Void visitPrimitive(Primitive_element_value ev, ClassOutputStream out) {
out.writeShort(ev.const_value_index);
return null;
}
public Void visitEnum(Enum_element_value ev, ClassOutputStream out) {
out.writeShort(ev.type_name_index);
out.writeShort(ev.const_name_index);
return null;
}
public Void visitClass(Class_element_value ev, ClassOutputStream out) {
out.writeShort(ev.class_info_index);
return null;
}
public Void visitAnnotation(Annotation_element_value ev, ClassOutputStream out) {
write(ev.annotation_value, out);
return null;
}
public Void visitArray(Array_element_value ev, ClassOutputStream out) {
out.writeShort(ev.num_values);
for (element_value v: ev.values)
write(v, out);
return null;
}
// TODO: Move this to TypeAnnotation to be closer with similar logic?
private void write(TypeAnnotation.Position p, ClassOutputStream out) {
out.writeByte(p.type.targetTypeValue());
switch (p.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
out.writeShort(p.offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = p.lvarOffset.length;
out.writeShort(table_length);
for (int i = 0; i < table_length; ++i) {
out.writeShort(1); // for table length
out.writeShort(p.lvarOffset[i]);
out.writeShort(p.lvarLength[i]);
out.writeShort(p.lvarIndex[i]);
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
out.writeShort(p.exception_index);
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameters
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
out.writeByte(p.parameter_index);
break;
// type parameters bounds
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
out.writeByte(p.parameter_index);
out.writeByte(p.bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
out.writeShort(p.type_index);
break;
// throws
case THROWS:
out.writeShort(p.type_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
out.writeByte(p.parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
out.writeShort(p.offset);
out.writeByte(p.type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("ClassWriter: UNKNOWN target type should never occur!");
default:
throw new AssertionError("ClassWriter: Unknown target type for position: " + p);
}
{ // Append location data for generics/arrays.
// TODO: check for overrun?
out.writeByte((byte)p.location.size());
for (int i : TypeAnnotation.Position.getBinaryFromTypePath(p.location))
out.writeByte((byte)i);
}
}
}
}

View File

@@ -0,0 +1,159 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* See JVMS, section 4.8.3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Code_attribute extends Attribute {
public static class InvalidIndex extends AttributeException {
private static final long serialVersionUID = -8904527774589382802L;
InvalidIndex(int index) {
this.index = index;
}
@Override
public String getMessage() {
// i18n
return "invalid index " + index + " in Code attribute";
}
public final int index;
}
Code_attribute(ClassReader cr, int name_index, int length)
throws IOException, ConstantPoolException {
super(name_index, length);
max_stack = cr.readUnsignedShort();
max_locals = cr.readUnsignedShort();
code_length = cr.readInt();
code = new byte[code_length];
cr.readFully(code);
exception_table_length = cr.readUnsignedShort();
exception_table = new Exception_data[exception_table_length];
for (int i = 0; i < exception_table_length; i++)
exception_table[i] = new Exception_data(cr);
attributes = new Attributes(cr);
}
public int getByte(int offset) throws InvalidIndex {
if (offset < 0 || offset >= code.length)
throw new InvalidIndex(offset);
return code[offset];
}
public int getUnsignedByte(int offset) throws InvalidIndex {
if (offset < 0 || offset >= code.length)
throw new InvalidIndex(offset);
return code[offset] & 0xff;
}
public int getShort(int offset) throws InvalidIndex {
if (offset < 0 || offset + 1 >= code.length)
throw new InvalidIndex(offset);
return (code[offset] << 8) | (code[offset + 1] & 0xFF);
}
public int getUnsignedShort(int offset) throws InvalidIndex {
if (offset < 0 || offset + 1 >= code.length)
throw new InvalidIndex(offset);
return ((code[offset] << 8) | (code[offset + 1] & 0xFF)) & 0xFFFF;
}
public int getInt(int offset) throws InvalidIndex {
if (offset < 0 || offset + 3 >= code.length)
throw new InvalidIndex(offset);
return (getShort(offset) << 16) | (getShort(offset + 2) & 0xFFFF);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitCode(this, data);
}
public Iterable<Instruction> getInstructions() {
return new Iterable<Instruction>() {
public Iterator<Instruction> iterator() {
return new Iterator<Instruction>() {
public boolean hasNext() {
return (next != null);
}
public Instruction next() {
if (next == null)
throw new NoSuchElementException();
current = next;
pc += current.length();
next = (pc < code.length ? new Instruction(code, pc) : null);
return current;
}
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
Instruction current = null;
int pc = 0;
Instruction next = new Instruction(code, pc);
};
}
};
}
public final int max_stack;
public final int max_locals;
public final int code_length;
public final byte[] code;
public final int exception_table_length;
public final Exception_data[] exception_table;
public final Attributes attributes;
public static class Exception_data {
Exception_data(ClassReader cr) throws IOException {
start_pc = cr.readUnsignedShort();
end_pc = cr.readUnsignedShort();
handler_pc = cr.readUnsignedShort();
catch_type = cr.readUnsignedShort();
}
public final int start_pc;
public final int end_pc;
public final int handler_pc;
public final int catch_type;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CompilationID_attribute extends Attribute {
CompilationID_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
compilationID_index = cr.readUnsignedShort();
}
public CompilationID_attribute(ConstantPool constant_pool, int compilationID_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.CompilationID), compilationID_index);
}
public CompilationID_attribute(int name_index, int compilationID_index) {
super(name_index, 2);
this.compilationID_index = compilationID_index;
}
String getCompilationID(ConstantPool constant_pool)
throws ConstantPoolException {
return constant_pool.getUTF8Value(compilationID_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitCompilationID(this, data);
}
public final int compilationID_index;
}

View File

@@ -0,0 +1,914 @@
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
/**
* See JVMS, section 4.5.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ConstantPool {
public static class InvalidIndex extends ConstantPoolException {
private static final long serialVersionUID = -4350294289300939730L;
InvalidIndex(int index) {
super(index);
}
@Override
public String getMessage() {
// i18n
return "invalid index #" + index;
}
}
public static class UnexpectedEntry extends ConstantPoolException {
private static final long serialVersionUID = 6986335935377933211L;
UnexpectedEntry(int index, int expected_tag, int found_tag) {
super(index);
this.expected_tag = expected_tag;
this.found_tag = found_tag;
}
@Override
public String getMessage() {
// i18n?
return "unexpected entry at #" + index + " -- expected tag " + expected_tag + ", found " + found_tag;
}
public final int expected_tag;
public final int found_tag;
}
public static class InvalidEntry extends ConstantPoolException {
private static final long serialVersionUID = 1000087545585204447L;
InvalidEntry(int index, int tag) {
super(index);
this.tag = tag;
}
@Override
public String getMessage() {
// i18n?
return "unexpected tag at #" + index + ": " + tag;
}
public final int tag;
}
public static class EntryNotFound extends ConstantPoolException {
private static final long serialVersionUID = 2885537606468581850L;
EntryNotFound(Object value) {
super(-1);
this.value = value;
}
@Override
public String getMessage() {
// i18n?
return "value not found: " + value;
}
public final Object value;
}
public static final int CONSTANT_Utf8 = 1;
public static final int CONSTANT_Integer = 3;
public static final int CONSTANT_Float = 4;
public static final int CONSTANT_Long = 5;
public static final int CONSTANT_Double = 6;
public static final int CONSTANT_Class = 7;
public static final int CONSTANT_String = 8;
public static final int CONSTANT_Fieldref = 9;
public static final int CONSTANT_Methodref = 10;
public static final int CONSTANT_InterfaceMethodref = 11;
public static final int CONSTANT_NameAndType = 12;
public static final int CONSTANT_MethodHandle = 15;
public static final int CONSTANT_MethodType = 16;
public static final int CONSTANT_InvokeDynamic = 18;
public static enum RefKind {
REF_getField(1, "getfield"),
REF_getStatic(2, "getstatic"),
REF_putField(3, "putfield"),
REF_putStatic(4, "putstatic"),
REF_invokeVirtual(5, "invokevirtual"),
REF_invokeStatic(6, "invokestatic"),
REF_invokeSpecial(7, "invokespecial"),
REF_newInvokeSpecial(8, "newinvokespecial"),
REF_invokeInterface(9, "invokeinterface");
public final int tag;
public final String name;
RefKind(int tag, String name) {
this.tag = tag;
this.name = name;
}
static RefKind getRefkind(int tag) {
switch(tag) {
case 1:
return REF_getField;
case 2:
return REF_getStatic;
case 3:
return REF_putField;
case 4:
return REF_putStatic;
case 5:
return REF_invokeVirtual;
case 6:
return REF_invokeStatic;
case 7:
return REF_invokeSpecial;
case 8:
return REF_newInvokeSpecial;
case 9:
return REF_invokeInterface;
default:
return null;
}
}
}
ConstantPool(ClassReader cr) throws IOException, InvalidEntry {
int count = cr.readUnsignedShort();
pool = new CPInfo[count];
for (int i = 1; i < count; i++) {
int tag = cr.readUnsignedByte();
switch (tag) {
case CONSTANT_Class:
pool[i] = new CONSTANT_Class_info(this, cr);
break;
case CONSTANT_Double:
pool[i] = new CONSTANT_Double_info(cr);
i++;
break;
case CONSTANT_Fieldref:
pool[i] = new CONSTANT_Fieldref_info(this, cr);
break;
case CONSTANT_Float:
pool[i] = new CONSTANT_Float_info(cr);
break;
case CONSTANT_Integer:
pool[i] = new CONSTANT_Integer_info(cr);
break;
case CONSTANT_InterfaceMethodref:
pool[i] = new CONSTANT_InterfaceMethodref_info(this, cr);
break;
case CONSTANT_InvokeDynamic:
pool[i] = new CONSTANT_InvokeDynamic_info(this, cr);
break;
case CONSTANT_Long:
pool[i] = new CONSTANT_Long_info(cr);
i++;
break;
case CONSTANT_MethodHandle:
pool[i] = new CONSTANT_MethodHandle_info(this, cr);
break;
case CONSTANT_MethodType:
pool[i] = new CONSTANT_MethodType_info(this, cr);
break;
case CONSTANT_Methodref:
pool[i] = new CONSTANT_Methodref_info(this, cr);
break;
case CONSTANT_NameAndType:
pool[i] = new CONSTANT_NameAndType_info(this, cr);
break;
case CONSTANT_String:
pool[i] = new CONSTANT_String_info(this, cr);
break;
case CONSTANT_Utf8:
pool[i] = new CONSTANT_Utf8_info(cr);
break;
default:
throw new InvalidEntry(i, tag);
}
}
}
public ConstantPool(CPInfo[] pool) {
this.pool = pool;
}
public int size() {
return pool.length;
}
public int byteLength() {
int length = 2;
for (int i = 1; i < size(); ) {
CPInfo cpInfo = pool[i];
length += cpInfo.byteLength();
i += cpInfo.size();
}
return length;
}
public CPInfo get(int index) throws InvalidIndex {
if (index <= 0 || index >= pool.length)
throw new InvalidIndex(index);
CPInfo info = pool[index];
if (info == null) {
// this occurs for indices referencing the "second half" of an
// 8 byte constant, such as CONSTANT_Double or CONSTANT_Long
throw new InvalidIndex(index);
}
return pool[index];
}
private CPInfo get(int index, int expected_type) throws InvalidIndex, UnexpectedEntry {
CPInfo info = get(index);
if (info.getTag() != expected_type)
throw new UnexpectedEntry(index, expected_type, info.getTag());
return info;
}
public CONSTANT_Utf8_info getUTF8Info(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_Utf8_info) get(index, CONSTANT_Utf8));
}
public CONSTANT_Class_info getClassInfo(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_Class_info) get(index, CONSTANT_Class));
}
public CONSTANT_NameAndType_info getNameAndTypeInfo(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_NameAndType_info) get(index, CONSTANT_NameAndType));
}
public String getUTF8Value(int index) throws InvalidIndex, UnexpectedEntry {
return getUTF8Info(index).value;
}
public int getUTF8Index(String value) throws EntryNotFound {
for (int i = 1; i < pool.length; i++) {
CPInfo info = pool[i];
if (info instanceof CONSTANT_Utf8_info &&
((CONSTANT_Utf8_info) info).value.equals(value))
return i;
}
throw new EntryNotFound(value);
}
public Iterable<CPInfo> entries() {
return new Iterable<CPInfo>() {
public Iterator<CPInfo> iterator() {
return new Iterator<CPInfo>() {
public boolean hasNext() {
return next < pool.length;
}
public CPInfo next() {
current = pool[next];
switch (current.getTag()) {
case CONSTANT_Double:
case CONSTANT_Long:
next += 2;
break;
default:
next += 1;
}
return current;
}
public void remove() {
throw new UnsupportedOperationException();
}
private CPInfo current;
private int next = 1;
};
}
};
}
private CPInfo[] pool;
public interface Visitor<R,P> {
R visitClass(CONSTANT_Class_info info, P p);
R visitDouble(CONSTANT_Double_info info, P p);
R visitFieldref(CONSTANT_Fieldref_info info, P p);
R visitFloat(CONSTANT_Float_info info, P p);
R visitInteger(CONSTANT_Integer_info info, P p);
R visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, P p);
R visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, P p);
R visitLong(CONSTANT_Long_info info, P p);
R visitNameAndType(CONSTANT_NameAndType_info info, P p);
R visitMethodref(CONSTANT_Methodref_info info, P p);
R visitMethodHandle(CONSTANT_MethodHandle_info info, P p);
R visitMethodType(CONSTANT_MethodType_info info, P p);
R visitString(CONSTANT_String_info info, P p);
R visitUtf8(CONSTANT_Utf8_info info, P p);
}
public static abstract class CPInfo {
CPInfo() {
this.cp = null;
}
CPInfo(ConstantPool cp) {
this.cp = cp;
}
public abstract int getTag();
/** The number of slots in the constant pool used by this entry.
* 2 for CONSTANT_Double and CONSTANT_Long; 1 for everything else. */
public int size() {
return 1;
}
public abstract int byteLength();
public abstract <R,D> R accept(Visitor<R,D> visitor, D data);
protected final ConstantPool cp;
}
public static abstract class CPRefInfo extends CPInfo {
protected CPRefInfo(ConstantPool cp, ClassReader cr, int tag) throws IOException {
super(cp);
this.tag = tag;
class_index = cr.readUnsignedShort();
name_and_type_index = cr.readUnsignedShort();
}
protected CPRefInfo(ConstantPool cp, int tag, int class_index, int name_and_type_index) {
super(cp);
this.tag = tag;
this.class_index = class_index;
this.name_and_type_index = name_and_type_index;
}
public int getTag() {
return tag;
}
public int byteLength() {
return 5;
}
public CONSTANT_Class_info getClassInfo() throws ConstantPoolException {
return cp.getClassInfo(class_index);
}
public String getClassName() throws ConstantPoolException {
return cp.getClassInfo(class_index).getName();
}
public CONSTANT_NameAndType_info getNameAndTypeInfo() throws ConstantPoolException {
return cp.getNameAndTypeInfo(name_and_type_index);
}
public final int tag;
public final int class_index;
public final int name_and_type_index;
}
public static class CONSTANT_Class_info extends CPInfo {
CONSTANT_Class_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
name_index = cr.readUnsignedShort();
}
public CONSTANT_Class_info(ConstantPool cp, int name_index) {
super(cp);
this.name_index = name_index;
}
public int getTag() {
return CONSTANT_Class;
}
public int byteLength() {
return 3;
}
/**
* Get the raw value of the class referenced by this constant pool entry.
* This will either be the name of the class, in internal form, or a
* descriptor for an array class.
* @return the raw value of the class
*/
public String getName() throws ConstantPoolException {
return cp.getUTF8Value(name_index);
}
/**
* If this constant pool entry identifies either a class or interface type,
* or a possibly multi-dimensional array of a class of interface type,
* return the name of the class or interface in internal form. Otherwise,
* (i.e. if this is a possibly multi-dimensional array of a primitive type),
* return null.
* @return the base class or interface name
*/
public String getBaseName() throws ConstantPoolException {
String name = getName();
if (name.startsWith("[")) {
int index = name.indexOf("[L");
if (index == -1)
return null;
return name.substring(index + 2, name.length() - 1);
} else
return name;
}
public int getDimensionCount() throws ConstantPoolException {
String name = getName();
int count = 0;
while (name.charAt(count) == '[')
count++;
return count;
}
@Override
public String toString() {
return "CONSTANT_Class_info[name_index: " + name_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitClass(this, data);
}
public final int name_index;
}
public static class CONSTANT_Double_info extends CPInfo {
CONSTANT_Double_info(ClassReader cr) throws IOException {
value = cr.readDouble();
}
public CONSTANT_Double_info(double value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Double;
}
public int byteLength() {
return 9;
}
@Override
public int size() {
return 2;
}
@Override
public String toString() {
return "CONSTANT_Double_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitDouble(this, data);
}
public final double value;
}
public static class CONSTANT_Fieldref_info extends CPRefInfo {
CONSTANT_Fieldref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_Fieldref);
}
public CONSTANT_Fieldref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_Fieldref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_Fieldref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitFieldref(this, data);
}
}
public static class CONSTANT_Float_info extends CPInfo {
CONSTANT_Float_info(ClassReader cr) throws IOException {
value = cr.readFloat();
}
public CONSTANT_Float_info(float value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Float;
}
public int byteLength() {
return 5;
}
@Override
public String toString() {
return "CONSTANT_Float_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitFloat(this, data);
}
public final float value;
}
public static class CONSTANT_Integer_info extends CPInfo {
CONSTANT_Integer_info(ClassReader cr) throws IOException {
value = cr.readInt();
}
public CONSTANT_Integer_info(int value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Integer;
}
public int byteLength() {
return 5;
}
@Override
public String toString() {
return "CONSTANT_Integer_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInteger(this, data);
}
public final int value;
}
public static class CONSTANT_InterfaceMethodref_info extends CPRefInfo {
CONSTANT_InterfaceMethodref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_InterfaceMethodref);
}
public CONSTANT_InterfaceMethodref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_InterfaceMethodref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_InterfaceMethodref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInterfaceMethodref(this, data);
}
}
public static class CONSTANT_InvokeDynamic_info extends CPInfo {
CONSTANT_InvokeDynamic_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
bootstrap_method_attr_index = cr.readUnsignedShort();
name_and_type_index = cr.readUnsignedShort();
}
public CONSTANT_InvokeDynamic_info(ConstantPool cp, int bootstrap_method_index, int name_and_type_index) {
super(cp);
this.bootstrap_method_attr_index = bootstrap_method_index;
this.name_and_type_index = name_and_type_index;
}
public int getTag() {
return CONSTANT_InvokeDynamic;
}
public int byteLength() {
return 5;
}
@Override
public String toString() {
return "CONSTANT_InvokeDynamic_info[bootstrap_method_index: " + bootstrap_method_attr_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInvokeDynamic(this, data);
}
public CONSTANT_NameAndType_info getNameAndTypeInfo() throws ConstantPoolException {
return cp.getNameAndTypeInfo(name_and_type_index);
}
public final int bootstrap_method_attr_index;
public final int name_and_type_index;
}
public static class CONSTANT_Long_info extends CPInfo {
CONSTANT_Long_info(ClassReader cr) throws IOException {
value = cr.readLong();
}
public CONSTANT_Long_info(long value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Long;
}
@Override
public int size() {
return 2;
}
public int byteLength() {
return 9;
}
@Override
public String toString() {
return "CONSTANT_Long_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitLong(this, data);
}
public final long value;
}
public static class CONSTANT_MethodHandle_info extends CPInfo {
CONSTANT_MethodHandle_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
reference_kind = RefKind.getRefkind(cr.readUnsignedByte());
reference_index = cr.readUnsignedShort();
}
public CONSTANT_MethodHandle_info(ConstantPool cp, RefKind ref_kind, int member_index) {
super(cp);
this.reference_kind = ref_kind;
this.reference_index = member_index;
}
public int getTag() {
return CONSTANT_MethodHandle;
}
public int byteLength() {
return 4;
}
@Override
public String toString() {
return "CONSTANT_MethodHandle_info[ref_kind: " + reference_kind + ", member_index: " + reference_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodHandle(this, data);
}
public CPRefInfo getCPRefInfo() throws ConstantPoolException {
int expected = CONSTANT_Methodref;
int actual = cp.get(reference_index).getTag();
// allow these tag types also:
switch (actual) {
case CONSTANT_Fieldref:
case CONSTANT_InterfaceMethodref:
expected = actual;
}
return (CPRefInfo) cp.get(reference_index, expected);
}
public final RefKind reference_kind;
public final int reference_index;
}
public static class CONSTANT_MethodType_info extends CPInfo {
CONSTANT_MethodType_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
descriptor_index = cr.readUnsignedShort();
}
public CONSTANT_MethodType_info(ConstantPool cp, int signature_index) {
super(cp);
this.descriptor_index = signature_index;
}
public int getTag() {
return CONSTANT_MethodType;
}
public int byteLength() {
return 3;
}
@Override
public String toString() {
return "CONSTANT_MethodType_info[signature_index: " + descriptor_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodType(this, data);
}
public String getType() throws ConstantPoolException {
return cp.getUTF8Value(descriptor_index);
}
public final int descriptor_index;
}
public static class CONSTANT_Methodref_info extends CPRefInfo {
CONSTANT_Methodref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_Methodref);
}
public CONSTANT_Methodref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_Methodref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_Methodref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodref(this, data);
}
}
public static class CONSTANT_NameAndType_info extends CPInfo {
CONSTANT_NameAndType_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
name_index = cr.readUnsignedShort();
type_index = cr.readUnsignedShort();
}
public CONSTANT_NameAndType_info(ConstantPool cp, int name_index, int type_index) {
super(cp);
this.name_index = name_index;
this.type_index = type_index;
}
public int getTag() {
return CONSTANT_NameAndType;
}
public int byteLength() {
return 5;
}
public String getName() throws ConstantPoolException {
return cp.getUTF8Value(name_index);
}
public String getType() throws ConstantPoolException {
return cp.getUTF8Value(type_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitNameAndType(this, data);
}
@Override
public String toString() {
return "CONSTANT_NameAndType_info[name_index: " + name_index + ", type_index: " + type_index + "]";
}
public final int name_index;
public final int type_index;
}
public static class CONSTANT_String_info extends CPInfo {
CONSTANT_String_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
string_index = cr.readUnsignedShort();
}
public CONSTANT_String_info(ConstantPool cp, int string_index) {
super(cp);
this.string_index = string_index;
}
public int getTag() {
return CONSTANT_String;
}
public int byteLength() {
return 3;
}
public String getString() throws ConstantPoolException {
return cp.getUTF8Value(string_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitString(this, data);
}
@Override
public String toString() {
return "CONSTANT_String_info[class_index: " + string_index + "]";
}
public final int string_index;
}
public static class CONSTANT_Utf8_info extends CPInfo {
CONSTANT_Utf8_info(ClassReader cr) throws IOException {
value = cr.readUTF();
}
public CONSTANT_Utf8_info(String value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Utf8;
}
public int byteLength() {
class SizeOutputStream extends OutputStream {
@Override
public void write(int b) {
size++;
}
int size;
}
SizeOutputStream sizeOut = new SizeOutputStream();
DataOutputStream out = new DataOutputStream(sizeOut);
try { out.writeUTF(value); } catch (IOException ignore) { }
return 1 + sizeOut.size;
}
@Override
public String toString() {
if (value.length() < 32 && isPrintableAscii(value))
return "CONSTANT_Utf8_info[value: \"" + value + "\"]";
else
return "CONSTANT_Utf8_info[value: (" + value.length() + " chars)]";
}
static boolean isPrintableAscii(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < 32 || c >= 127)
return false;
}
return true;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitUtf8(this, data);
}
public final String value;
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ConstantPoolException extends Exception {
private static final long serialVersionUID = -2324397349644754565L;
ConstantPoolException(int index) {
this.index = index;
}
public final int index;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.2.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ConstantValue_attribute extends Attribute {
ConstantValue_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
constantvalue_index = cr.readUnsignedShort();
}
public ConstantValue_attribute(ConstantPool constant_pool, int constantvalue_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.ConstantValue), constantvalue_index);
}
public ConstantValue_attribute(int name_index, int constantvalue_index) {
super(name_index, 2);
this.constantvalue_index = constantvalue_index;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitConstantValue(this, data);
}
public final int constantvalue_index;
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class DefaultAttribute extends Attribute {
DefaultAttribute(ClassReader cr, int name_index, byte[] data) {
this(cr, name_index, data, null);
}
DefaultAttribute(ClassReader cr, int name_index, byte[] data, String reason) {
super(name_index, data.length);
info = data;
this.reason = reason;
}
public DefaultAttribute(ConstantPool constant_pool, int name_index, byte[] info) {
this(constant_pool, name_index, info, null);
}
public DefaultAttribute(ConstantPool constant_pool, int name_index,
byte[] info, String reason) {
super(name_index, info.length);
this.info = info;
this.reason = reason;
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitDefault(this, p);
}
public final byte[] info;
/** Why did we need to generate a DefaultAttribute
*/
public final String reason;
}

View File

@@ -0,0 +1,794 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import com.sun.tools.classfile.Dependency.Filter;
import com.sun.tools.classfile.Dependency.Finder;
import com.sun.tools.classfile.Dependency.Location;
import com.sun.tools.classfile.Type.ArrayType;
import com.sun.tools.classfile.Type.ClassSigType;
import com.sun.tools.classfile.Type.ClassType;
import com.sun.tools.classfile.Type.MethodType;
import com.sun.tools.classfile.Type.SimpleType;
import com.sun.tools.classfile.Type.TypeParamType;
import com.sun.tools.classfile.Type.WildcardType;
import static com.sun.tools.classfile.ConstantPool.*;
/**
* A framework for determining {@link Dependency dependencies} between class files.
*
* A {@link Dependency.Finder finder} is used to identify the dependencies of
* individual classes. Some finders may return subtypes of {@code Dependency} to
* further characterize the type of dependency, such as a dependency on a
* method within a class.
*
* A {@link Dependency.Filter filter} may be used to restrict the set of
* dependencies found by a finder.
*
* Dependencies that are found may be passed to a {@link Dependencies.Recorder
* recorder} so that the dependencies can be stored in a custom data structure.
*/
public class Dependencies {
/**
* Thrown when a class file cannot be found.
*/
public static class ClassFileNotFoundException extends Exception {
private static final long serialVersionUID = 3632265927794475048L;
public ClassFileNotFoundException(String className) {
super(className);
this.className = className;
}
public ClassFileNotFoundException(String className, Throwable cause) {
this(className);
initCause(cause);
}
public final String className;
}
/**
* Thrown when an exception is found processing a class file.
*/
public static class ClassFileError extends Error {
private static final long serialVersionUID = 4111110813961313203L;
public ClassFileError(Throwable cause) {
initCause(cause);
}
}
/**
* Service provider interface to locate and read class files.
*/
public interface ClassFileReader {
/**
* Get the ClassFile object for a specified class.
* @param className the name of the class to be returned.
* @return the ClassFile for the given class
* @throws Dependencies.ClassFileNotFoundException if the classfile cannot be
* found
*/
public ClassFile getClassFile(String className)
throws ClassFileNotFoundException;
}
/**
* Service provide interface to handle results.
*/
public interface Recorder {
/**
* Record a dependency that has been found.
* @param d
*/
public void addDependency(Dependency d);
}
/**
* Get the default finder used to locate the dependencies for a class.
* @return the default finder
*/
public static Finder getDefaultFinder() {
return new APIDependencyFinder(AccessFlags.ACC_PRIVATE);
}
/**
* Get a finder used to locate the API dependencies for a class.
* These include the superclass, superinterfaces, and classes referenced in
* the declarations of fields and methods. The fields and methods that
* are checked can be limited according to a specified access.
* The access parameter must be one of {@link AccessFlags#ACC_PUBLIC ACC_PUBLIC},
* {@link AccessFlags#ACC_PRIVATE ACC_PRIVATE},
* {@link AccessFlags#ACC_PROTECTED ACC_PROTECTED}, or 0 for
* package private access. Members with greater than or equal accessibility
* to that specified will be searched for dependencies.
* @param access the access of members to be checked
* @return an API finder
*/
public static Finder getAPIFinder(int access) {
return new APIDependencyFinder(access);
}
/**
* Get a finder to do class dependency analysis.
*
* @return a Class dependency finder
*/
public static Finder getClassDependencyFinder() {
return new ClassDependencyFinder();
}
/**
* Get the finder used to locate the dependencies for a class.
* @return the finder
*/
public Finder getFinder() {
if (finder == null)
finder = getDefaultFinder();
return finder;
}
/**
* Set the finder used to locate the dependencies for a class.
* @param f the finder
*/
public void setFinder(Finder f) {
f.getClass(); // null check
finder = f;
}
/**
* Get the default filter used to determine included when searching
* the transitive closure of all the dependencies.
* Unless overridden, the default filter accepts all dependencies.
* @return the default filter.
*/
public static Filter getDefaultFilter() {
return DefaultFilter.instance();
}
/**
* Get a filter which uses a regular expression on the target's class name
* to determine if a dependency is of interest.
* @param pattern the pattern used to match the target's class name
* @return a filter for matching the target class name with a regular expression
*/
public static Filter getRegexFilter(Pattern pattern) {
return new TargetRegexFilter(pattern);
}
/**
* Get a filter which checks the package of a target's class name
* to determine if a dependency is of interest. The filter checks if the
* package of the target's class matches any of a set of given package
* names. The match may optionally match subpackages of the given names as well.
* @param packageNames the package names used to match the target's class name
* @param matchSubpackages whether or not to match subpackages as well
* @return a filter for checking the target package name against a list of package names
*/
public static Filter getPackageFilter(Set<String> packageNames, boolean matchSubpackages) {
return new TargetPackageFilter(packageNames, matchSubpackages);
}
/**
* Get the filter used to determine the dependencies included when searching
* the transitive closure of all the dependencies.
* Unless overridden, the default filter accepts all dependencies.
* @return the filter
*/
public Filter getFilter() {
if (filter == null)
filter = getDefaultFilter();
return filter;
}
/**
* Set the filter used to determine the dependencies included when searching
* the transitive closure of all the dependencies.
* @param f the filter
*/
public void setFilter(Filter f) {
f.getClass(); // null check
filter = f;
}
/**
* Find the dependencies of a class, using the current
* {@link Dependencies#getFinder finder} and
* {@link Dependencies#getFilter filter}.
* The search may optionally include the transitive closure of all the
* filtered dependencies, by also searching in the classes named in those
* dependencies.
* @param classFinder a finder to locate class files
* @param rootClassNames the names of the root classes from which to begin
* searching
* @param transitiveClosure whether or not to also search those classes
* named in any filtered dependencies that are found.
* @return the set of dependencies that were found
* @throws ClassFileNotFoundException if a required class file cannot be found
* @throws ClassFileError if an error occurs while processing a class file,
* such as an error in the internal class file structure.
*/
public Set<Dependency> findAllDependencies(
ClassFileReader classFinder, Set<String> rootClassNames,
boolean transitiveClosure)
throws ClassFileNotFoundException {
final Set<Dependency> results = new HashSet<Dependency>();
Recorder r = new Recorder() {
public void addDependency(Dependency d) {
results.add(d);
}
};
findAllDependencies(classFinder, rootClassNames, transitiveClosure, r);
return results;
}
/**
* Find the dependencies of a class, using the current
* {@link Dependencies#getFinder finder} and
* {@link Dependencies#getFilter filter}.
* The search may optionally include the transitive closure of all the
* filtered dependencies, by also searching in the classes named in those
* dependencies.
* @param classFinder a finder to locate class files
* @param rootClassNames the names of the root classes from which to begin
* searching
* @param transitiveClosure whether or not to also search those classes
* named in any filtered dependencies that are found.
* @param recorder a recorder for handling the results
* @throws ClassFileNotFoundException if a required class file cannot be found
* @throws ClassFileError if an error occurs while processing a class file,
* such as an error in the internal class file structure.
*/
public void findAllDependencies(
ClassFileReader classFinder, Set<String> rootClassNames,
boolean transitiveClosure, Recorder recorder)
throws ClassFileNotFoundException {
Set<String> doneClasses = new HashSet<String>();
getFinder(); // ensure initialized
getFilter(); // ensure initialized
// Work queue of names of classfiles to be searched.
// Entries will be unique, and for classes that do not yet have
// dependencies in the results map.
Deque<String> deque = new LinkedList<String>(rootClassNames);
String className;
while ((className = deque.poll()) != null) {
assert (!doneClasses.contains(className));
doneClasses.add(className);
ClassFile cf = classFinder.getClassFile(className);
// The following code just applies the filter to the dependencies
// followed for the transitive closure.
for (Dependency d: finder.findDependencies(cf)) {
recorder.addDependency(d);
if (transitiveClosure && filter.accepts(d)) {
String cn = d.getTarget().getClassName();
if (!doneClasses.contains(cn))
deque.add(cn);
}
}
}
}
private Filter filter;
private Finder finder;
/**
* A location identifying a class.
*/
static class SimpleLocation implements Location {
public SimpleLocation(String name) {
this.name = name;
this.className = name.replace('/', '.');
}
public String getName() {
return name;
}
public String getClassName() {
return className;
}
public String getPackageName() {
int i = name.lastIndexOf('/');
return (i > 0) ? name.substring(0, i).replace('/', '.') : "";
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof SimpleLocation))
return false;
return (name.equals(((SimpleLocation) other).name));
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
private String name;
private String className;
}
/**
* A dependency of one class on another.
*/
static class SimpleDependency implements Dependency {
public SimpleDependency(Location origin, Location target) {
this.origin = origin;
this.target = target;
}
public Location getOrigin() {
return origin;
}
public Location getTarget() {
return target;
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof SimpleDependency))
return false;
SimpleDependency o = (SimpleDependency) other;
return (origin.equals(o.origin) && target.equals(o.target));
}
@Override
public int hashCode() {
return origin.hashCode() * 31 + target.hashCode();
}
@Override
public String toString() {
return origin + ":" + target;
}
private Location origin;
private Location target;
}
/**
* This class accepts all dependencies.
*/
static class DefaultFilter implements Filter {
private static DefaultFilter instance;
static DefaultFilter instance() {
if (instance == null)
instance = new DefaultFilter();
return instance;
}
public boolean accepts(Dependency dependency) {
return true;
}
}
/**
* This class accepts those dependencies whose target's class name matches a
* regular expression.
*/
static class TargetRegexFilter implements Filter {
TargetRegexFilter(Pattern pattern) {
this.pattern = pattern;
}
public boolean accepts(Dependency dependency) {
return pattern.matcher(dependency.getTarget().getClassName()).matches();
}
private final Pattern pattern;
}
/**
* This class accepts those dependencies whose class name is in a given
* package.
*/
static class TargetPackageFilter implements Filter {
TargetPackageFilter(Set<String> packageNames, boolean matchSubpackages) {
for (String pn: packageNames) {
if (pn.length() == 0) // implies null check as well
throw new IllegalArgumentException();
}
this.packageNames = packageNames;
this.matchSubpackages = matchSubpackages;
}
public boolean accepts(Dependency dependency) {
String pn = dependency.getTarget().getPackageName();
if (packageNames.contains(pn))
return true;
if (matchSubpackages) {
for (String n: packageNames) {
if (pn.startsWith(n + "."))
return true;
}
}
return false;
}
private final Set<String> packageNames;
private final boolean matchSubpackages;
}
/**
* This class identifies class names directly or indirectly in the constant pool.
*/
static class ClassDependencyFinder extends BasicDependencyFinder {
public Iterable<? extends Dependency> findDependencies(ClassFile classfile) {
Visitor v = new Visitor(classfile);
for (CPInfo cpInfo: classfile.constant_pool.entries()) {
v.scan(cpInfo);
}
try {
v.addClass(classfile.super_class);
v.addClasses(classfile.interfaces);
v.scan(classfile.attributes);
for (Field f : classfile.fields) {
v.scan(f.descriptor, f.attributes);
}
for (Method m : classfile.methods) {
v.scan(m.descriptor, m.attributes);
Exceptions_attribute e =
(Exceptions_attribute)m.attributes.get(Attribute.Exceptions);
if (e != null) {
v.addClasses(e.exception_index_table);
}
}
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
return v.deps;
}
}
/**
* This class identifies class names in the signatures of classes, fields,
* and methods in a class.
*/
static class APIDependencyFinder extends BasicDependencyFinder {
APIDependencyFinder(int access) {
switch (access) {
case AccessFlags.ACC_PUBLIC:
case AccessFlags.ACC_PROTECTED:
case AccessFlags.ACC_PRIVATE:
case 0:
showAccess = access;
break;
default:
throw new IllegalArgumentException("invalid access 0x"
+ Integer.toHexString(access));
}
}
public Iterable<? extends Dependency> findDependencies(ClassFile classfile) {
try {
Visitor v = new Visitor(classfile);
v.addClass(classfile.super_class);
v.addClasses(classfile.interfaces);
// inner classes?
for (Field f : classfile.fields) {
if (checkAccess(f.access_flags))
v.scan(f.descriptor, f.attributes);
}
for (Method m : classfile.methods) {
if (checkAccess(m.access_flags)) {
v.scan(m.descriptor, m.attributes);
Exceptions_attribute e =
(Exceptions_attribute) m.attributes.get(Attribute.Exceptions);
if (e != null)
v.addClasses(e.exception_index_table);
}
}
return v.deps;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
boolean checkAccess(AccessFlags flags) {
// code copied from javap.Options.checkAccess
boolean isPublic = flags.is(AccessFlags.ACC_PUBLIC);
boolean isProtected = flags.is(AccessFlags.ACC_PROTECTED);
boolean isPrivate = flags.is(AccessFlags.ACC_PRIVATE);
boolean isPackage = !(isPublic || isProtected || isPrivate);
if ((showAccess == AccessFlags.ACC_PUBLIC) && (isProtected || isPrivate || isPackage))
return false;
else if ((showAccess == AccessFlags.ACC_PROTECTED) && (isPrivate || isPackage))
return false;
else if ((showAccess == 0) && (isPrivate))
return false;
else
return true;
}
private int showAccess;
}
static abstract class BasicDependencyFinder implements Finder {
private Map<String,Location> locations = new HashMap<String,Location>();
Location getLocation(String className) {
Location l = locations.get(className);
if (l == null)
locations.put(className, l = new SimpleLocation(className));
return l;
}
class Visitor implements ConstantPool.Visitor<Void,Void>, Type.Visitor<Void, Void> {
private ConstantPool constant_pool;
private Location origin;
Set<Dependency> deps;
Visitor(ClassFile classFile) {
try {
constant_pool = classFile.constant_pool;
origin = getLocation(classFile.getName());
deps = new HashSet<Dependency>();
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
void scan(Descriptor d, Attributes attrs) {
try {
scan(new Signature(d.index).getType(constant_pool));
scan(attrs);
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
void scan(CPInfo cpInfo) {
cpInfo.accept(this, null);
}
void scan(Type t) {
t.accept(this, null);
}
void scan(Attributes attrs) {
try {
Signature_attribute sa = (Signature_attribute)attrs.get(Attribute.Signature);
if (sa != null)
scan(sa.getParsedSignature().getType(constant_pool));
scan((RuntimeVisibleAnnotations_attribute)
attrs.get(Attribute.RuntimeVisibleAnnotations));
scan((RuntimeVisibleParameterAnnotations_attribute)
attrs.get(Attribute.RuntimeVisibleParameterAnnotations));
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
private void scan(RuntimeAnnotations_attribute attr) throws ConstantPoolException {
if (attr == null) {
return;
}
for (int i = 0; i < attr.annotations.length; i++) {
int index = attr.annotations[i].type_index;
scan(new Signature(index).getType(constant_pool));
}
}
private void scan(RuntimeParameterAnnotations_attribute attr) throws ConstantPoolException {
if (attr == null) {
return;
}
for (int param = 0; param < attr.parameter_annotations.length; param++) {
for (int i = 0; i < attr.parameter_annotations[param].length; i++) {
int index = attr.parameter_annotations[param][i].type_index;
scan(new Signature(index).getType(constant_pool));
}
}
}
void addClass(int index) throws ConstantPoolException {
if (index != 0) {
String name = constant_pool.getClassInfo(index).getBaseName();
if (name != null)
addDependency(name);
}
}
void addClasses(int[] indices) throws ConstantPoolException {
for (int i: indices)
addClass(i);
}
private void addDependency(String name) {
deps.add(new SimpleDependency(origin, getLocation(name)));
}
// ConstantPool.Visitor methods
public Void visitClass(CONSTANT_Class_info info, Void p) {
try {
if (info.getName().startsWith("["))
new Signature(info.name_index).getType(constant_pool).accept(this, null);
else
addDependency(info.getBaseName());
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
public Void visitDouble(CONSTANT_Double_info info, Void p) {
return null;
}
public Void visitFieldref(CONSTANT_Fieldref_info info, Void p) {
return visitRef(info, p);
}
public Void visitFloat(CONSTANT_Float_info info, Void p) {
return null;
}
public Void visitInteger(CONSTANT_Integer_info info, Void p) {
return null;
}
public Void visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, Void p) {
return visitRef(info, p);
}
public Void visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, Void p) {
return null;
}
public Void visitLong(CONSTANT_Long_info info, Void p) {
return null;
}
public Void visitMethodHandle(CONSTANT_MethodHandle_info info, Void p) {
return null;
}
public Void visitMethodType(CONSTANT_MethodType_info info, Void p) {
return null;
}
public Void visitMethodref(CONSTANT_Methodref_info info, Void p) {
return visitRef(info, p);
}
public Void visitNameAndType(CONSTANT_NameAndType_info info, Void p) {
try {
new Signature(info.type_index).getType(constant_pool).accept(this, null);
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
public Void visitString(CONSTANT_String_info info, Void p) {
return null;
}
public Void visitUtf8(CONSTANT_Utf8_info info, Void p) {
return null;
}
private Void visitRef(CPRefInfo info, Void p) {
try {
visitClass(info.getClassInfo(), p);
return null;
} catch (ConstantPoolException e) {
throw new ClassFileError(e);
}
}
// Type.Visitor methods
private void findDependencies(Type t) {
if (t != null)
t.accept(this, null);
}
private void findDependencies(List<? extends Type> ts) {
if (ts != null) {
for (Type t: ts)
t.accept(this, null);
}
}
public Void visitSimpleType(SimpleType type, Void p) {
return null;
}
public Void visitArrayType(ArrayType type, Void p) {
findDependencies(type.elemType);
return null;
}
public Void visitMethodType(MethodType type, Void p) {
findDependencies(type.paramTypes);
findDependencies(type.returnType);
findDependencies(type.throwsTypes);
findDependencies(type.typeParamTypes);
return null;
}
public Void visitClassSigType(ClassSigType type, Void p) {
findDependencies(type.superclassType);
findDependencies(type.superinterfaceTypes);
return null;
}
public Void visitClassType(ClassType type, Void p) {
findDependencies(type.outerType);
addDependency(type.getBinaryName());
findDependencies(type.typeArgs);
return null;
}
public Void visitTypeParamType(TypeParamType type, Void p) {
findDependencies(type.classBound);
findDependencies(type.interfaceBounds);
return null;
}
public Void visitWildcardType(WildcardType type, Void p) {
findDependencies(type.boundType);
return null;
}
}
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/**
* A directed relationship between two {@link Dependency.Location Location}s.
* Subtypes of {@code Dependency} may provide additional detail about the dependency.
*
* @see Dependency.Finder
* @see Dependency.Filter
* @see Dependencies
*/
public interface Dependency {
/**
* A filter used to select dependencies of interest, and to discard others.
*/
public interface Filter {
/**
* Return true if the dependency is of interest.
* @param dependency the dependency to be considered
* @return true if and only if the dependency is of interest.
*/
boolean accepts(Dependency dependency);
}
/**
* An interface for finding the immediate dependencies of a given class file.
*/
public interface Finder {
/**
* Find the immediate dependencies of a given class file.
* @param classfile the class file to be examined
* @return the dependencies located in the given class file.
*/
public Iterable<? extends Dependency> findDependencies(ClassFile classfile);
}
/**
* A location somewhere within a class. Subtypes of {@code Location}
* may be used to provide additional detail about the location.
*/
public interface Location {
/**
* Get the name of the class containing the location.
* This name will be used to locate the class file for transitive
* dependency analysis.
* @return the name of the class containing the location.
*/
String getName();
/**
* Get the fully-qualified name of the class containing the location.
* @return the fully-qualified name of the class containing the location.
*/
String getClassName();
/**
* Get the package name of the class containing the location.
* @return the package name of the class containing the location.
*/
String getPackageName();
}
/**
* Get the location that has the dependency.
* @return the location that has the dependency.
*/
Location getOrigin();
/**
* Get the location that is being depended upon.
* @return the location that is being depended upon.
*/
Location getTarget();
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.15.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Deprecated_attribute extends Attribute {
Deprecated_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
}
public Deprecated_attribute(ConstantPool constant_pool)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Deprecated));
}
public Deprecated_attribute(int name_index) {
super(name_index, 0);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitDeprecated(this, data);
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.4.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Descriptor {
public static class InvalidDescriptor extends DescriptorException {
private static final long serialVersionUID = 1L;
InvalidDescriptor(String desc) {
this.desc = desc;
this.index = -1;
}
InvalidDescriptor(String desc, int index) {
this.desc = desc;
this.index = index;
}
@Override
public String getMessage() {
// i18n
if (index == -1)
return "invalid descriptor \"" + desc + "\"";
else
return "descriptor is invalid at offset " + index + " in \"" + desc + "\"";
}
public final String desc;
public final int index;
}
public Descriptor(ClassReader cr) throws IOException {
this(cr.readUnsignedShort());
}
public Descriptor(int index) {
this.index = index;
}
public String getValue(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(index);
}
public int getParameterCount(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
parse(desc, 0, end + 1);
return count;
}
public String getParameterTypes(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
return parse(desc, 0, end + 1);
}
public String getReturnType(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
int end = desc.indexOf(")");
if (end == -1)
throw new InvalidDescriptor(desc);
return parse(desc, end + 1, desc.length());
}
public String getFieldType(ConstantPool constant_pool)
throws ConstantPoolException, InvalidDescriptor {
String desc = getValue(constant_pool);
return parse(desc, 0, desc.length());
}
private String parse(String desc, int start, int end)
throws InvalidDescriptor {
int p = start;
StringBuilder sb = new StringBuilder();
int dims = 0;
count = 0;
while (p < end) {
String type;
char ch;
switch (ch = desc.charAt(p++)) {
case '(':
sb.append('(');
continue;
case ')':
sb.append(')');
continue;
case '[':
dims++;
continue;
case 'B':
type = "byte";
break;
case 'C':
type = "char";
break;
case 'D':
type = "double";
break;
case 'F':
type = "float";
break;
case 'I':
type = "int";
break;
case 'J':
type = "long";
break;
case 'L':
int sep = desc.indexOf(';', p);
if (sep == -1)
throw new InvalidDescriptor(desc, p - 1);
type = desc.substring(p, sep).replace('/', '.');
p = sep + 1;
break;
case 'S':
type = "short";
break;
case 'Z':
type = "boolean";
break;
case 'V':
type = "void";
break;
default:
throw new InvalidDescriptor(desc, p - 1);
}
if (sb.length() > 1 && sb.charAt(0) == '(')
sb.append(", ");
sb.append(type);
for ( ; dims > 0; dims-- )
sb.append("[]");
count++;
}
return sb.toString();
}
public final int index;
private int count;
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class DescriptorException extends Exception {
private static final long serialVersionUID = 2411890273788901032L;
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.7.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class EnclosingMethod_attribute extends Attribute {
EnclosingMethod_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
class_index = cr.readUnsignedShort();
method_index = cr.readUnsignedShort();
}
public EnclosingMethod_attribute(ConstantPool constant_pool, int class_index, int method_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.EnclosingMethod), class_index, method_index);
}
public EnclosingMethod_attribute(int name_index, int class_index, int method_index) {
super(name_index, 4);
this.class_index = class_index;
this.method_index = method_index;
}
public String getClassName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getClassInfo(class_index).getName();
}
public String getMethodName(ConstantPool constant_pool) throws ConstantPoolException {
if (method_index == 0)
return "";
return constant_pool.getNameAndTypeInfo(method_index).getName();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitEnclosingMethod(this, data);
}
public final int class_index;
public final int method_index;
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.5.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Exceptions_attribute extends Attribute {
Exceptions_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
number_of_exceptions = cr.readUnsignedShort();
exception_index_table = new int[number_of_exceptions];
for (int i = 0; i < number_of_exceptions; i++)
exception_index_table[i] = cr.readUnsignedShort();
}
public Exceptions_attribute(ConstantPool constant_pool, int[] exception_index_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Exceptions), exception_index_table);
}
public Exceptions_attribute(int name_index, int[] exception_index_table) {
super(name_index, 2 + 2 * exception_index_table.length);
this.number_of_exceptions = exception_index_table.length;
this.exception_index_table = exception_index_table;
}
public String getException(int index, ConstantPool constant_pool) throws ConstantPoolException {
int exception_index = exception_index_table[index];
return constant_pool.getClassInfo(exception_index).getName();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitExceptions(this, data);
}
public final int number_of_exceptions;
public final int[] exception_index_table;
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Field {
Field(ClassReader cr) throws IOException {
access_flags = new AccessFlags(cr);
name_index = cr.readUnsignedShort();
descriptor = new Descriptor(cr);
attributes = new Attributes(cr);
}
public Field(AccessFlags access_flags,
int name_index, Descriptor descriptor,
Attributes attributes) {
this.access_flags = access_flags;
this.name_index = name_index;
this.descriptor = descriptor;
this.attributes = attributes;
}
public int byteLength() {
return 6 + attributes.byteLength();
}
public String getName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(name_index);
}
public final AccessFlags access_flags;
public final int name_index;
public final Descriptor descriptor;
public final Attributes attributes;
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import com.sun.tools.classfile.ConstantPool.*;
/**
* See JVMS, section 4.8.6.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class InnerClasses_attribute extends Attribute {
InnerClasses_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
number_of_classes = cr.readUnsignedShort();
classes = new Info[number_of_classes];
for (int i = 0; i < number_of_classes; i++)
classes[i] = new Info(cr);
}
public InnerClasses_attribute(ConstantPool constant_pool, Info[] classes)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.InnerClasses), classes);
}
public InnerClasses_attribute(int name_index, Info[] classes) {
super(name_index, 2 + Info.length() * classes.length);
this.number_of_classes = classes.length;
this.classes = classes;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInnerClasses(this, data);
}
public final int number_of_classes;
public final Info[] classes;
public static class Info {
Info(ClassReader cr) throws IOException {
inner_class_info_index = cr.readUnsignedShort();
outer_class_info_index = cr.readUnsignedShort();
inner_name_index = cr.readUnsignedShort();
inner_class_access_flags = new AccessFlags(cr.readUnsignedShort());
}
public CONSTANT_Class_info getInnerClassInfo(ConstantPool constant_pool) throws ConstantPoolException {
if (inner_class_info_index == 0)
return null;
return constant_pool.getClassInfo(inner_class_info_index);
}
public CONSTANT_Class_info getOuterClassInfo(ConstantPool constant_pool) throws ConstantPoolException {
if (outer_class_info_index == 0)
return null;
return constant_pool.getClassInfo(outer_class_info_index);
}
public String getInnerName(ConstantPool constant_pool) throws ConstantPoolException {
if (inner_name_index == 0)
return null;
return constant_pool.getUTF8Value(inner_name_index);
}
public static int length() {
return 8;
}
public final int inner_class_info_index;
public final int outer_class_info_index;
public final int inner_name_index;
public final AccessFlags inner_class_access_flags;
}
}

View File

@@ -0,0 +1,353 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.Locale;
/**
* See JVMS, chapter 6.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @see Code_attribute#getInstructions
*/
public class Instruction {
/** The kind of an instruction, as determined by the position, size and
* types of its operands. */
public static enum Kind {
/** Opcode is not followed by any operands. */
NO_OPERANDS(1),
/** Opcode is followed by a byte indicating a type. */
ATYPE(2),
/** Opcode is followed by a 2-byte branch offset. */
BRANCH(3),
/** Opcode is followed by a 4-byte branch offset. */
BRANCH_W(5),
/** Opcode is followed by a signed byte value. */
BYTE(2),
/** Opcode is followed by a 1-byte index into the constant pool. */
CPREF(2),
/** Opcode is followed by a 2-byte index into the constant pool. */
CPREF_W(3),
/** Opcode is followed by a 2-byte index into the constant pool,
* an unsigned byte value. */
CPREF_W_UBYTE(4),
/** Opcode is followed by a 2-byte index into the constant pool.,
* an unsigned byte value, and a zero byte. */
CPREF_W_UBYTE_ZERO(5),
/** Opcode is followed by variable number of operands, depending
* on the instruction.*/
DYNAMIC(-1),
/** Opcode is followed by a 1-byte reference to a local variable. */
LOCAL(2),
/** Opcode is followed by a 1-byte reference to a local variable,
* and a signed byte value. */
LOCAL_BYTE(3),
/** Opcode is followed by a signed short value. */
SHORT(3),
/** Wide opcode is not followed by any operands. */
WIDE_NO_OPERANDS(2),
/** Wide opcode is followed by a 2-byte index into the local variables array. */
WIDE_LOCAL(4),
/** Wide opcode is followed by a 2-byte index into the constant pool. */
WIDE_CPREF_W(4),
/** Wide opcode is followed by a 2-byte index into the constant pool,
* and a signed short value. */
WIDE_CPREF_W_SHORT(6),
/** Wide opcode is followed by a 2-byte reference to a local variable,
* and a signed short value. */
WIDE_LOCAL_SHORT(6),
/** Opcode was not recognized. */
UNKNOWN(1);
Kind(int length) {
this.length = length;
}
/** The length, in bytes, of this kind of instruction, or -1 is the
* length depends on the specific instruction. */
public final int length;
};
/** A utility visitor to help decode the operands of an instruction.
* @see Instruction#accept */
public interface KindVisitor<R,P> {
/** See {@link Kind#NO_OPERANDS}, {@link Kind#WIDE_NO_OPERANDS}. */
R visitNoOperands(Instruction instr, P p);
/** See {@link Kind#ATYPE}. */
R visitArrayType(Instruction instr, TypeKind kind, P p);
/** See {@link Kind#BRANCH}, {@link Kind#BRANCH_W}. */
R visitBranch(Instruction instr, int offset, P p);
/** See {@link Kind#CPREF}, {@link Kind#CPREF_W}, {@link Kind#WIDE_CPREF_W}. */
R visitConstantPoolRef(Instruction instr, int index, P p);
/** See {@link Kind#CPREF_W_UBYTE}, {@link Kind#CPREF_W_UBYTE_ZERO}, {@link Kind#WIDE_CPREF_W_SHORT}. */
R visitConstantPoolRefAndValue(Instruction instr, int index, int value, P p);
/** See {@link Kind#LOCAL}, {@link Kind#WIDE_LOCAL}. */
R visitLocal(Instruction instr, int index, P p);
/** See {@link Kind#LOCAL_BYTE}. */
R visitLocalAndValue(Instruction instr, int index, int value, P p);
/** See {@link Kind#DYNAMIC}. */
R visitLookupSwitch(Instruction instr, int default_, int npairs, int[] matches, int[] offsets, P p);
/** See {@link Kind#DYNAMIC}. */
R visitTableSwitch(Instruction instr, int default_, int low, int high, int[] offsets, P p);
/** See {@link Kind#BYTE}, {@link Kind#SHORT}. */
R visitValue(Instruction instr, int value, P p);
/** Instruction is unrecognized. */
R visitUnknown(Instruction instr, P p);
}
/** The kind of primitive array type to create.
* See JVMS chapter 6, newarray. */
public static enum TypeKind {
T_BOOLEAN(4, "boolean"),
T_CHAR(5, "char"),
T_FLOAT(6, "float"),
T_DOUBLE(7, "double"),
T_BYTE(8, "byte"),
T_SHORT(9, "short"),
T_INT (10, "int"),
T_LONG (11, "long");
TypeKind(int value, String name) {
this.value = value;
this.name = name;
}
public static TypeKind get(int value) {
switch (value) {
case 4: return T_BOOLEAN;
case 5: return T_CHAR;
case 6: return T_FLOAT;
case 7: return T_DOUBLE;
case 8: return T_BYTE;
case 9: return T_SHORT;
case 10: return T_INT;
case 11: return T_LONG;
default: return null;
}
}
public final int value;
public final String name;
}
/** An instruction is defined by its position in a bytecode array. */
public Instruction(byte[] bytes, int pc) {
this.bytes = bytes;
this.pc = pc;
}
/** Get the position of the instruction within the bytecode array. */
public int getPC() {
return pc;
}
/** Get a byte value, relative to the start of this instruction. */
public int getByte(int offset) {
return bytes[pc + offset];
}
/** Get an unsigned byte value, relative to the start of this instruction. */
public int getUnsignedByte(int offset) {
return getByte(offset) & 0xff;
}
/** Get a 2-byte value, relative to the start of this instruction. */
public int getShort(int offset) {
return (getByte(offset) << 8) | getUnsignedByte(offset + 1);
}
/** Get a unsigned 2-byte value, relative to the start of this instruction. */
public int getUnsignedShort(int offset) {
return getShort(offset) & 0xFFFF;
}
/** Get a 4-byte value, relative to the start of this instruction. */
public int getInt(int offset) {
return (getShort(offset) << 16) | (getUnsignedShort(offset + 2));
}
/** Get the Opcode for this instruction, or null if the instruction is
* unrecognized. */
public Opcode getOpcode() {
int b = getUnsignedByte(0);
switch (b) {
case Opcode.NONPRIV:
case Opcode.PRIV:
case Opcode.WIDE:
return Opcode.get(b, getUnsignedByte(1));
}
return Opcode.get(b);
}
/** Get the mnemonic for this instruction, or a default string if the
* instruction is unrecognized. */
public String getMnemonic() {
Opcode opcode = getOpcode();
if (opcode == null)
return "bytecode " + getUnsignedByte(0);
else
return opcode.toString().toLowerCase(Locale.US);
}
/** Get the length, in bytes, of this instruction, including the opcode
* and all its operands. */
public int length() {
Opcode opcode = getOpcode();
if (opcode == null)
return 1;
switch (opcode) {
case TABLESWITCH: {
int pad = align(pc + 1) - pc;
int low = getInt(pad + 4);
int high = getInt(pad + 8);
return pad + 12 + 4 * (high - low + 1);
}
case LOOKUPSWITCH: {
int pad = align(pc + 1) - pc;
int npairs = getInt(pad + 4);
return pad + 8 + 8 * npairs;
}
default:
return opcode.kind.length;
}
}
/** Get the {@link Kind} of this instruction. */
public Kind getKind() {
Opcode opcode = getOpcode();
return (opcode != null ? opcode.kind : Kind.UNKNOWN);
}
/** Invoke a method on the visitor according to the kind of this
* instruction, passing in the decoded operands for the instruction. */
public <R,P> R accept(KindVisitor<R,P> visitor, P p) {
switch (getKind()) {
case NO_OPERANDS:
return visitor.visitNoOperands(this, p);
case ATYPE:
return visitor.visitArrayType(
this, TypeKind.get(getUnsignedByte(1)), p);
case BRANCH:
return visitor.visitBranch(this, getShort(1), p);
case BRANCH_W:
return visitor.visitBranch(this, getInt(1), p);
case BYTE:
return visitor.visitValue(this, getByte(1), p);
case CPREF:
return visitor.visitConstantPoolRef(this, getUnsignedByte(1), p);
case CPREF_W:
return visitor.visitConstantPoolRef(this, getUnsignedShort(1), p);
case CPREF_W_UBYTE:
case CPREF_W_UBYTE_ZERO:
return visitor.visitConstantPoolRefAndValue(
this, getUnsignedShort(1), getUnsignedByte(3), p);
case DYNAMIC: {
switch (getOpcode()) {
case TABLESWITCH: {
int pad = align(pc + 1) - pc;
int default_ = getInt(pad);
int low = getInt(pad + 4);
int high = getInt(pad + 8);
int[] values = new int[high - low + 1];
for (int i = 0; i < values.length; i++)
values[i] = getInt(pad + 12 + 4 * i);
return visitor.visitTableSwitch(
this, default_, low, high, values, p);
}
case LOOKUPSWITCH: {
int pad = align(pc + 1) - pc;
int default_ = getInt(pad);
int npairs = getInt(pad + 4);
int[] matches = new int[npairs];
int[] offsets = new int[npairs];
for (int i = 0; i < npairs; i++) {
matches[i] = getInt(pad + 8 + i * 8);
offsets[i] = getInt(pad + 12 + i * 8);
}
return visitor.visitLookupSwitch(
this, default_, npairs, matches, offsets, p);
}
default:
throw new IllegalStateException();
}
}
case LOCAL:
return visitor.visitLocal(this, getUnsignedByte(1), p);
case LOCAL_BYTE:
return visitor.visitLocalAndValue(
this, getUnsignedByte(1), getByte(2), p);
case SHORT:
return visitor.visitValue(this, getShort(1), p);
case WIDE_NO_OPERANDS:
return visitor.visitNoOperands(this, p);
case WIDE_LOCAL:
return visitor.visitLocal(this, getUnsignedShort(2), p);
case WIDE_CPREF_W:
return visitor.visitConstantPoolRef(this, getUnsignedShort(2), p);
case WIDE_CPREF_W_SHORT:
return visitor.visitConstantPoolRefAndValue(
this, getUnsignedShort(2), getUnsignedByte(4), p);
case WIDE_LOCAL_SHORT:
return visitor.visitLocalAndValue(
this, getUnsignedShort(2), getShort(4), p);
case UNKNOWN:
return visitor.visitUnknown(this, p);
default:
throw new IllegalStateException();
}
}
private static int align(int n) {
return (n + 3) & ~3;
}
private byte[] bytes;
private int pc;
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.12.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class LineNumberTable_attribute extends Attribute {
LineNumberTable_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
line_number_table_length = cr.readUnsignedShort();
line_number_table = new Entry[line_number_table_length];
for (int i = 0; i < line_number_table_length; i++)
line_number_table[i] = new Entry(cr);
}
public LineNumberTable_attribute(ConstantPool constant_pool, Entry[] line_number_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.LineNumberTable), line_number_table);
}
public LineNumberTable_attribute(int name_index, Entry[] line_number_table) {
super(name_index, 2 + line_number_table.length * Entry.length());
this.line_number_table_length = line_number_table.length;
this.line_number_table = line_number_table;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitLineNumberTable(this, data);
}
public final int line_number_table_length;
public final Entry[] line_number_table;
public static class Entry {
Entry(ClassReader cr) throws IOException {
start_pc = cr.readUnsignedShort();
line_number = cr.readUnsignedShort();
}
public static int length() {
return 4;
}
public final int start_pc;
public final int line_number;
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.13.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class LocalVariableTable_attribute extends Attribute {
LocalVariableTable_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
local_variable_table_length = cr.readUnsignedShort();
local_variable_table = new Entry[local_variable_table_length];
for (int i = 0; i < local_variable_table_length; i++)
local_variable_table[i] = new Entry(cr);
}
public LocalVariableTable_attribute(ConstantPool constant_pool, Entry[] local_variable_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.LocalVariableTable), local_variable_table);
}
public LocalVariableTable_attribute(int name_index, Entry[] local_variable_table) {
super(name_index, 2 + local_variable_table.length * Entry.length());
this.local_variable_table_length = local_variable_table.length;
this.local_variable_table = local_variable_table;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitLocalVariableTable(this, data);
}
public final int local_variable_table_length;
public final Entry[] local_variable_table;
public static class Entry {
Entry(ClassReader cr) throws IOException {
start_pc = cr.readUnsignedShort();
length = cr.readUnsignedShort();
name_index = cr.readUnsignedShort();
descriptor_index = cr.readUnsignedShort();
index = cr.readUnsignedShort();
}
public static int length() {
return 10;
}
public final int start_pc;
public final int length;
public final int name_index;
public final int descriptor_index;
public final int index;
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.14.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class LocalVariableTypeTable_attribute extends Attribute {
LocalVariableTypeTable_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
local_variable_table_length = cr.readUnsignedShort();
local_variable_table = new Entry[local_variable_table_length];
for (int i = 0; i < local_variable_table_length; i++)
local_variable_table[i] = new Entry(cr);
}
public LocalVariableTypeTable_attribute(ConstantPool constant_pool, Entry[] local_variable_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.LocalVariableTypeTable), local_variable_table);
}
public LocalVariableTypeTable_attribute(int name_index, Entry[] local_variable_table) {
super(name_index, 2 + local_variable_table.length * Entry.length());
this.local_variable_table_length = local_variable_table.length;
this.local_variable_table = local_variable_table;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitLocalVariableTypeTable(this, data);
}
public final int local_variable_table_length;
public final Entry[] local_variable_table;
public static class Entry {
Entry(ClassReader cr) throws IOException {
start_pc = cr.readUnsignedShort();
length = cr.readUnsignedShort();
name_index = cr.readUnsignedShort();
signature_index = cr.readUnsignedShort();
index = cr.readUnsignedShort();
}
public static int length() {
return 10;
}
public final int start_pc;
public final int length;
public final int name_index;
public final int signature_index;
public final int index;
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Method {
Method(ClassReader cr) throws IOException {
access_flags = new AccessFlags(cr);
name_index = cr.readUnsignedShort();
descriptor = new Descriptor(cr);
attributes = new Attributes(cr);
}
public Method(AccessFlags access_flags,
int name_index, Descriptor descriptor,
Attributes attributes) {
this.access_flags = access_flags;
this.name_index = name_index;
this.descriptor = descriptor;
this.attributes = attributes;
}
public int byteLength() {
return 6 + attributes.byteLength();
}
public String getName(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(name_index);
}
public final AccessFlags access_flags;
public final int name_index;
public final Descriptor descriptor;
public final Attributes attributes;
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.13.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class MethodParameters_attribute extends Attribute {
public final int method_parameter_table_length;
public final Entry[] method_parameter_table;
MethodParameters_attribute(ClassReader cr,
int name_index,
int length)
throws IOException {
super(name_index, length);
method_parameter_table_length = cr.readUnsignedByte();
method_parameter_table = new Entry[method_parameter_table_length];
for (int i = 0; i < method_parameter_table_length; i++)
method_parameter_table[i] = new Entry(cr);
}
public MethodParameters_attribute(ConstantPool constant_pool,
Entry[] method_parameter_table)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.MethodParameters),
method_parameter_table);
}
public MethodParameters_attribute(int name_index,
Entry[] method_parameter_table) {
super(name_index, 1 + method_parameter_table.length * Entry.length());
this.method_parameter_table_length = method_parameter_table.length;
this.method_parameter_table = method_parameter_table;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodParameters(this, data);
}
public static class Entry {
Entry(ClassReader cr) throws IOException {
name_index = cr.readUnsignedShort();
flags = cr.readUnsignedShort();
}
public static int length() {
return 6;
}
public final int name_index;
public final int flags;
}
}

View File

@@ -0,0 +1,472 @@
/*
* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import static com.sun.tools.classfile.Instruction.Kind.*;
import static com.sun.tools.classfile.Opcode.Set.*;
/**
* See JVMS, chapter 6.
*
* <p>In addition to providing all the standard opcodes defined in JVMS,
* this class also provides legacy support for the PicoJava extensions.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public enum Opcode {
NOP(0x0),
ACONST_NULL(0x1),
ICONST_M1(0x2),
ICONST_0(0x3),
ICONST_1(0x4),
ICONST_2(0x5),
ICONST_3(0x6),
ICONST_4(0x7),
ICONST_5(0x8),
LCONST_0(0x9),
LCONST_1(0xa),
FCONST_0(0xb),
FCONST_1(0xc),
FCONST_2(0xd),
DCONST_0(0xe),
DCONST_1(0xf),
BIPUSH(0x10, BYTE),
SIPUSH(0x11, SHORT),
LDC(0x12, CPREF),
LDC_W(0x13, CPREF_W),
LDC2_W(0x14, CPREF_W),
ILOAD(0x15, LOCAL),
LLOAD(0x16, LOCAL),
FLOAD(0x17, LOCAL),
DLOAD(0x18, LOCAL),
ALOAD(0x19, LOCAL),
ILOAD_0(0x1a),
ILOAD_1(0x1b),
ILOAD_2(0x1c),
ILOAD_3(0x1d),
LLOAD_0(0x1e),
LLOAD_1(0x1f),
LLOAD_2(0x20),
LLOAD_3(0x21),
FLOAD_0(0x22),
FLOAD_1(0x23),
FLOAD_2(0x24),
FLOAD_3(0x25),
DLOAD_0(0x26),
DLOAD_1(0x27),
DLOAD_2(0x28),
DLOAD_3(0x29),
ALOAD_0(0x2a),
ALOAD_1(0x2b),
ALOAD_2(0x2c),
ALOAD_3(0x2d),
IALOAD(0x2e),
LALOAD(0x2f),
FALOAD(0x30),
DALOAD(0x31),
AALOAD(0x32),
BALOAD(0x33),
CALOAD(0x34),
SALOAD(0x35),
ISTORE(0x36, LOCAL),
LSTORE(0x37, LOCAL),
FSTORE(0x38, LOCAL),
DSTORE(0x39, LOCAL),
ASTORE(0x3a, LOCAL),
ISTORE_0(0x3b),
ISTORE_1(0x3c),
ISTORE_2(0x3d),
ISTORE_3(0x3e),
LSTORE_0(0x3f),
LSTORE_1(0x40),
LSTORE_2(0x41),
LSTORE_3(0x42),
FSTORE_0(0x43),
FSTORE_1(0x44),
FSTORE_2(0x45),
FSTORE_3(0x46),
DSTORE_0(0x47),
DSTORE_1(0x48),
DSTORE_2(0x49),
DSTORE_3(0x4a),
ASTORE_0(0x4b),
ASTORE_1(0x4c),
ASTORE_2(0x4d),
ASTORE_3(0x4e),
IASTORE(0x4f),
LASTORE(0x50),
FASTORE(0x51),
DASTORE(0x52),
AASTORE(0x53),
BASTORE(0x54),
CASTORE(0x55),
SASTORE(0x56),
POP(0x57),
POP2(0x58),
DUP(0x59),
DUP_X1(0x5a),
DUP_X2(0x5b),
DUP2(0x5c),
DUP2_X1(0x5d),
DUP2_X2(0x5e),
SWAP(0x5f),
IADD(0x60),
LADD(0x61),
FADD(0x62),
DADD(0x63),
ISUB(0x64),
LSUB(0x65),
FSUB(0x66),
DSUB(0x67),
IMUL(0x68),
LMUL(0x69),
FMUL(0x6a),
DMUL(0x6b),
IDIV(0x6c),
LDIV(0x6d),
FDIV(0x6e),
DDIV(0x6f),
IREM(0x70),
LREM(0x71),
FREM(0x72),
DREM(0x73),
INEG(0x74),
LNEG(0x75),
FNEG(0x76),
DNEG(0x77),
ISHL(0x78),
LSHL(0x79),
ISHR(0x7a),
LSHR(0x7b),
IUSHR(0x7c),
LUSHR(0x7d),
IAND(0x7e),
LAND(0x7f),
IOR(0x80),
LOR(0x81),
IXOR(0x82),
LXOR(0x83),
IINC(0x84, LOCAL_BYTE),
I2L(0x85),
I2F(0x86),
I2D(0x87),
L2I(0x88),
L2F(0x89),
L2D(0x8a),
F2I(0x8b),
F2L(0x8c),
F2D(0x8d),
D2I(0x8e),
D2L(0x8f),
D2F(0x90),
I2B(0x91),
I2C(0x92),
I2S(0x93),
LCMP(0x94),
FCMPL(0x95),
FCMPG(0x96),
DCMPL(0x97),
DCMPG(0x98),
IFEQ(0x99, BRANCH),
IFNE(0x9a, BRANCH),
IFLT(0x9b, BRANCH),
IFGE(0x9c, BRANCH),
IFGT(0x9d, BRANCH),
IFLE(0x9e, BRANCH),
IF_ICMPEQ(0x9f, BRANCH),
IF_ICMPNE(0xa0, BRANCH),
IF_ICMPLT(0xa1, BRANCH),
IF_ICMPGE(0xa2, BRANCH),
IF_ICMPGT(0xa3, BRANCH),
IF_ICMPLE(0xa4, BRANCH),
IF_ACMPEQ(0xa5, BRANCH),
IF_ACMPNE(0xa6, BRANCH),
GOTO(0xa7, BRANCH),
JSR(0xa8, BRANCH),
RET(0xa9, LOCAL),
TABLESWITCH(0xaa, DYNAMIC),
LOOKUPSWITCH(0xab, DYNAMIC),
IRETURN(0xac),
LRETURN(0xad),
FRETURN(0xae),
DRETURN(0xaf),
ARETURN(0xb0),
RETURN(0xb1),
GETSTATIC(0xb2, CPREF_W),
PUTSTATIC(0xb3, CPREF_W),
GETFIELD(0xb4, CPREF_W),
PUTFIELD(0xb5, CPREF_W),
INVOKEVIRTUAL(0xb6, CPREF_W),
INVOKESPECIAL(0xb7, CPREF_W),
INVOKESTATIC(0xb8, CPREF_W),
INVOKEINTERFACE(0xb9, CPREF_W_UBYTE_ZERO),
INVOKEDYNAMIC(0xba, CPREF_W_UBYTE_ZERO),
NEW(0xbb, CPREF_W),
NEWARRAY(0xbc, ATYPE),
ANEWARRAY(0xbd, CPREF_W),
ARRAYLENGTH(0xbe),
ATHROW(0xbf),
CHECKCAST(0xc0, CPREF_W),
INSTANCEOF(0xc1, CPREF_W),
MONITORENTER(0xc2),
MONITOREXIT(0xc3),
// wide 0xc4
MULTIANEWARRAY(0xc5, CPREF_W_UBYTE),
IFNULL(0xc6, BRANCH),
IFNONNULL(0xc7, BRANCH),
GOTO_W(0xc8, BRANCH_W),
JSR_W(0xc9, BRANCH_W),
// impdep 0xfe: PicoJava nonpriv
// impdep 0xff: Picojava priv
// wide opcodes
ILOAD_W(0xc415, WIDE_LOCAL),
LLOAD_W(0xc416, WIDE_LOCAL),
FLOAD_W(0xc417, WIDE_LOCAL),
DLOAD_W(0xc418, WIDE_LOCAL),
ALOAD_W(0xc419, WIDE_LOCAL),
ISTORE_W(0xc436, WIDE_LOCAL),
LSTORE_W(0xc437, WIDE_LOCAL),
FSTORE_W(0xc438, WIDE_LOCAL),
DSTORE_W(0xc439, WIDE_LOCAL),
ASTORE_W(0xc43a, WIDE_LOCAL),
IINC_W(0xc484, WIDE_LOCAL_SHORT),
RET_W(0xc4a9, WIDE_LOCAL),
// PicoJava nonpriv instructions
LOAD_UBYTE(PICOJAVA, 0xfe00),
LOAD_BYTE(PICOJAVA, 0xfe01),
LOAD_CHAR(PICOJAVA, 0xfe02),
LOAD_SHORT(PICOJAVA, 0xfe03),
LOAD_WORD(PICOJAVA, 0xfe04),
RET_FROM_SUB(PICOJAVA, 0xfe05),
LOAD_CHAR_OE(PICOJAVA, 0xfe0a),
LOAD_SHORT_OE(PICOJAVA, 0xfe0b),
LOAD_WORD_OE(PICOJAVA, 0xfe0c),
NCLOAD_UBYTE(PICOJAVA, 0xfe10),
NCLOAD_BYTE(PICOJAVA, 0xfe11),
NCLOAD_CHAR(PICOJAVA, 0xfe12),
NCLOAD_SHORT(PICOJAVA, 0xfe13),
NCLOAD_WORD(PICOJAVA, 0xfe14),
NCLOAD_CHAR_OE(PICOJAVA, 0xfe1a),
NCLOAD_SHORT_OE(PICOJAVA, 0xfe1b),
NCLOAD_WORD_OE(PICOJAVA, 0xfe1c),
CACHE_FLUSH(PICOJAVA, 0xfe1e),
STORE_BYTE(PICOJAVA, 0xfe20),
STORE_SHORT(PICOJAVA, 0xfe22),
STORE_WORD(PICOJAVA, 0xfe24),
STORE_SHORT_OE(PICOJAVA, 0xfe2a),
STORE_WORD_OE(PICOJAVA, 0xfe2c),
NCSTORE_BYTE(PICOJAVA, 0xfe30),
NCSTORE_SHORT(PICOJAVA, 0xfe32),
NCSTORE_WORD(PICOJAVA, 0xfe34),
NCSTORE_SHORT_OE(PICOJAVA, 0xfe3a),
NCSTORE_WORD_OE(PICOJAVA, 0xfe3c),
ZERO_LINE(PICOJAVA, 0xfe3e),
ENTER_SYNC_METHOD(PICOJAVA, 0xfe3f),
// PicoJava priv instructions
PRIV_LOAD_UBYTE(PICOJAVA, 0xff00),
PRIV_LOAD_BYTE(PICOJAVA, 0xff01),
PRIV_LOAD_CHAR(PICOJAVA, 0xff02),
PRIV_LOAD_SHORT(PICOJAVA, 0xff03),
PRIV_LOAD_WORD(PICOJAVA, 0xff04),
PRIV_RET_FROM_TRAP(PICOJAVA, 0xff05),
PRIV_READ_DCACHE_TAG(PICOJAVA, 0xff06),
PRIV_READ_DCACHE_DATA(PICOJAVA, 0xff07),
PRIV_LOAD_CHAR_OE(PICOJAVA, 0xff0a),
PRIV_LOAD_SHORT_OE(PICOJAVA, 0xff0b),
PRIV_LOAD_WORD_OE(PICOJAVA, 0xff0c),
PRIV_READ_ICACHE_TAG(PICOJAVA, 0xff0e),
PRIV_READ_ICACHE_DATA(PICOJAVA, 0xff0f),
PRIV_NCLOAD_UBYTE(PICOJAVA, 0xff10),
PRIV_NCLOAD_BYTE(PICOJAVA, 0xff11),
PRIV_NCLOAD_CHAR(PICOJAVA, 0xff12),
PRIV_NCLOAD_SHORT(PICOJAVA, 0xff13),
PRIV_NCLOAD_WORD(PICOJAVA, 0xff14),
PRIV_POWERDOWN(PICOJAVA, 0xff16),
PRIV_READ_SCACHE_DATA(PICOJAVA, 0xff17),
PRIV_NCLOAD_CHAR_OE(PICOJAVA, 0xff1a),
PRIV_NCLOAD_SHORT_OE(PICOJAVA, 0xff1b),
PRIV_NCLOAD_WORD_OE(PICOJAVA, 0xff1c),
PRIV_CACHE_FLUSH(PICOJAVA, 0xff1e),
PRIV_CACHE_INDEX_FLUSH(PICOJAVA, 0xff1f),
PRIV_STORE_BYTE(PICOJAVA, 0xff20),
PRIV_STORE_SHORT(PICOJAVA, 0xff22),
PRIV_STORE_WORD(PICOJAVA, 0xff24),
PRIV_WRITE_DCACHE_TAG(PICOJAVA, 0xff26),
PRIV_WRITE_DCACHE_DATA(PICOJAVA, 0xff27),
PRIV_STORE_SHORT_OE(PICOJAVA, 0xff2a),
PRIV_STORE_WORD_OE(PICOJAVA, 0xff2c),
PRIV_WRITE_ICACHE_TAG(PICOJAVA, 0xff2e),
PRIV_WRITE_ICACHE_DATA(PICOJAVA, 0xff2f),
PRIV_NCSTORE_BYTE(PICOJAVA, 0xff30),
PRIV_NCSTORE_SHORT(PICOJAVA, 0xff32),
PRIV_NCSTORE_WORD(PICOJAVA, 0xff34),
PRIV_RESET(PICOJAVA, 0xff36),
PRIV_WRITE_SCACHE_DATA(PICOJAVA, 0xff37),
PRIV_NCSTORE_SHORT_OE(PICOJAVA, 0xff3a),
PRIV_NCSTORE_WORD_OE(PICOJAVA, 0xff3c),
PRIV_ZERO_LINE(PICOJAVA, 0xff3e),
PRIV_READ_REG_0(PICOJAVA, 0xff40),
PRIV_READ_REG_1(PICOJAVA, 0xff41),
PRIV_READ_REG_2(PICOJAVA, 0xff42),
PRIV_READ_REG_3(PICOJAVA, 0xff43),
PRIV_READ_REG_4(PICOJAVA, 0xff44),
PRIV_READ_REG_5(PICOJAVA, 0xff45),
PRIV_READ_REG_6(PICOJAVA, 0xff46),
PRIV_READ_REG_7(PICOJAVA, 0xff47),
PRIV_READ_REG_8(PICOJAVA, 0xff48),
PRIV_READ_REG_9(PICOJAVA, 0xff49),
PRIV_READ_REG_10(PICOJAVA, 0xff4a),
PRIV_READ_REG_11(PICOJAVA, 0xff4b),
PRIV_READ_REG_12(PICOJAVA, 0xff4c),
PRIV_READ_REG_13(PICOJAVA, 0xff4d),
PRIV_READ_REG_14(PICOJAVA, 0xff4e),
PRIV_READ_REG_15(PICOJAVA, 0xff4f),
PRIV_READ_REG_16(PICOJAVA, 0xff50),
PRIV_READ_REG_17(PICOJAVA, 0xff51),
PRIV_READ_REG_18(PICOJAVA, 0xff52),
PRIV_READ_REG_19(PICOJAVA, 0xff53),
PRIV_READ_REG_20(PICOJAVA, 0xff54),
PRIV_READ_REG_21(PICOJAVA, 0xff55),
PRIV_READ_REG_22(PICOJAVA, 0xff56),
PRIV_READ_REG_23(PICOJAVA, 0xff57),
PRIV_READ_REG_24(PICOJAVA, 0xff58),
PRIV_READ_REG_25(PICOJAVA, 0xff59),
PRIV_READ_REG_26(PICOJAVA, 0xff5a),
PRIV_READ_REG_27(PICOJAVA, 0xff5b),
PRIV_READ_REG_28(PICOJAVA, 0xff5c),
PRIV_READ_REG_29(PICOJAVA, 0xff5d),
PRIV_READ_REG_30(PICOJAVA, 0xff5e),
PRIV_READ_REG_31(PICOJAVA, 0xff5f),
PRIV_WRITE_REG_0(PICOJAVA, 0xff60),
PRIV_WRITE_REG_1(PICOJAVA, 0xff61),
PRIV_WRITE_REG_2(PICOJAVA, 0xff62),
PRIV_WRITE_REG_3(PICOJAVA, 0xff63),
PRIV_WRITE_REG_4(PICOJAVA, 0xff64),
PRIV_WRITE_REG_5(PICOJAVA, 0xff65),
PRIV_WRITE_REG_6(PICOJAVA, 0xff66),
PRIV_WRITE_REG_7(PICOJAVA, 0xff67),
PRIV_WRITE_REG_8(PICOJAVA, 0xff68),
PRIV_WRITE_REG_9(PICOJAVA, 0xff69),
PRIV_WRITE_REG_10(PICOJAVA, 0xff6a),
PRIV_WRITE_REG_11(PICOJAVA, 0xff6b),
PRIV_WRITE_REG_12(PICOJAVA, 0xff6c),
PRIV_WRITE_REG_13(PICOJAVA, 0xff6d),
PRIV_WRITE_REG_14(PICOJAVA, 0xff6e),
PRIV_WRITE_REG_15(PICOJAVA, 0xff6f),
PRIV_WRITE_REG_16(PICOJAVA, 0xff70),
PRIV_WRITE_REG_17(PICOJAVA, 0xff71),
PRIV_WRITE_REG_18(PICOJAVA, 0xff72),
PRIV_WRITE_REG_19(PICOJAVA, 0xff73),
PRIV_WRITE_REG_20(PICOJAVA, 0xff74),
PRIV_WRITE_REG_21(PICOJAVA, 0xff75),
PRIV_WRITE_REG_22(PICOJAVA, 0xff76),
PRIV_WRITE_REG_23(PICOJAVA, 0xff77),
PRIV_WRITE_REG_24(PICOJAVA, 0xff78),
PRIV_WRITE_REG_25(PICOJAVA, 0xff79),
PRIV_WRITE_REG_26(PICOJAVA, 0xff7a),
PRIV_WRITE_REG_27(PICOJAVA, 0xff7b),
PRIV_WRITE_REG_28(PICOJAVA, 0xff7c),
PRIV_WRITE_REG_29(PICOJAVA, 0xff7d),
PRIV_WRITE_REG_30(PICOJAVA, 0xff7e),
PRIV_WRITE_REG_31(PICOJAVA, 0xff7f);
Opcode(int opcode) {
this(STANDARD, opcode, NO_OPERANDS);
}
Opcode(int opcode, Instruction.Kind kind) {
this(STANDARD, opcode, kind);
}
Opcode(Set set, int opcode) {
this(set, opcode, (set == STANDARD ? NO_OPERANDS : WIDE_NO_OPERANDS));
}
Opcode(Set set, int opcode, Instruction.Kind kind) {
this.set = set;
this.opcode = opcode;
this.kind = kind;
}
public final Set set;
public final int opcode;
public final Instruction.Kind kind;
/** Get the Opcode for a simple standard 1-byte opcode. */
public static Opcode get(int opcode) {
return stdOpcodes[opcode];
}
/** Get the Opcode for 1- or 2-byte opcode. */
public static Opcode get(int opcodePrefix, int opcode) {
Opcode[] block = getOpcodeBlock(opcodePrefix);
return (block == null ? null : block[opcode]);
}
private static Opcode[] getOpcodeBlock(int opcodePrefix) {
switch (opcodePrefix) {
case 0:
return stdOpcodes;
case WIDE:
return wideOpcodes;
case NONPRIV:
return nonPrivOpcodes;
case PRIV:
return privOpcodes;
default:
return null;
}
}
private static final Opcode[] stdOpcodes = new Opcode[256];
private static final Opcode[] wideOpcodes = new Opcode[256];
private static final Opcode[] nonPrivOpcodes = new Opcode[256];
private static final Opcode[] privOpcodes = new Opcode[256];
static {
for (Opcode o: values())
getOpcodeBlock(o.opcode >> 8)[o.opcode & 0xff] = o;
}
/** The byte prefix for the wide instructions. */
public static final int WIDE = 0xc4;
/** The byte prefix for the PicoJava nonpriv instructions. */
public static final int NONPRIV = 0xfe;
/** The byte prefix for the PicoJava priv instructions. */
public static final int PRIV = 0xff;
public enum Set {
/** Standard opcodes. */
STANDARD,
/** Legacy support for PicoJava opcodes. */
PICOJAVA };
}

View File

@@ -0,0 +1,240 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.sun.tools.classfile.Instruction.TypeKind;
import static com.sun.tools.classfile.ConstantPool.*;
/**
* A utility class to find where in a ClassFile references
* a {@link CONSTANT_Methodref_info method},
* a {@link CONSTANT_InterfaceMethodref_info interface method,
* or a {@link CONSTANT_Fieldref_info field}.
*/
public final class ReferenceFinder {
/**
* Filter for ReferenceFinder of what constant pool entries for reference lookup.
*/
public interface Filter {
/**
* Decides if the given CPRefInfo entry should be accepted or filtered.
*
* @param cpool ConstantPool of the ClassFile being parsed
* @param cpref constant pool entry representing a reference to
* a fields method, and interface method.
* @return {@code true} if accepted; otherwise {@code false}
*/
boolean accept(ConstantPool cpool, CPRefInfo cpref);
}
/**
* Visitor of individual method of a ClassFile that references the
* accepted field, method, or interface method references.
*/
public interface Visitor {
/**
* Invoked for a method containing one or more accepted CPRefInfo entries
*
* @param cf ClassFile
* @param method Method that does the references the accepted references
* @param refs Accepted constant pool method/field reference
*/
void visit(ClassFile cf, Method method, List<CPRefInfo> refConstantPool);
}
private final Filter filter;
private final Visitor visitor;
/**
* Constructor.
*/
public ReferenceFinder(Filter filter, Visitor visitor) {
this.filter = Objects.requireNonNull(filter);
this.visitor = Objects.requireNonNull(visitor);
}
/**
* Parses a given ClassFile and invoke the visitor if there is any reference
* to the constant pool entries referencing field, method, or
* interface method that are accepted. This method will return
* {@code true} if there is one or more accepted constant pool entries
* to lookup; otherwise, it will return {@code false}.
*
* @param cf ClassFile
* @return {@code true} if the given class file is processed to lookup
* references
* @throws ConstantPoolException if an error of the constant pool
*/
public boolean parse(ClassFile cf) throws ConstantPoolException {
List<Integer> cprefs = new ArrayList<Integer>();
int index = 1;
for (ConstantPool.CPInfo cpInfo : cf.constant_pool.entries()) {
if (cpInfo.accept(cpVisitor, cf.constant_pool)) {
cprefs.add(index);
}
index += cpInfo.size();
}
if (cprefs.isEmpty()) {
return false;
}
for (Method m : cf.methods) {
Set<Integer> ids = new HashSet<Integer>();
Code_attribute c_attr = (Code_attribute) m.attributes.get(Attribute.Code);
if (c_attr != null) {
for (Instruction instr : c_attr.getInstructions()) {
int idx = instr.accept(codeVisitor, cprefs);
if (idx > 0) {
ids.add(idx);
}
}
}
if (ids.size() > 0) {
List<CPRefInfo> refInfos = new ArrayList<CPRefInfo>(ids.size());
for (int id : ids) {
refInfos.add(CPRefInfo.class.cast(cf.constant_pool.get(id)));
}
visitor.visit(cf, m, refInfos);
}
}
return true;
}
private ConstantPool.Visitor<Boolean,ConstantPool> cpVisitor =
new ConstantPool.Visitor<Boolean,ConstantPool>()
{
public Boolean visitClass(CONSTANT_Class_info info, ConstantPool cpool) {
return false;
}
public Boolean visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, ConstantPool cpool) {
return filter.accept(cpool, info);
}
public Boolean visitMethodref(CONSTANT_Methodref_info info, ConstantPool cpool) {
return filter.accept(cpool, info);
}
public Boolean visitFieldref(CONSTANT_Fieldref_info info, ConstantPool cpool) {
return filter.accept(cpool, info);
}
public Boolean visitDouble(CONSTANT_Double_info info, ConstantPool cpool) {
return false;
}
public Boolean visitFloat(CONSTANT_Float_info info, ConstantPool cpool) {
return false;
}
public Boolean visitInteger(CONSTANT_Integer_info info, ConstantPool cpool) {
return false;
}
public Boolean visitInvokeDynamic(CONSTANT_InvokeDynamic_info info, ConstantPool cpool) {
return false;
}
public Boolean visitLong(CONSTANT_Long_info info, ConstantPool cpool) {
return false;
}
public Boolean visitNameAndType(CONSTANT_NameAndType_info info, ConstantPool cpool) {
return false;
}
public Boolean visitMethodHandle(CONSTANT_MethodHandle_info info, ConstantPool cpool) {
return false;
}
public Boolean visitMethodType(CONSTANT_MethodType_info info, ConstantPool cpool) {
return false;
}
public Boolean visitString(CONSTANT_String_info info, ConstantPool cpool) {
return false;
}
public Boolean visitUtf8(CONSTANT_Utf8_info info, ConstantPool cpool) {
return false;
}
};
private Instruction.KindVisitor<Integer, List<Integer>> codeVisitor =
new Instruction.KindVisitor<Integer, List<Integer>>()
{
public Integer visitNoOperands(Instruction instr, List<Integer> p) {
return 0;
}
public Integer visitArrayType(Instruction instr, TypeKind kind, List<Integer> p) {
return 0;
}
public Integer visitBranch(Instruction instr, int offset, List<Integer> p) {
return 0;
}
public Integer visitConstantPoolRef(Instruction instr, int index, List<Integer> p) {
return p.contains(index) ? index : 0;
}
public Integer visitConstantPoolRefAndValue(Instruction instr, int index, int value, List<Integer> p) {
return p.contains(index) ? index : 0;
}
public Integer visitLocal(Instruction instr, int index, List<Integer> p) {
return 0;
}
public Integer visitLocalAndValue(Instruction instr, int index, int value, List<Integer> p) {
return 0;
}
public Integer visitLookupSwitch(Instruction instr, int default_, int npairs, int[] matches, int[] offsets, List<Integer> p) {
return 0;
}
public Integer visitTableSwitch(Instruction instr, int default_, int low, int high, int[] offsets, List<Integer> p) {
return 0;
}
public Integer visitValue(Instruction instr, int value, List<Integer> p) {
return 0;
}
public Integer visitUnknown(Instruction instr, List<Integer> p) {
return 0;
}
};
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.16 and 4.8.17.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class RuntimeAnnotations_attribute extends Attribute {
protected RuntimeAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
int num_annotations = cr.readUnsignedShort();
annotations = new Annotation[num_annotations];
for (int i = 0; i < annotations.length; i++)
annotations[i] = new Annotation(cr);
}
protected RuntimeAnnotations_attribute(int name_index, Annotation[] annotations) {
super(name_index, length(annotations));
this.annotations = annotations;
}
private static int length(Annotation[] annos) {
int n = 2;
for (Annotation anno: annos)
n += anno.length();
return n;
}
public final Annotation[] annotations;
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.17.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeInvisibleAnnotations_attribute extends RuntimeAnnotations_attribute {
RuntimeInvisibleAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, AttributeException {
super(cr, name_index, length);
}
public RuntimeInvisibleAnnotations_attribute(ConstantPool cp, Annotation[] annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeInvisibleAnnotations), annotations);
}
public RuntimeInvisibleAnnotations_attribute(int name_index, Annotation[] annotations) {
super(name_index, annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeInvisibleAnnotations(this, p);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.18.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeInvisibleParameterAnnotations_attribute extends RuntimeParameterAnnotations_attribute {
RuntimeInvisibleParameterAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeInvisibleParameterAnnotations_attribute(ConstantPool cp, Annotation[][] parameter_annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeInvisibleParameterAnnotations), parameter_annotations);
}
public RuntimeInvisibleParameterAnnotations_attribute(int name_index, Annotation[][] parameter_annotations) {
super(name_index, parameter_annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeInvisibleParameterAnnotations(this, p);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeInvisibleTypeAnnotations_attribute extends RuntimeTypeAnnotations_attribute {
RuntimeInvisibleTypeAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeInvisibleTypeAnnotations_attribute(ConstantPool cp, TypeAnnotation[] annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeInvisibleTypeAnnotations), annotations);
}
public RuntimeInvisibleTypeAnnotations_attribute(int name_index, TypeAnnotation[] annotations) {
super(name_index, annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeInvisibleTypeAnnotations(this, p);
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.18 and 4.8.19.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class RuntimeParameterAnnotations_attribute extends Attribute {
RuntimeParameterAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
int num_parameters = cr.readUnsignedByte();
parameter_annotations = new Annotation[num_parameters][];
for (int p = 0; p < parameter_annotations.length; p++) {
int num_annotations = cr.readUnsignedShort();
Annotation[] annotations = new Annotation[num_annotations];
for (int i = 0; i < num_annotations; i++)
annotations[i] = new Annotation(cr);
parameter_annotations[p] = annotations;
}
}
protected RuntimeParameterAnnotations_attribute(int name_index, Annotation[][] parameter_annotations) {
super(name_index, length(parameter_annotations));
this.parameter_annotations = parameter_annotations;
}
private static int length(Annotation[][] anno_arrays) {
int n = 1;
for (Annotation[] anno_array: anno_arrays) {
n += 2;
for (Annotation anno: anno_array)
n += anno.length();
}
return n;
}
public final Annotation[][] parameter_annotations;
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class RuntimeTypeAnnotations_attribute extends Attribute {
protected RuntimeTypeAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(name_index, length);
int num_annotations = cr.readUnsignedShort();
annotations = new TypeAnnotation[num_annotations];
for (int i = 0; i < annotations.length; i++)
annotations[i] = new TypeAnnotation(cr);
}
protected RuntimeTypeAnnotations_attribute(int name_index, TypeAnnotation[] annotations) {
super(name_index, length(annotations));
this.annotations = annotations;
}
private static int length(TypeAnnotation[] annos) {
int n = 2;
for (TypeAnnotation anno: annos)
n += anno.length();
return n;
}
public final TypeAnnotation[] annotations;
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.16.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeVisibleAnnotations_attribute extends RuntimeAnnotations_attribute {
RuntimeVisibleAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeVisibleAnnotations_attribute(ConstantPool cp, Annotation[] annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeVisibleAnnotations), annotations);
}
public RuntimeVisibleAnnotations_attribute(int name_index, Annotation[] annotations) {
super(name_index, annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeVisibleAnnotations(this, p);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.18.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeVisibleParameterAnnotations_attribute extends RuntimeParameterAnnotations_attribute {
RuntimeVisibleParameterAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeVisibleParameterAnnotations_attribute(ConstantPool cp, Annotation[][] parameter_annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeVisibleParameterAnnotations), parameter_annotations);
}
public RuntimeVisibleParameterAnnotations_attribute(int name_index, Annotation[][] parameter_annotations) {
super(name_index, parameter_annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeVisibleParameterAnnotations(this, p);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class RuntimeVisibleTypeAnnotations_attribute extends RuntimeTypeAnnotations_attribute {
RuntimeVisibleTypeAnnotations_attribute(ClassReader cr, int name_index, int length)
throws IOException, Annotation.InvalidAnnotation {
super(cr, name_index, length);
}
public RuntimeVisibleTypeAnnotations_attribute(ConstantPool cp, TypeAnnotation[] annotations)
throws ConstantPoolException {
this(cp.getUTF8Index(Attribute.RuntimeVisibleTypeAnnotations), annotations);
}
public RuntimeVisibleTypeAnnotations_attribute(int name_index, TypeAnnotation[] annotations) {
super(name_index, annotations);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitRuntimeVisibleTypeAnnotations(this, p);
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.ArrayList;
import java.util.List;
import com.sun.tools.classfile.Type.*;
/**
* See JVMS 4.4.4.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Signature extends Descriptor {
public Signature(int index) {
super(index);
}
public Type getType(ConstantPool constant_pool) throws ConstantPoolException {
if (type == null)
type = parse(getValue(constant_pool));
return type;
}
@Override
public int getParameterCount(ConstantPool constant_pool) throws ConstantPoolException {
MethodType m = (MethodType) getType(constant_pool);
return m.paramTypes.size();
}
@Override
public String getParameterTypes(ConstantPool constant_pool) throws ConstantPoolException {
MethodType m = (MethodType) getType(constant_pool);
StringBuilder sb = new StringBuilder();
sb.append("(");
String sep = "";
for (Type paramType: m.paramTypes) {
sb.append(sep);
sb.append(paramType);
sep = ", ";
}
sb.append(")");
return sb.toString();
}
@Override
public String getReturnType(ConstantPool constant_pool) throws ConstantPoolException {
MethodType m = (MethodType) getType(constant_pool);
return m.returnType.toString();
}
@Override
public String getFieldType(ConstantPool constant_pool) throws ConstantPoolException {
return getType(constant_pool).toString();
}
private Type parse(String sig) {
this.sig = sig;
sigp = 0;
List<TypeParamType> typeParamTypes = null;
if (sig.charAt(sigp) == '<')
typeParamTypes = parseTypeParamTypes();
if (sig.charAt(sigp) == '(') {
List<Type> paramTypes = parseTypeSignatures(')');
Type returnType = parseTypeSignature();
List<Type> throwsTypes = null;
while (sigp < sig.length() && sig.charAt(sigp) == '^') {
sigp++;
if (throwsTypes == null)
throwsTypes = new ArrayList<Type>();
throwsTypes.add(parseTypeSignature());
}
return new MethodType(typeParamTypes, paramTypes, returnType, throwsTypes);
} else {
Type t = parseTypeSignature();
if (typeParamTypes == null && sigp == sig.length())
return t;
Type superclass = t;
List<Type> superinterfaces = null;
while (sigp < sig.length()) {
if (superinterfaces == null)
superinterfaces = new ArrayList<Type>();
superinterfaces.add(parseTypeSignature());
}
return new ClassSigType(typeParamTypes, superclass, superinterfaces);
}
}
private Type parseTypeSignature() {
switch (sig.charAt(sigp)) {
case 'B':
sigp++;
return new SimpleType("byte");
case 'C':
sigp++;
return new SimpleType("char");
case 'D':
sigp++;
return new SimpleType("double");
case 'F':
sigp++;
return new SimpleType("float");
case 'I':
sigp++;
return new SimpleType("int");
case 'J':
sigp++;
return new SimpleType("long");
case 'L':
return parseClassTypeSignature();
case 'S':
sigp++;
return new SimpleType("short");
case 'T':
return parseTypeVariableSignature();
case 'V':
sigp++;
return new SimpleType("void");
case 'Z':
sigp++;
return new SimpleType("boolean");
case '[':
sigp++;
return new ArrayType(parseTypeSignature());
case '*':
sigp++;
return new WildcardType();
case '+':
sigp++;
return new WildcardType(WildcardType.Kind.EXTENDS, parseTypeSignature());
case '-':
sigp++;
return new WildcardType(WildcardType.Kind.SUPER, parseTypeSignature());
default:
throw new IllegalStateException(debugInfo());
}
}
private List<Type> parseTypeSignatures(char term) {
sigp++;
List<Type> types = new ArrayList<Type>();
while (sig.charAt(sigp) != term)
types.add(parseTypeSignature());
sigp++;
return types;
}
private Type parseClassTypeSignature() {
assert sig.charAt(sigp) == 'L';
sigp++;
return parseClassTypeSignatureRest();
}
private Type parseClassTypeSignatureRest() {
StringBuilder sb = new StringBuilder();
List<Type> argTypes = null;
ClassType t = null;
char sigch ;
do {
switch (sigch = sig.charAt(sigp)) {
case '<':
argTypes = parseTypeSignatures('>');
break;
case '.':
case ';':
sigp++;
t = new ClassType(t, sb.toString(), argTypes);
sb.setLength(0);
argTypes = null;
break;
default:
sigp++;
sb.append(sigch);
break;
}
} while (sigch != ';');
return t;
}
private List<TypeParamType> parseTypeParamTypes() {
assert sig.charAt(sigp) == '<';
sigp++;
List<TypeParamType> types = new ArrayList<TypeParamType>();
while (sig.charAt(sigp) != '>')
types.add(parseTypeParamType());
sigp++;
return types;
}
private TypeParamType parseTypeParamType() {
int sep = sig.indexOf(":", sigp);
String name = sig.substring(sigp, sep);
Type classBound = null;
List<Type> interfaceBounds = null;
sigp = sep + 1;
if (sig.charAt(sigp) != ':')
classBound = parseTypeSignature();
while (sig.charAt(sigp) == ':') {
sigp++;
if (interfaceBounds == null)
interfaceBounds = new ArrayList<Type>();
interfaceBounds.add(parseTypeSignature());
}
return new TypeParamType(name, classBound, interfaceBounds);
}
private Type parseTypeVariableSignature() {
sigp++;
int sep = sig.indexOf(';', sigp);
Type t = new SimpleType(sig.substring(sigp, sep));
sigp = sep + 1;
return t;
}
private String debugInfo() {
return sig.substring(0, sigp) + "!" + sig.charAt(sigp) + "!" + sig.substring(sigp+1);
}
private String sig;
private int sigp;
private Type type;
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.9.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Signature_attribute extends Attribute {
Signature_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
signature_index = cr.readUnsignedShort();
}
public Signature_attribute(ConstantPool constant_pool, int signature_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Signature), signature_index);
}
public Signature_attribute(int name_index, int signature_index) {
super(name_index, 2);
this.signature_index = signature_index;
}
public String getSignature(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(signature_index);
}
public Signature getParsedSignature() {
return new Signature(signature_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSignature(this, data);
}
public final int signature_index;
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* See JVMS, section 4.8.15.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class SourceDebugExtension_attribute extends Attribute {
private static final Charset UTF8 = Charset.forName("UTF-8");
SourceDebugExtension_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
debug_extension = new byte[attribute_length];
cr.readFully(debug_extension);
}
public SourceDebugExtension_attribute(ConstantPool constant_pool, byte[] debug_extension)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.SourceDebugExtension), debug_extension);
}
public SourceDebugExtension_attribute(int name_index, byte[] debug_extension) {
super(name_index, debug_extension.length);
this.debug_extension = debug_extension;
}
public String getValue() {
return new String(debug_extension, UTF8);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSourceDebugExtension(this, data);
}
public final byte[] debug_extension;
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.10.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class SourceFile_attribute extends Attribute {
SourceFile_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
sourcefile_index = cr.readUnsignedShort();
}
public SourceFile_attribute(ConstantPool constant_pool, int sourcefile_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.SourceFile), sourcefile_index);
}
public SourceFile_attribute(int name_index, int sourcefile_index) {
super(name_index, 2);
this.sourcefile_index = sourcefile_index;
}
public String getSourceFile(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(sourcefile_index);
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitSourceFile(this, p);
}
public final int sourcefile_index;
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class SourceID_attribute extends Attribute {
SourceID_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
sourceID_index = cr.readUnsignedShort();
}
public SourceID_attribute(ConstantPool constant_pool, int sourceID_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.SourceID), sourceID_index);
}
public SourceID_attribute(int name_index, int sourceID_index) {
super(name_index, 2);
this.sourceID_index = sourceID_index;
}
String getSourceID(ConstantPool constant_pool) throws ConstantPoolException {
return constant_pool.getUTF8Value(sourceID_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSourceID(this, data);
}
public final int sourceID_index;
}

View File

@@ -0,0 +1,380 @@
/*
* Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.4.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class StackMapTable_attribute extends Attribute {
static class InvalidStackMap extends AttributeException {
private static final long serialVersionUID = -5659038410855089780L;
InvalidStackMap(String msg) {
super(msg);
}
}
StackMapTable_attribute(ClassReader cr, int name_index, int length)
throws IOException, InvalidStackMap {
super(name_index, length);
number_of_entries = cr.readUnsignedShort();
entries = new stack_map_frame[number_of_entries];
for (int i = 0; i < number_of_entries; i++)
entries[i] = stack_map_frame.read(cr);
}
public StackMapTable_attribute(ConstantPool constant_pool, stack_map_frame[] entries)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.StackMapTable), entries);
}
public StackMapTable_attribute(int name_index, stack_map_frame[] entries) {
super(name_index, length(entries));
this.number_of_entries = entries.length;
this.entries = entries;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitStackMapTable(this, data);
}
static int length(stack_map_frame[] entries) {
int n = 2;
for (stack_map_frame entry: entries)
n += entry.length();
return n;
}
public final int number_of_entries;
public final stack_map_frame entries[];
public static abstract class stack_map_frame {
static stack_map_frame read(ClassReader cr)
throws IOException, InvalidStackMap {
int frame_type = cr.readUnsignedByte();
if (frame_type <= 63)
return new same_frame(frame_type);
else if (frame_type <= 127)
return new same_locals_1_stack_item_frame(frame_type, cr);
else if (frame_type <= 246)
throw new Error("unknown frame_type " + frame_type);
else if (frame_type == 247)
return new same_locals_1_stack_item_frame_extended(frame_type, cr);
else if (frame_type <= 250)
return new chop_frame(frame_type, cr);
else if (frame_type == 251)
return new same_frame_extended(frame_type, cr);
else if (frame_type <= 254)
return new append_frame(frame_type, cr);
else
return new full_frame(frame_type, cr);
}
protected stack_map_frame(int frame_type) {
this.frame_type = frame_type;
}
public int length() {
return 1;
}
public abstract int getOffsetDelta();
public abstract <R,D> R accept(Visitor<R,D> visitor, D data);
public final int frame_type;
public static interface Visitor<R,P> {
R visit_same_frame(same_frame frame, P p);
R visit_same_locals_1_stack_item_frame(same_locals_1_stack_item_frame frame, P p);
R visit_same_locals_1_stack_item_frame_extended(same_locals_1_stack_item_frame_extended frame, P p);
R visit_chop_frame(chop_frame frame, P p);
R visit_same_frame_extended(same_frame_extended frame, P p);
R visit_append_frame(append_frame frame, P p);
R visit_full_frame(full_frame frame, P p);
}
}
public static class same_frame extends stack_map_frame {
same_frame(int frame_type) {
super(frame_type);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_same_frame(this, data);
}
public int getOffsetDelta() {
return frame_type;
}
}
public static class same_locals_1_stack_item_frame extends stack_map_frame {
same_locals_1_stack_item_frame(int frame_type, ClassReader cr)
throws IOException, InvalidStackMap {
super(frame_type);
stack = new verification_type_info[1];
stack[0] = verification_type_info.read(cr);
}
@Override
public int length() {
return super.length() + stack[0].length();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_same_locals_1_stack_item_frame(this, data);
}
public int getOffsetDelta() {
return frame_type - 64;
}
public final verification_type_info[] stack;
}
public static class same_locals_1_stack_item_frame_extended extends stack_map_frame {
same_locals_1_stack_item_frame_extended(int frame_type, ClassReader cr)
throws IOException, InvalidStackMap {
super(frame_type);
offset_delta = cr.readUnsignedShort();
stack = new verification_type_info[1];
stack[0] = verification_type_info.read(cr);
}
@Override
public int length() {
return super.length() + 2 + stack[0].length();
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_same_locals_1_stack_item_frame_extended(this, data);
}
public int getOffsetDelta() {
return offset_delta;
}
public final int offset_delta;
public final verification_type_info[] stack;
}
public static class chop_frame extends stack_map_frame {
chop_frame(int frame_type, ClassReader cr) throws IOException {
super(frame_type);
offset_delta = cr.readUnsignedShort();
}
@Override
public int length() {
return super.length() + 2;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_chop_frame(this, data);
}
public int getOffsetDelta() {
return offset_delta;
}
public final int offset_delta;
}
public static class same_frame_extended extends stack_map_frame {
same_frame_extended(int frame_type, ClassReader cr) throws IOException {
super(frame_type);
offset_delta = cr.readUnsignedShort();
}
@Override
public int length() {
return super.length() + 2;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_same_frame_extended(this, data);
}
public int getOffsetDelta() {
return offset_delta;
}
public final int offset_delta;
}
public static class append_frame extends stack_map_frame {
append_frame(int frame_type, ClassReader cr)
throws IOException, InvalidStackMap {
super(frame_type);
offset_delta = cr.readUnsignedShort();
locals = new verification_type_info[frame_type - 251];
for (int i = 0; i < locals.length; i++)
locals[i] = verification_type_info.read(cr);
}
@Override
public int length() {
int n = super.length() + 2;
for (verification_type_info local: locals)
n += local.length();
return n;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_append_frame(this, data);
}
public int getOffsetDelta() {
return offset_delta;
}
public final int offset_delta;
public final verification_type_info[] locals;
}
public static class full_frame extends stack_map_frame {
full_frame(int frame_type, ClassReader cr)
throws IOException, InvalidStackMap {
super(frame_type);
offset_delta = cr.readUnsignedShort();
number_of_locals = cr.readUnsignedShort();
locals = new verification_type_info[number_of_locals];
for (int i = 0; i < locals.length; i++)
locals[i] = verification_type_info.read(cr);
number_of_stack_items = cr.readUnsignedShort();
stack = new verification_type_info[number_of_stack_items];
for (int i = 0; i < stack.length; i++)
stack[i] = verification_type_info.read(cr);
}
@Override
public int length() {
int n = super.length() + 2;
for (verification_type_info local: locals)
n += local.length();
n += 2;
for (verification_type_info item: stack)
n += item.length();
return n;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visit_full_frame(this, data);
}
public int getOffsetDelta() {
return offset_delta;
}
public final int offset_delta;
public final int number_of_locals;
public final verification_type_info[] locals;
public final int number_of_stack_items;
public final verification_type_info[] stack;
}
public static class verification_type_info {
public static final int ITEM_Top = 0;
public static final int ITEM_Integer = 1;
public static final int ITEM_Float = 2;
public static final int ITEM_Long = 4;
public static final int ITEM_Double = 3;
public static final int ITEM_Null = 5;
public static final int ITEM_UninitializedThis = 6;
public static final int ITEM_Object = 7;
public static final int ITEM_Uninitialized = 8;
static verification_type_info read(ClassReader cr)
throws IOException, InvalidStackMap {
int tag = cr.readUnsignedByte();
switch (tag) {
case ITEM_Top:
case ITEM_Integer:
case ITEM_Float:
case ITEM_Long:
case ITEM_Double:
case ITEM_Null:
case ITEM_UninitializedThis:
return new verification_type_info(tag);
case ITEM_Object:
return new Object_variable_info(cr);
case ITEM_Uninitialized:
return new Uninitialized_variable_info(cr);
default:
throw new InvalidStackMap("unrecognized verification_type_info tag");
}
}
protected verification_type_info(int tag) {
this.tag = tag;
}
public int length() {
return 1;
}
public final int tag;
}
public static class Object_variable_info extends verification_type_info {
Object_variable_info(ClassReader cr) throws IOException {
super(ITEM_Object);
cpool_index = cr.readUnsignedShort();
}
@Override
public int length() {
return super.length() + 2;
}
public final int cpool_index;
}
public static class Uninitialized_variable_info extends verification_type_info {
Uninitialized_variable_info(ClassReader cr) throws IOException {
super(ITEM_Uninitialized);
offset = cr.readUnsignedShort();
}
@Override
public int length() {
return super.length() + 2;
}
public final int offset;
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class StackMap_attribute extends Attribute {
StackMap_attribute(ClassReader cr, int name_index, int length)
throws IOException, StackMapTable_attribute.InvalidStackMap {
super(name_index, length);
number_of_entries = cr.readUnsignedShort();
entries = new stack_map_frame[number_of_entries];
for (int i = 0; i < number_of_entries; i++)
entries[i] = new stack_map_frame(cr);
}
public StackMap_attribute(ConstantPool constant_pool, stack_map_frame[] entries)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.StackMap), entries);
}
public StackMap_attribute(int name_index, stack_map_frame[] entries) {
super(name_index, StackMapTable_attribute.length(entries));
this.number_of_entries = entries.length;
this.entries = entries;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitStackMap(this, data);
}
public final int number_of_entries;
public final stack_map_frame entries[];
public static class stack_map_frame extends StackMapTable_attribute.full_frame {
stack_map_frame(ClassReader cr)
throws IOException, StackMapTable_attribute.InvalidStackMap {
super(255, cr);
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* See JVMS, section 4.8.8.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Synthetic_attribute extends Attribute {
Synthetic_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
}
public Synthetic_attribute(ConstantPool constant_pool)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.Synthetic));
}
public Synthetic_attribute(int name_index) {
super(name_index, 0);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSynthetic(this, data);
}
}

View File

@@ -0,0 +1,377 @@
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*
* Family of classes used to represent the parsed form of a {@link Descriptor}
* or {@link Signature}.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class Type {
protected Type() { }
public boolean isObject() {
return false;
}
public abstract <R,D> R accept(Visitor<R,D> visitor, D data);
protected static void append(StringBuilder sb, String prefix, List<? extends Type> types, String suffix) {
sb.append(prefix);
String sep = "";
for (Type t: types) {
sb.append(sep);
sb.append(t);
sep = ", ";
}
sb.append(suffix);
}
protected static void appendIfNotEmpty(StringBuilder sb, String prefix, List<? extends Type> types, String suffix) {
if (types != null && types.size() > 0)
append(sb, prefix, types, suffix);
}
public interface Visitor<R,P> {
R visitSimpleType(SimpleType type, P p);
R visitArrayType(ArrayType type, P p);
R visitMethodType(MethodType type, P p);
R visitClassSigType(ClassSigType type, P p);
R visitClassType(ClassType type, P p);
R visitTypeParamType(TypeParamType type, P p);
R visitWildcardType(WildcardType type, P p);
}
/**
* Represents a type signature with a simple name. The name may be that of a
* primitive type, such "{@code int}, {@code float}, etc
* or that of a type argument, such as {@code T}, {@code K}, {@code V}, etc.
*
* See:
* JVMS 4.3.2
* BaseType:
* {@code B}, {@code C}, {@code D}, {@code F}, {@code I},
* {@code J}, {@code S}, {@code Z};
* VoidDescriptor:
* {@code V};
* JVMS 4.3.4
* TypeVariableSignature:
* {@code T} Identifier {@code ;}
*/
public static class SimpleType extends Type {
public SimpleType(String name) {
this.name = name;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitSimpleType(this, data);
}
public boolean isPrimitiveType() {
return primitiveTypes.contains(name);
}
// where
private static final Set<String> primitiveTypes = new HashSet<String>(Arrays.asList(
"boolean", "byte", "char", "double", "float", "int", "long", "short", "void"));
@Override
public String toString() {
return name;
}
public final String name;
}
/**
* Represents an array type signature.
*
* See:
* JVMS 4.3.4
* ArrayTypeSignature:
* {@code [} TypeSignature {@code ]}
*/
public static class ArrayType extends Type {
public ArrayType(Type elemType) {
this.elemType = elemType;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitArrayType(this, data);
}
@Override
public String toString() {
return elemType + "[]";
}
public final Type elemType;
}
/**
* Represents a method type signature.
*
* See;
* JVMS 4.3.4
* MethodTypeSignature:
* FormalTypeParameters_opt {@code (} TypeSignature* {@code)} ReturnType
* ThrowsSignature*
*/
public static class MethodType extends Type {
public MethodType(List<? extends Type> paramTypes, Type resultType) {
this(null, paramTypes, resultType, null);
}
public MethodType(List<? extends TypeParamType> typeParamTypes,
List<? extends Type> paramTypes,
Type returnType,
List<? extends Type> throwsTypes) {
this.typeParamTypes = typeParamTypes;
this.paramTypes = paramTypes;
this.returnType = returnType;
this.throwsTypes = throwsTypes;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodType(this, data);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
appendIfNotEmpty(sb, "<", typeParamTypes, "> ");
sb.append(returnType);
append(sb, " (", paramTypes, ")");
appendIfNotEmpty(sb, " throws ", throwsTypes, "");
return sb.toString();
}
public final List<? extends TypeParamType> typeParamTypes;
public final List<? extends Type> paramTypes;
public final Type returnType;
public final List<? extends Type> throwsTypes;
}
/**
* Represents a class signature. These describe the signature of
* a class that has type arguments.
*
* See:
* JVMS 4.3.4
* ClassSignature:
* FormalTypeParameters_opt SuperclassSignature SuperinterfaceSignature*
*/
public static class ClassSigType extends Type {
public ClassSigType(List<TypeParamType> typeParamTypes, Type superclassType,
List<Type> superinterfaceTypes) {
this.typeParamTypes = typeParamTypes;
this.superclassType = superclassType;
this.superinterfaceTypes = superinterfaceTypes;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitClassSigType(this, data);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
appendIfNotEmpty(sb, "<", typeParamTypes, ">");
if (superclassType != null) {
sb.append(" extends ");
sb.append(superclassType);
}
appendIfNotEmpty(sb, " implements ", superinterfaceTypes, "");
return sb.toString();
}
public final List<TypeParamType> typeParamTypes;
public final Type superclassType;
public final List<Type> superinterfaceTypes;
}
/**
* Represents a class type signature. This is used to represent a
* reference to a class, such as in a field, parameter, return type, etc.
*
* See:
* JVMS 4.3.4
* ClassTypeSignature:
* {@code L} PackageSpecifier_opt SimpleClassTypeSignature
* ClassTypeSignatureSuffix* {@code ;}
* PackageSpecifier:
* Identifier {@code /} PackageSpecifier*
* SimpleClassTypeSignature:
* Identifier TypeArguments_opt }
* ClassTypeSignatureSuffix:
* {@code .} SimpleClassTypeSignature
*/
public static class ClassType extends Type {
public ClassType(ClassType outerType, String name, List<Type> typeArgs) {
this.outerType = outerType;
this.name = name;
this.typeArgs = typeArgs;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitClassType(this, data);
}
public String getBinaryName() {
if (outerType == null)
return name;
else
return (outerType.getBinaryName() + "$" + name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (outerType != null) {
sb.append(outerType);
sb.append(".");
}
sb.append(name);
appendIfNotEmpty(sb, "<", typeArgs, ">");
return sb.toString();
}
@Override
public boolean isObject() {
return (outerType == null)
&& name.equals("java/lang/Object")
&& (typeArgs == null || typeArgs.isEmpty());
}
public final ClassType outerType;
public final String name;
public final List<Type> typeArgs;
}
/**
* Represents a FormalTypeParameter. These are used to declare the type
* parameters for generic classes and methods.
*
* See:
* JVMS 4.3.4
* FormalTypeParameters:
* {@code <} FormalTypeParameter+ {@code >}
* FormalTypeParameter:
* Identifier ClassBound InterfaceBound*
* ClassBound:
* {@code :} FieldTypeSignature_opt
* InterfaceBound:
* {@code :} FieldTypeSignature
*/
public static class TypeParamType extends Type {
public TypeParamType(String name, Type classBound, List<Type> interfaceBounds) {
this.name = name;
this.classBound = classBound;
this.interfaceBounds = interfaceBounds;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitTypeParamType(this, data);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
String sep = " extends ";
if (classBound != null) {
sb.append(sep);
sb.append(classBound);
sep = " & ";
}
if (interfaceBounds != null) {
for (Type bound: interfaceBounds) {
sb.append(sep);
sb.append(bound);
sep = " & ";
}
}
return sb.toString();
}
public final String name;
public final Type classBound;
public final List<Type> interfaceBounds;
}
/**
* Represents a wildcard type argument. A type argument that is not a
* wildcard type argument will be represented by a ClassType, ArrayType, etc.
*
* See:
* JVMS 4.3.4
* TypeArgument:
* WildcardIndicator_opt FieldTypeSignature
* {@code *}
* WildcardIndicator:
* {@code +}
* {@code -}
*/
public static class WildcardType extends Type {
public enum Kind { UNBOUNDED, EXTENDS, SUPER };
public WildcardType() {
this(Kind.UNBOUNDED, null);
}
public WildcardType(Kind kind, Type boundType) {
this.kind = kind;
this.boundType = boundType;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitWildcardType(this, data);
}
@Override
public String toString() {
switch (kind) {
case UNBOUNDED:
return "?";
case EXTENDS:
return "? extends " + boundType;
case SUPER:
return "? super " + boundType;
default:
throw new AssertionError();
}
}
public final Kind kind;
public final Type boundType;
}
}

View File

@@ -0,0 +1,657 @@
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.sun.tools.classfile.TypeAnnotation.Position.TypePathEntry;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class TypeAnnotation {
TypeAnnotation(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
constant_pool = cr.getConstantPool();
position = read_position(cr);
annotation = new Annotation(cr);
}
public TypeAnnotation(ConstantPool constant_pool,
Annotation annotation, Position position) {
this.constant_pool = constant_pool;
this.position = position;
this.annotation = annotation;
}
public int length() {
int n = annotation.length();
n += position_length(position);
return n;
}
@Override
public String toString() {
try {
return "@" + constant_pool.getUTF8Value(annotation.type_index).toString().substring(1) +
" pos: " + position.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
public final ConstantPool constant_pool;
public final Position position;
public final Annotation annotation;
private static Position read_position(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
// Copied from ClassReader
int tag = cr.readUnsignedByte(); // TargetType tag is a byte
if (!TargetType.isValidTargetTypeValue(tag))
throw new Annotation.InvalidAnnotation("TypeAnnotation: Invalid type annotation target type value: " + String.format("0x%02X", tag));
TargetType type = TargetType.fromTargetTypeValue(tag);
Position position = new Position();
position.type = type;
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
position.offset = cr.readUnsignedShort();
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = cr.readUnsignedShort();
position.lvarOffset = new int[table_length];
position.lvarLength = new int[table_length];
position.lvarIndex = new int[table_length];
for (int i = 0; i < table_length; ++i) {
position.lvarOffset[i] = cr.readUnsignedShort();
position.lvarLength[i] = cr.readUnsignedShort();
position.lvarIndex[i] = cr.readUnsignedShort();
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
position.exception_index = cr.readUnsignedShort();
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
position.parameter_index = cr.readUnsignedByte();
position.bound_index = cr.readUnsignedByte();
break;
// class extends or implements clause
case CLASS_EXTENDS:
int in = cr.readUnsignedShort();
if (in == 0xFFFF)
in = -1;
position.type_index = in;
break;
// throws
case THROWS:
position.type_index = cr.readUnsignedShort();
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
position.offset = cr.readUnsignedShort();
position.type_index = cr.readUnsignedByte();
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + type);
}
{ // Write type path
int len = cr.readUnsignedByte();
List<Integer> loc = new ArrayList<Integer>(len);
for (int i = 0; i < len * TypePathEntry.bytesPerEntry; ++i)
loc.add(cr.readUnsignedByte());
position.location = Position.getTypePathFromBinary(loc);
}
return position;
}
private static int position_length(Position pos) {
int n = 0;
n += 1; // TargetType tag is a byte
switch (pos.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
n += 2; // offset
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
n += 2; // table_length;
int table_length = pos.lvarOffset.length;
n += 2 * table_length; // offset
n += 2 * table_length; // length
n += 2 * table_length; // index
break;
// exception parameter
case EXCEPTION_PARAMETER:
n += 2; // exception_index
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
n += 1; // parameter_index
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
n += 1; // parameter_index
n += 1; // bound_index
break;
// class extends or implements clause
case CLASS_EXTENDS:
n += 2; // type_index
break;
// throws
case THROWS:
n += 2; // type_index
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
n += 1; // parameter_index
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
n += 2; // offset
n += 1; // type index
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + pos.type);
}
{
n += 1; // length
n += TypePathEntry.bytesPerEntry * pos.location.size(); // bytes for actual array
}
return n;
}
// Code duplicated from com.sun.tools.javac.code.TypeAnnotationPosition
public static class Position {
public enum TypePathEntryKind {
ARRAY(0),
INNER_TYPE(1),
WILDCARD(2),
TYPE_ARGUMENT(3);
public final int tag;
private TypePathEntryKind(int tag) {
this.tag = tag;
}
}
public static class TypePathEntry {
/** The fixed number of bytes per TypePathEntry. */
public static final int bytesPerEntry = 2;
public final TypePathEntryKind tag;
public final int arg;
public static final TypePathEntry ARRAY = new TypePathEntry(TypePathEntryKind.ARRAY);
public static final TypePathEntry INNER_TYPE = new TypePathEntry(TypePathEntryKind.INNER_TYPE);
public static final TypePathEntry WILDCARD = new TypePathEntry(TypePathEntryKind.WILDCARD);
private TypePathEntry(TypePathEntryKind tag) {
if (!(tag == TypePathEntryKind.ARRAY ||
tag == TypePathEntryKind.INNER_TYPE ||
tag == TypePathEntryKind.WILDCARD)) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = 0;
}
public TypePathEntry(TypePathEntryKind tag, int arg) {
if (tag != TypePathEntryKind.TYPE_ARGUMENT) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = arg;
}
public static TypePathEntry fromBinary(int tag, int arg) {
if (arg != 0 && tag != TypePathEntryKind.TYPE_ARGUMENT.tag) {
throw new AssertionError("Invalid TypePathEntry tag/arg: " + tag + "/" + arg);
}
switch (tag) {
case 0:
return ARRAY;
case 1:
return INNER_TYPE;
case 2:
return WILDCARD;
case 3:
return new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT, arg);
default:
throw new AssertionError("Invalid TypePathEntryKind tag: " + tag);
}
}
@Override
public String toString() {
return tag.toString() +
(tag == TypePathEntryKind.TYPE_ARGUMENT ? ("(" + arg + ")") : "");
}
@Override
public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) {
return false;
}
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
}
@Override
public int hashCode() {
return this.tag.hashCode() * 17 + this.arg;
}
}
public TargetType type = TargetType.UNKNOWN;
// For generic/array types.
// TODO: or should we use null? Noone will use this object.
public List<TypePathEntry> location = new ArrayList<TypePathEntry>(0);
// Tree position.
public int pos = -1;
// For typecasts, type tests, new (and locals, as start_pc).
public boolean isValidOffset = false;
public int offset = -1;
// For locals. arrays same length
public int[] lvarOffset = null;
public int[] lvarLength = null;
public int[] lvarIndex = null;
// For type parameter bound
public int bound_index = Integer.MIN_VALUE;
// For type parameter and method parameter
public int parameter_index = Integer.MIN_VALUE;
// For class extends, implements, and throws clauses
public int type_index = Integer.MIN_VALUE;
// For exception parameters, index into exception table
public int exception_index = Integer.MIN_VALUE;
public Position() {}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(type);
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
sb.append(", offset = ");
sb.append(offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
if (lvarOffset == null) {
sb.append(", lvarOffset is null!");
break;
}
sb.append(", {");
for (int i = 0; i < lvarOffset.length; ++i) {
if (i != 0) sb.append("; ");
sb.append("start_pc = ");
sb.append(lvarOffset[i]);
sb.append(", length = ");
sb.append(lvarLength[i]);
sb.append(", index = ");
sb.append(lvarIndex[i]);
}
sb.append("}");
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
sb.append(", param_index = ");
sb.append(parameter_index);
sb.append(", bound_index = ");
sb.append(bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// throws
case THROWS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// exception parameter
case EXCEPTION_PARAMETER:
sb.append(", exception_index = ");
sb.append(exception_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
sb.append(", offset = ");
sb.append(offset);
sb.append(", type_index = ");
sb.append(type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
sb.append(", position UNKNOWN!");
break;
default:
throw new AssertionError("Unknown target type: " + type);
}
// Append location data for generics/arrays.
if (!location.isEmpty()) {
sb.append(", location = (");
sb.append(location);
sb.append(")");
}
sb.append(", pos = ");
sb.append(pos);
sb.append(']');
return sb.toString();
}
/**
* Indicates whether the target tree of the annotation has been optimized
* away from classfile or not.
* @return true if the target has not been optimized away
*/
public boolean emitToClassfile() {
return !type.isLocal() || isValidOffset;
}
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
*
* @param list The bytecode representation of the type path.
*/
public static List<TypePathEntry> getTypePathFromBinary(List<Integer> list) {
List<TypePathEntry> loc = new ArrayList<TypePathEntry>(list.size() / TypePathEntry.bytesPerEntry);
int idx = 0;
while (idx < list.size()) {
if (idx + 1 == list.size()) {
throw new AssertionError("Could not decode type path: " + list);
}
loc.add(TypePathEntry.fromBinary(list.get(idx), list.get(idx + 1)));
idx += 2;
}
return loc;
}
public static List<Integer> getBinaryFromTypePath(List<TypePathEntry> locs) {
List<Integer> loc = new ArrayList<Integer>(locs.size() * TypePathEntry.bytesPerEntry);
for (TypePathEntry tpe : locs) {
loc.add(tpe.tag.tag);
loc.add(tpe.arg);
}
return loc;
}
}
// Code duplicated from com.sun.tools.javac.code.TargetType
// The IsLocal flag could be removed here.
public enum TargetType {
/** For annotations on a class type parameter declaration. */
CLASS_TYPE_PARAMETER(0x00),
/** For annotations on a method type parameter declaration. */
METHOD_TYPE_PARAMETER(0x01),
/** For annotations on the type of an "extends" or "implements" clause. */
CLASS_EXTENDS(0x10),
/** For annotations on a bound of a type parameter of a class. */
CLASS_TYPE_PARAMETER_BOUND(0x11),
/** For annotations on a bound of a type parameter of a method. */
METHOD_TYPE_PARAMETER_BOUND(0x12),
/** For annotations on a field. */
FIELD(0x13),
/** For annotations on a method return type. */
METHOD_RETURN(0x14),
/** For annotations on the method receiver. */
METHOD_RECEIVER(0x15),
/** For annotations on a method parameter. */
METHOD_FORMAL_PARAMETER(0x16),
/** For annotations on a throws clause in a method declaration. */
THROWS(0x17),
/** For annotations on a local variable. */
LOCAL_VARIABLE(0x40, true),
/** For annotations on a resource variable. */
RESOURCE_VARIABLE(0x41, true),
/** For annotations on an exception parameter. */
EXCEPTION_PARAMETER(0x42, true),
/** For annotations on a type test. */
INSTANCEOF(0x43, true),
/** For annotations on an object creation expression. */
NEW(0x44, true),
/** For annotations on a constructor reference receiver. */
CONSTRUCTOR_REFERENCE(0x45, true),
/** For annotations on a method reference receiver. */
METHOD_REFERENCE(0x46, true),
/** For annotations on a typecast. */
CAST(0x47, true),
/** For annotations on a type argument of an object creation expression. */
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(0x48, true),
/** For annotations on a type argument of a method call. */
METHOD_INVOCATION_TYPE_ARGUMENT(0x49, true),
/** For annotations on a type argument of a constructor reference. */
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(0x4A, true),
/** For annotations on a type argument of a method reference. */
METHOD_REFERENCE_TYPE_ARGUMENT(0x4B, true),
/** For annotations with an unknown target. */
UNKNOWN(0xFF);
private static final int MAXIMUM_TARGET_TYPE_VALUE = 0x4B;
private final int targetTypeValue;
private final boolean isLocal;
private TargetType(int targetTypeValue) {
this(targetTypeValue, false);
}
private TargetType(int targetTypeValue, boolean isLocal) {
if (targetTypeValue < 0
|| targetTypeValue > 255)
throw new AssertionError("Attribute type value needs to be an unsigned byte: " + String.format("0x%02X", targetTypeValue));
this.targetTypeValue = targetTypeValue;
this.isLocal = isLocal;
}
/**
* Returns whether or not this TargetType represents an annotation whose
* target is exclusively a tree in a method body
*
* Note: wildcard bound targets could target a local tree and a class
* member declaration signature tree
*/
public boolean isLocal() {
return isLocal;
}
public int targetTypeValue() {
return this.targetTypeValue;
}
private static final TargetType[] targets;
static {
targets = new TargetType[MAXIMUM_TARGET_TYPE_VALUE + 1];
TargetType[] alltargets = values();
for (TargetType target : alltargets) {
if (target.targetTypeValue != UNKNOWN.targetTypeValue)
targets[target.targetTypeValue] = target;
}
for (int i = 0; i <= MAXIMUM_TARGET_TYPE_VALUE; ++i) {
if (targets[i] == null)
targets[i] = UNKNOWN;
}
}
public static boolean isValidTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return true;
return (tag >= 0 && tag < targets.length);
}
public static TargetType fromTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return UNKNOWN;
if (tag < 0 || tag >= targets.length)
throw new AssertionError("Unknown TargetType: " + tag);
return targets[tag];
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
A minimalist library to read and write class files into objects closely
based on the corresponding definitions in
<cite>The Java&trade; Virtual Machine Specification</cite> (JVMS).
<p><b>This is NOT part of any supported API.
If you write code that depends on this, you do so at your own risk.
This code and its internal interfaces are subject to change or
deletion without notice.</b>
*/
@jdk.Exported(false)
package com.sun.tools.classfile;

View File

@@ -0,0 +1,325 @@
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
// -F46082.51<daz> Remove -stateful option. "Stateful interfaces" obsolete.
// -D58319<daz> Add -version option. Note that this may occur as the last
// argument on the command-line.
// -F60858.1<daz> Add -corba [level] option. Accept IDL upto this level, and
// behave in a "proprietary manner" otherwise.
// -D62023<daz> Add -noWarn option to supress warnings.
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import java.util.StringTokenizer;
import java.lang.reflect.Modifier;
import java.lang.reflect.Field;
import com.sun.tools.corba.se.idl.som.cff.FileLocator;
/**
* This class is responsible for parsing the command line arguments to the
* compiler. To add new arguments to the compiler, this class must be extended
* and the parseOtherArgs method overridden.
**/
public class Arguments
{
/**
* Method parseOtherArgs() is called when the framework detects arguments
* which are unknown to it. The default implementation of this method simply
* throws an InvalidArgument exception. Any overriding implementation
* must check the arguments passed to it for validity and process the
* arguments appropriately. If it detects an invalid argument, it should
* throw an InvalidArgument exception. Arguments MUST be of the form
* `/<arg> [<qualifiers>]' or `-<arg> [<qualifiers>]' where <qualifiers>
* is optional (for example, -iC:\includes, `C:\includes' is the qualifier
* for the argument `i').
* @param args The arguments which are unknown by the framework.
* @param properties Environment-style properties collected from the
* file idl.config.
* @exception idl.InvalidArgument if the argument is unknown.
**/
protected void parseOtherArgs (String[] args, Properties properties) throws InvalidArgument
{
if (args.length > 0)
throw new InvalidArgument (args[0]);
} // parseOtherArgs
protected void setDebugFlags( String args )
{
StringTokenizer st = new StringTokenizer( args, "," ) ;
while (st.hasMoreTokens()) {
String token = st.nextToken() ;
// If there is a public boolean data member in this class
// named token + "DebugFlag", set it to true.
try {
Field fld = this.getClass().getField( token + "DebugFlag" ) ;
int mod = fld.getModifiers() ;
if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod ))
if (fld.getType() == boolean.class)
fld.setBoolean( this, true ) ;
} catch (Exception exc) {
// ignore it
}
}
}
/**
* Collect the command-line parameters.
**/
void parseArgs (String[] args) throws InvalidArgument {
Vector unknownArgs = new Vector ();
int i = 0;
try {
// Process command line parameters
for (i = 0; i < args.length - 1; ++i) {
String lcArg = args[i].toLowerCase ();
if (lcArg.charAt (0) != '-' && lcArg.charAt (0) != '/')
throw new InvalidArgument (args[i]);
if (lcArg.charAt (0) == '-' ) {
lcArg = lcArg.substring (1);
}
// Include path
if (lcArg.equals ("i")) {
includePaths.addElement (args[++i]);
} else if (lcArg.startsWith ("i")) {
includePaths.addElement (args[i].substring (2));
} else if (lcArg.equals ("v") || lcArg.equals ("verbose")) {
// Verbose mode
verbose = true;
} else if (lcArg.equals ("d")) {
// Define symbol
definedSymbols.put (args[++i], "");
} else if (lcArg.equals( "debug" )) {
// Turn on debug flags
setDebugFlags( args[++i] ) ;
} else if (lcArg.startsWith ("d")) {
definedSymbols.put (args[i].substring (2), "");
} else if (lcArg.equals ("emitall")) {
// Emit bindings for included sources
emitAll = true;
} else if (lcArg.equals ("keep")) {
// Keep old files
keepOldFiles = true;
} else if (lcArg.equals ("nowarn")) {
// <d62023> Suppress warnings
noWarn = true;
} else if (lcArg.equals ("trace")) {
// Allow tracing.
Runtime.getRuntime ().traceMethodCalls (true);
}
// <f46082.51> Remove -stateful feature.
//else if (lcArg.equals ("stateful"))
//{
// Emit stateful bindings.
// parseStateful = true;
//}
// CPPModule
else if ( lcArg.equals ("cppmodule")) {
cppModule = true;
} else if (lcArg.equals ("version")) {
// Version
versionRequest = true;
} else if (lcArg.equals ("corba")) {
// CORBA level
if (i + 1 >= args.length)
throw new InvalidArgument (args[i]);
String level = args[++i];
if (level.charAt (0) == '-')
throw new InvalidArgument (args[i - 1]);
try {
corbaLevel = new Float (level).floatValue ();
} catch (NumberFormatException e) {
throw new InvalidArgument (args[i]);
}
} else {
unknownArgs.addElement (args[i]);
++i;
while (i < (args.length - 1) &&
args[i].charAt (0) != '-' &&
args[i].charAt (0) != '/') {
unknownArgs.addElement (args[i++]);
}
--i;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
// If there is any array indexing problem, it is probably
// because the qualifier on the last argument is missing.
// Report that this last argument is invalid.
throw new InvalidArgument (args[args.length - 1]);
}
// <d57319>
// The last argument is the file argument or "-version", which may
// be specified without a file argument.
if (i == args.length - 1) {
if (args[i].toLowerCase ().equals ("-version"))
versionRequest = true;
else
file = args[i];
} else
throw new InvalidArgument ();
// Get and process the idl.config file.
Properties props = new Properties ();
try {
DataInputStream stream = FileLocator.locateFileInClassPath ("idl.config");
props.load (stream);
addIncludePaths (props);
} catch (IOException e) {
}
// Call parseOtherArgs. By default, if there are unknown args,
// InvalidArgument is called. A call to parseOtherArgs is useful
// only when this framework has been extended.
String[] otherArgs;
if (unknownArgs.size () > 0) {
otherArgs = new String[unknownArgs.size ()];
unknownArgs.copyInto (otherArgs);
} else
otherArgs = new String[0];
parseOtherArgs (otherArgs, props);
} // parseArgs
/**
*
**/
private void addIncludePaths (Properties props)
{
String paths = props.getProperty ("includes");
if (paths != null)
{
String separator = System.getProperty ("path.separator");
int end = -separator.length (); // so the first pass paths == original paths
do
{
paths = paths.substring (end + separator.length ());
end = paths.indexOf (separator);
if (end < 0)
end = paths.length ();
includePaths.addElement (paths.substring (0, end));
}
while (end != paths.length ());
}
} // addIncludePaths
/**
* The name of the IDL file.
**/
public String file = null;
/**
* True if the user wishes to see processing remarks.
**/
public boolean verbose = false;
/**
* If this is true, then existing files should not be overwritten
* by the compiler.
**/
public boolean keepOldFiles = false;
/**
* If this is true, then the types in all included files are also emitted.
**/
public boolean emitAll = false;
// <f46082.51> Remove -stateful feature.
///**
// * If this is true, then stateful interfaces (for the Objects-by-Value
// * proposal) are allowed. This is not yet a standard, so it must
// * explicitly be called for by setting the -stateful argument to the
// * compiler. If -stateful does not appear on the command line, then
// * the IDL will be parsed according to the standards.
// **/
//public boolean parseStateful = false;
/**
* A list of strings, each of which is a path from which included files
* are found.
**/
public Vector includePaths = new Vector ();
/**
* A table of defined symbols. The key is the symbol name; the value
* (if any) is the replacement value for the symbol.
**/
public Hashtable definedSymbols = new Hashtable ();
/**
* <f46082.46.01> True if new module entries are created for each
* re-opened module.
**/
public boolean cppModule = false;
/**
* -version option.
**/
public boolean versionRequest = false; // <D58319>
// <f60858.1> Specify the maximal level of the CORBA spec. the parser
// will support.
//
// NOTE: For BOSS 3.0, specify at 2.2. Raise to greater value in future
// releases.
/**
* -corba [level] option, where [level] is a floating-point number indicating
* the maximal level of CORBA IDL the parser framework can accept.
**/
public float corbaLevel = 2.2f;
// <d62023>
/**
* -noWarn option. Suppress warnings when true.
**/
public boolean noWarn = false; // Issue warnings by default.
// Currently defined debug flags. Any additions must be called xxxDebugFlag.
// All debug flags must be public boolean types.
// These are set by passing the flag -ORBDebug x,y,z in the ORB init args.
// Note that x,y,z must not contain spaces.
public boolean scannerDebugFlag = false ;
public boolean tokenDebugFlag = false ;
} // class Arguments

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
/**
* This is the symbol table entry for attributes. An attribute is simply
* two methods with no exceptions or contexts: a get method and, if not
* readOnly, a set method.
**/
public class AttributeEntry extends MethodEntry
{
protected AttributeEntry ()
{
super ();
} // ctor
protected AttributeEntry (AttributeEntry that)
{
super (that);
_readOnly = that._readOnly;
} // ctor
protected AttributeEntry (InterfaceEntry that, IDLID clone)
{
super (that, clone);
} // ctor
public Object clone ()
{
return new AttributeEntry (this);
} // clone
/** Invoke the attribute generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
attributeGen.generate (symbolTable, this, stream);
} // generate
/** Access the attribute generator.
@returns an object which implements the AttributeGen interface.
@see AttributeGen */
public Generator generator ()
{
return attributeGen;
} // generator
/** if true, only a get method will be generated. */
public boolean readOnly ()
{
return _readOnly;
} // readOnly
/** if true, only a get method will be generated. */
public void readOnly (boolean readOnly)
{
_readOnly = readOnly;
} // readOnly
static AttributeGen attributeGen;
public boolean _readOnly = false;
} // class AttributeEntry

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
public interface AttributeGen extends Generator
{
void generate (Hashtable symbolTable, AttributeEntry entry, PrintWriter stream);
} // interface AttributeGen

View File

@@ -0,0 +1,208 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
public class Comment
{
// Styles
static final int UNKNOWN = -1;
static final int JAVA_DOC = 0;
static final int C_BLOCK = 1;
static final int CPP_LINE = 2;
// System-dependent line separator
private static String _eol = System.getProperty ("line.separator");
private String _text = new String ("");
private int _style = UNKNOWN;
Comment () {_text = new String (""); _style = UNKNOWN;} // ctor
Comment (String text) {_text = text; _style = style (_text);} // ctor
/** Sets comment text */
public void text (String string) {_text = string; _style = style (_text);}
/** Returns comment text */
public String text () {return _text;}
/** Returns the comment style of a string. */
private int style (String text)
{
if (text == null)
return UNKNOWN;
else if (text.startsWith ("/**") && text.endsWith ("*/"))
return JAVA_DOC;
else if (text.startsWith ("/*") && text.endsWith ("*/"))
return C_BLOCK;
else if (text.startsWith ("//"))
return CPP_LINE;
else
return UNKNOWN;
} // style
/** Writes comment text to standard output (debug). */
public void write () {System.out.println (_text);}
/** Writes comment text to the specified print stream in the appropriate format. */
public void generate (String indent, PrintWriter printStream)
{
if (_text == null || printStream == null)
return;
if (indent == null)
indent = new String ("");
switch (_style)
{
case JAVA_DOC:
//printJavaDoc (indent, printStream);
print (indent, printStream);
break;
case C_BLOCK:
//printCBlock (indent, printStream);
print (indent, printStream);
break;
case CPP_LINE:
//printCppLine (indent, printStream);
print (indent, printStream);
break;
default:
break;
}
} // generate
/** Writes comment to the specified print stream without altering its format.
This routine does not alter vertical or horizontal spacing of comment text,
thus, it only works well for comments with a non-indented first line. */
private void print (String indent, PrintWriter stream)
{
String text = _text.trim () + _eol;
String line = null;
int iLineStart = 0;
int iLineEnd = text.indexOf (_eol);
int iTextEnd = text.length () - 1;
stream.println ();
while (iLineStart < iTextEnd)
{
line = text.substring (iLineStart, iLineEnd);
stream.println (indent + line);
iLineStart = iLineEnd + _eol.length ();
iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol);
}
} // print
/*
* The following routines print formatted comments of differing styles.
* Each routine will alter the horizontal spacing of the comment text,
* but not the vertical spacing.
*/
/** Writes comment in JavaDoc-style to the specified print stream. */
private void printJavaDoc (String indent, PrintWriter stream)
{
// Strip surrounding "/**", "*/", and whitespace; append sentinel
String text = _text.substring (3, (_text.length () - 2)).trim () + _eol;
String line = null;
int iLineStart = 0;
int iLineEnd = text.indexOf (_eol);
int iTextEnd = text.length () - 1; // index of last text character
stream.println (_eol + indent + "/**");
while (iLineStart < iTextEnd)
{
line = text.substring (iLineStart, iLineEnd).trim ();
if (line.startsWith ("*"))
// Strip existing "*<ws>" prefix
stream.println (indent + " * " + line.substring (1, line.length ()).trim ());
else
stream.println (indent + " * " + line);
iLineStart = iLineEnd + _eol.length ();
iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol);
}
stream.println (indent + " */");
} // printJavaDoc
/** Writes comment in c-block-style to the specified print stream. */
private void printCBlock (String indent, PrintWriter stream)
{
// Strip surrounding "/*", "*/", and whitespace; append sentinel
String text = _text.substring (2, (_text.length () - 2)).trim () + _eol;
String line = null;
int iLineStart = 0;
int iLineEnd = text.indexOf (_eol);
int iTextEnd = text.length () - 1; // index of last text character
stream.println (indent + "/*");
while (iLineStart < iTextEnd)
{
line = text.substring (iLineStart, iLineEnd).trim ();
if (line.startsWith ("*"))
// Strip existing "*[ws]" prefix
stream.println (indent + " * " + line.substring (1, line.length ()).trim ());
else
stream.println (indent + " * " + line);
iLineStart = iLineEnd + _eol.length ();
iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol);
}
stream.println (indent + " */");
} // printCBlock
/** Writes a line comment to the specified print stream. */
private void printCppLine (String indent, PrintWriter stream)
{
stream.println (indent + "//");
// Strip "//[ws]" prefix
stream.println (indent + "// " + _text.substring (2).trim ());
stream.println (indent + "//");
} // printCppLine
} // class Comment
/*==================================================================================
DATE<AUTHOR> ACTION
----------------------------------------------------------------------------------
11aug1997<daz> Initial version completed.
18aug1997<daz> Modified generate to write comment unformatted.
==================================================================================*/

View File

@@ -0,0 +1,520 @@
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
// -D56351<daz> Update computation of RepositoryIDs to CORBA 2.3 (see spec.).
// -D58319<daz> Display version info. for -version option.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import com.sun.tools.corba.se.idl.constExpr.ExprFactory;
import com.sun.tools.corba.se.idl.constExpr.DefaultExprFactory;
/**
* Compiler usage:
* <br><br>
*
* java com.sun.tools.corba.se.idl.toJava.compile [options] <idl file>
* <br><br>
*
* where &lt;idl file&gt; is the name of a file containing IDL definitions,
* and [options] is any combination of the options listed below. The options
* and the idl file name can appear in any order.
* <br><br>
*
* Options:
* <dl>
* <dt>-i &lt;include path&gt;
* <dd>By default, the current directory is scanned for included files.
* This option adds another directory. See also Note 1 below.
*
* <dt>-d &lt;symbol&gt;
* <dd>This is equivalent to the following line in an IDL file: #define &lt;symbol&gt;
*
* <dt>-emitAll
* <dd>Emit all types, including those found in #included files.
*
* <dt>-v
* <dd>Verbose mode.
* </dl>
*
* Note 1: If you have an include path or paths that you will always be using,
* it can get tedious putting these on the command with the -i option all the
* time. Instead, these can be placed into a config file called idl.config.
* This file must be in the CLASSPATH. The format of the includes line is:
*
* <pre>
* includes=<path1>;<path2>;...;<pathN>
* </pre>
*
* Note that the path separator character, here shown as a semicolon, is
* machine dependent. For instance, on Windows 95 this character is a
* semicolon, on UNIX it is a colon.
*
* <p>
* Note 2: If you are directly invoking the main method on this class (not
* a subclass), then it will only check that the IDL file is syntactically
* correct. It does not generate any files. Only extensions to this
* framework generate files, therefore an extension must be invoked if you
* want files to be generated.
* <br><br>
*
* To Extend the compiler:
* <br><br>
*
* You only need to extend the compiler if you want it to generate something
* other than what it currently generates.
* <br><br>
*
* Step 1 - Implement the generator interfaces:
* <br><br>
*
* Each generator interface defines one method: generate (Hashtable, XXXEntry, PrintWriter);
* <br>
* - The Hashtable is the symbol table; each element is a SymtabEntry (or a
* subclass of SymtabEntry) and is keyed by its fully qualified name;
* <br>
* - XXXEntry is the appropriate entry for the type to be generated. For
* example: AttributeGen defines generate (Hashtable, AttributeEntry, PrintWriter);
* ConstGen defines generate (Hashtable, ConstEntry, PrintWriter); etc.
* <br>
* - The PrintWriter is a stream to the file being generated. For the
* generators called by the compiler framework, this will be null. The
* generator is responsible for creating and opening files. But for
* generators that are called by other generators - for instance,
* MethodGen.generate will most likely be called by InterfaceGen.generate -
* this parameter is provided so that the proper file can be written to.
* <br><br>
*
* Step 2 - Implement the GenFactory interface:
* <br><br>
*
* All of the generators implemented in Step 1 must be created somehow. There
* is an interface for a factory, GenFactory, which must be implemented. The
* name of this factory must be set in the extension to the Compile class (see
* Step 3, below).
* <br><br>
*
* Step 3 - Extend com.sun.tools.corba.se.idl.Factories:
* <br><br>
*
* Extend com.sun.tools.corba.se.idl.Factories and override the method genFactory. This
* method must return an instance of the factory which you implemented in
* step 2. Your extension of this class may also do more, this is only the
* minimum. See com.sun.tools.corba.se.idl.Factories for more information.
* <br><br>
*
* Step 4 - Extend com.sun.tools.corba.se.idl.Compile:
* <br><br>
*
* Your extension of com.sun.tools.corba.se.idl.Compile should contain a minimum of
* two methods:
* <dl>
* <dt>protected com.sun.tools.corba.se.idl.Factories ()
* <dd>This method overrides com.sun.tools.corba.se.idl.Compile.factories and returns your
* extension from Step 3.
*
* <dt>public static void main (String[] args)
* <dd>This main method must instantiate this class and call its start method.
* </dl>
*
* Given that the extension of Factories is MyFactories, the extension of
* Compile could be:
*
* <pre>
* public class MyCompile extends com.sun.tools.corba.se.idl.Compile
* {
* protected com.sun.tools.corba.se.idl.Factories factories ()
* {
* return new MyFactories ();
* }
* public static void main (String[] args)
* {
* MyCompile compile = new MyCompile ();
* compile.start (args);
* }
* }
* </pre>
*
* If you would like a bit more control over the processing of the framework,
* you can replace compile.start with what it calls. But then you also have
* to handle the exceptions which start handles for you:
* <pre>
* public class MyCompile extends com.sun.tools.corba.se.idl.Compile
* {
* ...
*
* public static void main (String[] args)
* {
* MyCompile compile = new MyCompile ();
* try
* {
* compile.init (args);
* java.util.Enumeration emitList = compile.parse ();
* compile.generate ();
* }
* catch (com.sun.tools.corba.se.idl.InvalidArgument e)
* {
* System.err.println (e);
* }
* catch (java.io.IOException e)
* {
* System.err.println (e);
* }
* }
* }
* </pre>
*
* Note that compile.parse returns an enumeration. This enumerates the
* SymtabEntry's which should be generated. If the parse method detects
* errors, it returns null. Note that you do not have to check that
* `emitList' is valid before calling generate (that's done internally), but
* if you do any processing between parse and generate, emitList should be
* checked before executing that code.
* <br><br>
**/
public class Compile
{
public Compile ()
{
noPragma.init (preprocessor);
preprocessor.registerPragma (noPragma);
// <d41197> Reset static variables to allow parsing multiple sources.
// DO NOT reset SymtabEntry.maxKey because it crashes IDLC.
ParseException.detected = false;
SymtabEntry.includeStack = new java.util.Stack ();
SymtabEntry.setEmit = true;
//SymtabEntry.maxKey = -1;
Parser.repIDStack = new java.util.Stack (); // <d56351>
} // ctor
public static void main (String[] args)
{
(new Compile ()).start (args);
} // main
protected Factories factories ()
{
return new Factories ();
} // genFactoryName
protected void registerPragma (PragmaHandler handler)
{
handler.init (preprocessor);
preprocessor.registerPragma (handler);
} // registerPragma
/**
* Initialize the framework.
**/
protected void init (String[] args) throws InvalidArgument
{
initFactories ();
arguments.parseArgs (args);
initGenerators ();
parser = new Parser (preprocessor, arguments, overrideNames, symbolTable, symtabFactory, exprFactory, keywords);
preprocessor.init (parser);
parser.includes = includes;
parser.includeEntries = includeEntries;
} // init
/**
* Parse the IDL file and return an enumeration of the symbols to be
* generated. All elements of the Enumeration will be extensions of
* SymtabEntry. If any errors were encountered during parsing, null
* will be returned.
**/
protected Enumeration parse () throws IOException
{
if (arguments.verbose)
System.out.println (Util.getMessage ("Compile.parsing", arguments.file));
parser.parse (arguments.file);
if ( !ParseException.detected )
{
parser.forwardEntryCheck();
// <46082.03> Revert to "IDL:"-style (i.e., regular) repository ID.
//parser.updateRepositoryIds();
}
if (arguments.verbose)
System.out.println (Util.getMessage ("Compile.parseDone", arguments.file));
if (ParseException.detected)
{
symbolTable = null;
emitList = null;
}
else
{
symbolTable = parser.symbolTable;
emitList = parser.emitList.elements ();
}
return emitList;
} // parse
/**
* Invoke the generators.
**/
protected void generate () throws IOException
{
/*
// print the symbol table
Enumeration v = parser.symbolTable.elements ();
Enumeration k = parser.symbolTable.keys ();
while (k.hasMoreElements ())
System.out.println (k.nextElement () + ": " + v.nextElement ());
*/
if (ParseException.detected)
emitList = null;
else
emitList = parser.emitList.elements ();
if (emitList != null)
{
// Emit the output files for all of the types in the IDL file
if (arguments.verbose)
System.out.println ();
while (emitList.hasMoreElements ())
{
SymtabEntry entry = (SymtabEntry)emitList.nextElement ();
if (arguments.verbose)
if (entry.generator () instanceof Noop)
; // Nothing will be generated, so don't say so.
else if (entry.module () . equals (""))
System.out.println (Util.getMessage ("Compile.generating", entry.name ()));
else
System.out.println (Util.getMessage ("Compile.generating", entry.module () + '/' + entry.name ()));
entry.generate (symbolTable, null);
if (arguments.verbose)
if (entry.generator () instanceof Noop)
; // Nothing will be generated, so don't say so.
else if (entry.module () . equals (""))
System.out.println (Util.getMessage ("Compile.genDone", entry.name ()));
else
System.out.println (Util.getMessage ("Compile.genDone", entry.module () + '/' + entry.name ()));
}
}
} // generate
/**
* Start the parse/code generation process. This method calls init,
* parse, generate. If more control is desired, rather than call start,
* those three methods could be called explicitly.
**/
public void start (String[] args)
{
try
{
init (args);
if (arguments.versionRequest) // <d59319>
displayVersion ();
else
{
parse ();
generate ();
}
}
catch (InvalidArgument e)
{
System.err.println (e);
}
catch (IOException e)
{
System.err.println (e);
}
} // start
private void initFactories ()
{
// Get the factories.
Factories factories = factories ();
if (factories == null) factories = new Factories ();
// Get the argument processor from the factories.
Arguments tmpArgs = factories.arguments ();
if (tmpArgs == null)
arguments = new Arguments ();
else
arguments = tmpArgs;
// Get the symbol table entry factory from the factories.
SymtabFactory tmpSTF = factories.symtabFactory ();
if (tmpSTF == null)
symtabFactory = new DefaultSymtabFactory ();
else
symtabFactory = tmpSTF;
// Get the expression factory from the factories.
ExprFactory tmpExpF = factories.exprFactory ();
if (tmpExpF == null)
exprFactory = new DefaultExprFactory ();
else
exprFactory = tmpExpF;
// Get the generator factory from the factories.
GenFactory tmpGenF = factories.genFactory ();
if (tmpGenF == null)
genFactory = noop;
else
genFactory = tmpGenF;
// Get the language keywords.
keywords = factories.languageKeywords ();
if (keywords == null)
keywords = new String[0];
} // initFactories
private void initGenerators ()
{
AttributeGen agen = genFactory.createAttributeGen ();
AttributeEntry.attributeGen = agen == null ? noop : agen;
ConstGen cgen = genFactory.createConstGen ();
ConstEntry.constGen = cgen == null ? noop : cgen;
EnumGen egen = genFactory.createEnumGen ();
EnumEntry.enumGen = egen == null ? noop : egen;
ExceptionGen exgen = genFactory.createExceptionGen ();
ExceptionEntry.exceptionGen = exgen == null ? noop : exgen;
ForwardGen fgen = genFactory.createForwardGen ();
ForwardEntry.forwardGen = fgen == null ? noop : fgen;
ForwardValueGen fvgen = genFactory.createForwardValueGen ();
ForwardValueEntry.forwardValueGen = fvgen == null ? noop : fvgen;
IncludeGen ingen = genFactory.createIncludeGen ();
IncludeEntry.includeGen = ingen == null ? noop : ingen;
InterfaceGen igen = genFactory.createInterfaceGen ();
InterfaceEntry.interfaceGen = igen == null ? noop : igen;
ValueGen vgen = genFactory.createValueGen ();
ValueEntry.valueGen = vgen == null ? noop : vgen;
ValueBoxGen vbgen = genFactory.createValueBoxGen ();
ValueBoxEntry.valueBoxGen = vbgen == null ? noop : vbgen;
MethodGen mgen = genFactory.createMethodGen ();
MethodEntry.methodGen = mgen == null ? noop : mgen;
ModuleGen modgen = genFactory.createModuleGen ();
ModuleEntry.moduleGen = modgen == null ? noop : modgen;
NativeGen ngen = genFactory.createNativeGen ();
NativeEntry.nativeGen = ngen == null ? noop : ngen;
ParameterGen pgen = genFactory.createParameterGen ();
ParameterEntry.parameterGen = pgen == null ? noop : pgen;
PragmaGen prgen = genFactory.createPragmaGen ();
PragmaEntry.pragmaGen = prgen == null ? noop : prgen;
PrimitiveGen primgen = genFactory.createPrimitiveGen ();
PrimitiveEntry.primitiveGen = primgen == null ? noop : primgen;
SequenceGen seqgen = genFactory.createSequenceGen ();
SequenceEntry.sequenceGen = seqgen == null ? noop : seqgen;
StringGen strgen = genFactory.createStringGen ();
StringEntry.stringGen = strgen == null ? noop : strgen;
StructGen sgen = genFactory.createStructGen ();
StructEntry.structGen = sgen == null ? noop : sgen;
TypedefGen tgen = genFactory.createTypedefGen ();
TypedefEntry.typedefGen = tgen == null ? noop : tgen;
UnionGen ugen = genFactory.createUnionGen ();
UnionEntry.unionGen = ugen == null ? noop : ugen;
} // initGenerators
/**
* Write the version number of this compiler to standard out.
**/
protected void displayVersion ()
{
String message = Util.getMessage ("Version.product", Util.getMessage ("Version.number"));
System.out.println (message);
}
/**
* This is the repository of emitter arguments.
**/
public Arguments arguments = null;
/**
* This hashtable contains <real name, alias> pairs. It is filled in by
* extenders in cases where they wish to override an IDL type name with
* some other name. For instance, when mapping to Java, there could be
* an overrideNames entry of <"TRUE", "true">. NOTE: Do NOT change this
* variable to a new Hash table. Just add elements to it.
**/
protected Hashtable overrideNames = new Hashtable ();
/**
* This is the symbol table. It will be empty until the parse method
* executes. If errors are encountered, the state of the symbol table
* is undefined.
**/
protected Hashtable symbolTable = new Hashtable ();
/**
* This is a vector of strings of the form "IDLfile" or <IDLfile>. It is
* a list of the files included in the given IDL file. It will be empty
* until the parse method executes. If errors are encountered, the state
* of this vector is undefined.
**/
protected Vector includes = new Vector ();
/**
* This is a vector of IncludeEntry's. It is a list of the files included
* in the given IDL file. It mirrors the includes vector. It will be empty
* until the parse method executes. If errors are encountered, the state of
* this vector is undefined.
**/
protected Vector includeEntries = new Vector ();
static Noop noop = new Noop ();
private GenFactory genFactory = null;
private SymtabFactory symtabFactory = null;
private ExprFactory exprFactory = null;
private Parser parser = null;
Preprocessor preprocessor = new Preprocessor ();
private NoPragma noPragma = new NoPragma ();
private Enumeration emitList = null;
private String[] keywords = null;
} // class Compile

View File

@@ -0,0 +1,112 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.constExpr.Expression;
/**
* This is the symbol table entry for constants.
**/
public class ConstEntry extends SymtabEntry
{
protected ConstEntry ()
{
super ();
} // ctor
protected ConstEntry (ConstEntry that)
{
super (that);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
_value = that._value;
} // ctor
/** This is a shallow copy constructor. */
protected ConstEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
/** This is a shallow copy clone. */
public Object clone ()
{
return new ConstEntry (this);
} // clone
/** Invoke the constant generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
constGen.generate (symbolTable, this, stream);
} // generate
/** Access the constant generator.
@returns an object which implements the ConstGen interface.
@see ConstGen */
public Generator generator ()
{
return constGen;
} // generator
public Expression value ()
{
return _value;
} // value
public void value (Expression newValue)
{
_value = newValue;
} // value
static ConstGen constGen;
private Expression _value = null;
} // class ConstEntry

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
public interface ConstGen extends Generator
{
void generate (Hashtable symbolTable, ConstEntry entry, PrintWriter stream);
} // interface ConstGen

View File

@@ -0,0 +1,257 @@
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
/**
* This factory constructs the default symbol table entries, namely,
* those declared within the package com.sun.tools.corba.se.idl.
**/
public class DefaultSymtabFactory implements SymtabFactory
{
public AttributeEntry attributeEntry ()
{
return new AttributeEntry ();
} // attributeEntry
public AttributeEntry attributeEntry (InterfaceEntry container, IDLID id)
{
return new AttributeEntry (container, id);
} // attributeEntry
public ConstEntry constEntry ()
{
return new ConstEntry ();
} // constEntry
public ConstEntry constEntry (SymtabEntry container, IDLID id)
{
return new ConstEntry (container, id);
} // constEntry
public NativeEntry nativeEntry ()
{
return new NativeEntry ();
} // interfaceEntry
public NativeEntry nativeEntry (SymtabEntry container, IDLID id)
{
return new NativeEntry (container, id);
} // interfaceEntry
public EnumEntry enumEntry ()
{
return new EnumEntry ();
} // enumEntry
public EnumEntry enumEntry (SymtabEntry container, IDLID id)
{
return new EnumEntry (container, id);
} // enumEntry
public ExceptionEntry exceptionEntry ()
{
return new ExceptionEntry ();
} // exceptionEntry
public ExceptionEntry exceptionEntry (SymtabEntry container, IDLID id)
{
return new ExceptionEntry (container, id);
} // exceptionEntry
public ForwardEntry forwardEntry ()
{
return new ForwardEntry ();
} // forwardEntry
public ForwardEntry forwardEntry (ModuleEntry container, IDLID id)
{
return new ForwardEntry (container, id);
} // forwardEntry
public ForwardValueEntry forwardValueEntry ()
{
return new ForwardValueEntry ();
} // forwardValueEntry
public ForwardValueEntry forwardValueEntry (ModuleEntry container, IDLID id)
{
return new ForwardValueEntry (container, id);
} // forwardValueEntry
public IncludeEntry includeEntry ()
{
return new IncludeEntry ();
} // includeEntry
public IncludeEntry includeEntry (SymtabEntry container)
{
return new IncludeEntry (container);
} // includeEntry
public InterfaceEntry interfaceEntry ()
{
return new InterfaceEntry ();
} // interfaceEntry
public InterfaceEntry interfaceEntry (ModuleEntry container, IDLID id)
{
return new InterfaceEntry (container, id);
} // interfaceEntry
public ValueEntry valueEntry ()
{
return new ValueEntry ();
} // valueEntry
public ValueEntry valueEntry (ModuleEntry container, IDLID id)
{
return new ValueEntry (container, id);
} // valueEntry
public ValueBoxEntry valueBoxEntry ()
{
return new ValueBoxEntry ();
} // valueBoxEntry
public ValueBoxEntry valueBoxEntry (ModuleEntry container, IDLID id)
{
return new ValueBoxEntry (container, id);
} // valueBoxEntry
public MethodEntry methodEntry ()
{
return new MethodEntry ();
} // methodEntry
public MethodEntry methodEntry (InterfaceEntry container, IDLID id)
{
return new MethodEntry (container, id);
} // methodEntry
public ModuleEntry moduleEntry ()
{
return new ModuleEntry ();
} // moduleEntry
public ModuleEntry moduleEntry (ModuleEntry container, IDLID id)
{
return new ModuleEntry (container, id);
} // moduleEntry
public ParameterEntry parameterEntry ()
{
return new ParameterEntry ();
} // parameterEntry
public ParameterEntry parameterEntry (MethodEntry container, IDLID id)
{
return new ParameterEntry (container, id);
} // parameterEntry
public PragmaEntry pragmaEntry ()
{
return new PragmaEntry ();
} // pragmaEntry
public PragmaEntry pragmaEntry (SymtabEntry container)
{
return new PragmaEntry (container);
} // pragmaEntry
public PrimitiveEntry primitiveEntry ()
{
return new PrimitiveEntry ();
} // primitiveEntry
/** "name" can be, but is not limited to, the primitive idl type names:
'char', 'octet', 'short', 'long', etc. The reason it is not limited
to these is that, as an extender, you may wish to override these names.
For instance, when generating Java code, octet translates to byte, so
there is an entry in Compile.overrideNames: <"octet", "byte"> and a
PrimitiveEntry in the symbol table for "byte". */
public PrimitiveEntry primitiveEntry (String name)
{
return new PrimitiveEntry (name);
} // primitiveEntry
public SequenceEntry sequenceEntry ()
{
return new SequenceEntry ();
} // sequenceEntry
public SequenceEntry sequenceEntry (SymtabEntry container, IDLID id)
{
return new SequenceEntry (container, id);
} // sequenceEntry
public StringEntry stringEntry ()
{
return new StringEntry ();
} // stringEntry
public StructEntry structEntry ()
{
return new StructEntry ();
} // structEntry
public StructEntry structEntry (SymtabEntry container, IDLID id)
{
return new StructEntry (container, id);
} // structEntry
public TypedefEntry typedefEntry ()
{
return new TypedefEntry ();
} // typedefEntry
public TypedefEntry typedefEntry (SymtabEntry container, IDLID id)
{
return new TypedefEntry (container, id);
} // typedefEntry
public UnionEntry unionEntry ()
{
return new UnionEntry ();
} // unionEntry
public UnionEntry unionEntry (SymtabEntry container, IDLID id)
{
return new UnionEntry (container, id);
} // unionEntry
} // interface DefaultSymtabFactory

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for enumerated types.
**/
public class EnumEntry extends SymtabEntry
{
protected EnumEntry ()
{
super ();
} // ctor
protected EnumEntry (EnumEntry that)
{
super (that);
_elements = (Vector)that._elements.clone ();
} // ctor
protected EnumEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
public Object clone ()
{
return new EnumEntry (this);
} // clone
/** Invoke the enumerator generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
enumGen.generate (symbolTable, this, stream);
} // generate
/** Access the enumerator generator.
@returns an object which implements the EnumGen interface.
@see EnumGen */
public Generator generator ()
{
return enumGen;
} // generator
/** Add an element to the list of elements. */
public void addElement (String element)
{
_elements.addElement (element);
} // addElement
/** Each element of the vector is a String. */
public Vector elements ()
{
return _elements;
} // elements
static EnumGen enumGen;
private Vector _elements = new Vector ();
} // class EnumEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface EnumGen extends Generator
{
void generate (Hashtable symbolTable, EnumEntry entry, PrintWriter stream);
} // interface EnumGen

View File

@@ -0,0 +1,91 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for exceptions. An exception is simply
* a struct by a different name.
**/
public class ExceptionEntry extends StructEntry
{
protected ExceptionEntry ()
{
super ();
} // ctor
protected ExceptionEntry (ExceptionEntry that)
{
super (that);
} // ctor
protected ExceptionEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
} // ctor
public Object clone ()
{
return new ExceptionEntry (this);
} // clone
/** Invoke the exception generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
exceptionGen.generate (symbolTable, this, stream);
} // generate
/** Access the exception generator.
@returns an object which implements the ExceptionGen interface.
@see ExceptionGen */
public Generator generator ()
{
return exceptionGen;
} // generator
static ExceptionGen exceptionGen;
} // class ExceptionEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface ExceptionGen extends Generator
{
void generate (Hashtable symbolTable, ExceptionEntry entry, PrintWriter stream);
} // interface ExceptionGen

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
/**
* If the framework is being extended, this class must be extended.
* At very least, the genFactory method must be overridden to return
* the code generator extensions. The remaining methods may be overridden
* if necessary:
* <dl>
* <dt>symtabFactory
* <dd>If you wish to extend the symbol table entries, this method must return the factory which constructs those extensions. If you only want to extend a few of the symbol table entries, it may be useful to extend com.sun.tools.corba.se.idl.DefaultSymtabFactory and only override the pertinent methods.
* <dt>exprFactory
* <dd>If you wish to extend the expression classes, this method must return the factory which constructs those extensions. If you only want to extend a few of the expression classes, it may be useful to extend com.sun.tools.corba.se.idl.constExpr.DefaultSymtabFactory and only override the pertinent methods.
* <dt>arguments
* <dd>If you wish to add additional arguments to the base set of arguments, extend com.sun.tools.corba.se.idl.Arguments and override this method to return that class.
* <dt>languageKeywords
* <dd>If the language you are generating code in has keywords other than IDL keywords, these keywords should be returned by this method. The framework will prepend any IDL identifiers it encounters which are in this list with an underscore (`_') to avoid compilation errors. For instance, `catch' is a Java keyword. If the generators are emitting Java code for the following IDL, emitting `catch' as is will cause compile errors, so it is changed to `_catch':
* <br>
* IDL:
* <br>
* const long catch = 22;
* <br>
* Possible generated code:
* <br>
* public static final int _catch = 22;
* </dl>
**/
public class Factories
{
/** Return the implementation of the GenFactory interface. If this
returns null, then the compiler cannot generate anything. */
public GenFactory genFactory ()
{
return null;
} // genFactory
/** Return the implementation of the SymtabFactory interface. If this
returns null, the default symbol table entries will be used. */
public SymtabFactory symtabFactory ()
{
return new DefaultSymtabFactory ();
} // symtabFactory
/** Return the implementation of the ExprFactory interface. If this
returns null, the default expressions will be used. */
public com.sun.tools.corba.se.idl.constExpr.ExprFactory exprFactory ()
{
return new com.sun.tools.corba.se.idl.constExpr.DefaultExprFactory ();
} // exprFactory
/** Return a subclass of the Arguments class. If this returns null,
the default will be used. */
public Arguments arguments ()
{
return new Arguments ();
} // arguments
/** Return the list of keywords in the generated language.
Note that these keywords may contain the following wildcards:
<dl>
<dt>`*'
<dd>matches zero or more characters
<dt>`+'
<dd>matches one or more characters
<dt>`.'
<dd>matches any single character
</dl> */
public String[] languageKeywords ()
{
return null;
} // languageKeywords
} // interface Factories

View File

@@ -0,0 +1,142 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for forward declarations of interfaces.
**/
public class ForwardEntry extends SymtabEntry implements InterfaceType
{
protected ForwardEntry ()
{
super ();
} // ctor
protected ForwardEntry (ForwardEntry that)
{
super (that);
} // ctor
protected ForwardEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
public Object clone ()
{
return new ForwardEntry (this);
} // clone
/** Invoke the forward declaration generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
forwardGen.generate (symbolTable, this, stream);
} // generate
/** Access the interface generator.
@returns an object which implements the InterfaceGen interface.
@see InterfaceGen */
public Generator generator ()
{
return forwardGen;
} // generator
static boolean replaceForwardDecl (InterfaceEntry interfaceEntry)
{
boolean result = true;
try
{
ForwardEntry forwardEntry =
(ForwardEntry)Parser.symbolTable.get (interfaceEntry.fullName ());
if ( forwardEntry != null )
{
result = (interfaceEntry.getInterfaceType () ==
forwardEntry.getInterfaceType ());
forwardEntry.type (interfaceEntry);
// If this interface has been forward declared, there are probably
// other interfaces which derive from a ForwardEntry. Replace
// those ForwardEntry's with this InterfaceEntry:
interfaceEntry.forwardedDerivers = forwardEntry.derivers;
for ( Enumeration derivers = forwardEntry.derivers.elements();
derivers.hasMoreElements(); )
((InterfaceEntry)derivers.nextElement ()).replaceForwardDecl (forwardEntry, interfaceEntry);
// Replace the entry's whose types are forward declarations:
for ( Enumeration types = forwardEntry.types.elements ();
types.hasMoreElements (); )
((SymtabEntry)types.nextElement ()).type (interfaceEntry);
}
}
catch (Exception exception)
{}
return result;
} // replaceForwardDecl
///////////////
// Implement interface InterfaceType
public int getInterfaceType ()
{
return _type;
}
public void setInterfaceType (int type)
{
_type = type;
}
static ForwardGen forwardGen;
Vector derivers = new Vector (); // Vector of InterfaceEntry's.
Vector types = new Vector (); // Vector of the entry's whose type is a forward declaration.
private int _type = InterfaceType.NORMAL; // interface type
} // class ForwardEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface ForwardGen extends Generator
{
void generate (Hashtable symbolTable, ForwardEntry entry, PrintWriter stream);
} // interface ForwardGen

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for forward declarations of values.
**/
public class ForwardValueEntry extends ForwardEntry
{
protected ForwardValueEntry ()
{
super ();
} // ctor
protected ForwardValueEntry (ForwardValueEntry that)
{
super (that);
} // ctor
protected ForwardValueEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
} // ctor
public Object clone ()
{
return new ForwardValueEntry (this);
} // clone
/** Invoke the forward value declaration generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
forwardValueGen.generate (symbolTable, this, stream);
} // generate
/** Access the interface generator.
@returns an object which implements the ForwardValueGen interface.
@see ValueGen */
public Generator generator ()
{
return forwardValueGen;
} // generator
static ForwardValueGen forwardValueGen;
} // class ForwardValueEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface ForwardValueGen extends Generator
{
void generate (Hashtable symbolTable, ForwardValueEntry entry, PrintWriter stream);
} // interface ForwardValueGen

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
/**
* To extend this compiler framework to generate something other than
* the default, this factory interface must be implemented and the name
* of it must be set in the main method (see idl.Compile).
* <p>
* The implementation of each method should be quite simple. Take
* createAttributeGen, for instance. If the interface AttributeGen is
* implemented by a class called MyAttributeGen, then createAttributeGen
* will be the following:
* <pre>
* public AttributeGen createAttributeGen ()
* {
* return new MyAttributeGen ();
* }
* </pre>
* <p>
* If it is desired that a generator do nothing, it is not necessary to
* implement one which does nothing; you may simply write that particular
* create method so that it returns null.
* <p>
* Note that this class MUST have a public default constructor (one which
* takes no parameters).
**/
public interface GenFactory
{
public AttributeGen createAttributeGen ();
public ConstGen createConstGen ();
public EnumGen createEnumGen ();
public ExceptionGen createExceptionGen ();
public ForwardGen createForwardGen ();
public ForwardValueGen createForwardValueGen ();
public IncludeGen createIncludeGen ();
public InterfaceGen createInterfaceGen ();
public ValueGen createValueGen ();
public ValueBoxGen createValueBoxGen ();
public MethodGen createMethodGen ();
public ModuleGen createModuleGen ();
public NativeGen createNativeGen ();
public ParameterGen createParameterGen ();
public PragmaGen createPragmaGen ();
public PrimitiveGen createPrimitiveGen ();
public SequenceGen createSequenceGen ();
public StringGen createStringGen ();
public StructGen createStructGen ();
public TypedefGen createTypedefGen ();
public UnionGen createUnionGen ();
} // interface GenFactory

View File

@@ -0,0 +1,97 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class GenFileStream extends PrintWriter
{
public GenFileStream (String filename)
{
// What I really want to do here is:
// super (byteStream = new ByteArrayOutputStream ());
// but that isn't legal. The super constructor MUST
// be called before any instance variables are used.
// This implementation gets around that problem.
// <f49747.1>
//super (tmpByteStream = new ByteArrayOutputStream ());
//byteStream = tmpByteStream;
super (tmpCharArrayWriter = new CharArrayWriter());
charArrayWriter = tmpCharArrayWriter;
name = filename;
} // ctor
public void close ()
{
File file = new File (name);
try
{
if (checkError ())
throw new IOException ();
// <f49747.1>
//FileOutputStream fileStream = new FileOutputStream (file);
//fileStream.write (byteStream.toByteArray ());
//fileStream.close ();
FileWriter fileWriter = new FileWriter (file);
fileWriter.write (charArrayWriter.toCharArray ());
fileWriter.close ();
}
catch (IOException e)
{
String[] parameters = {name, e.toString ()};
System.err.println (Util.getMessage ("GenFileStream.1", parameters));
}
super.close ();
} // close
public String name ()
{
return name;
} // name
// <f49747.1>
//private ByteArrayOutputStream byteStream;
//private static ByteArrayOutputStream tmpByteStream;
private CharArrayWriter charArrayWriter;
private static CharArrayWriter tmpCharArrayWriter;
private String name;
} // GenFileStream

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
public interface Generator
{
} // interface Generator

View File

@@ -0,0 +1,134 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
public class IDLID extends RepositoryID
{
public IDLID ()
{
_prefix = "";
_name = "";
_version = "1.0";
} // ctor
public IDLID (String prefix, String name, String version)
{
_prefix = prefix;
_name = name;
_version = version;
} // ctor
public String ID ()
{
if (_prefix.equals (""))
return "IDL:" + _name + ':' + _version;
else
return "IDL:" + _prefix + '/' + _name + ':' + _version;
} // ID
public String prefix ()
{
return _prefix;
} // prefix
void prefix (String prefix)
{
if (prefix == null)
_prefix = "";
else
_prefix = prefix;
} // prefix
public String name ()
{
return _name;
} // name
void name (String name)
{
if (name == null)
_name = "";
else
_name = name;
} // name
public String version ()
{
return _version;
} // version
void version (String version)
{
if (version == null)
_version = "";
else
_version = version;
} // version
void appendToName (String name)
{
if (name != null)
if (_name.equals (""))
_name = name;
else
_name = _name + '/' + name;
} // appendToName
void replaceName (String name)
{
if (name == null)
_name = "";
else
{
int index = _name.lastIndexOf ('/');
if (index < 0)
_name = name;
else
_name = _name.substring (0, index + 1) + name;
}
} // replaceName
public Object clone ()
{
return new IDLID (_prefix, _name, _version);
} // clone
private String _prefix;
private String _name;
private String _version;
} // class IDLID

View File

@@ -0,0 +1,125 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for the #include statement.
**/
public class IncludeEntry extends SymtabEntry
{
protected IncludeEntry ()
{
super ();
repositoryID (Util.emptyID);
} // ctor
protected IncludeEntry (SymtabEntry that)
{
super (that, new IDLID ());
module (that.name ());
name ("");
} // ctor
protected IncludeEntry (IncludeEntry that)
{
super (that);
} // ctor
public Object clone ()
{
return new IncludeEntry (this);
} // clone
/** Invoke the Include type generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
includeGen.generate (symbolTable, this, stream);
} // generate
/** Access the Include type generator.
@returns an object which implements the IncludeGen interface.
@see IncludeGen */
public Generator generator ()
{
return includeGen;
} // generator
//d44810
/** Set the fully-qualified file specification of this include file. */
public void absFilename (String afn)
{
_absFilename = afn;
}
//d44810
/** Access the fully-qualified file specification of this include.
@returns a string containing the path of the include file. */
public String absFilename ()
{
return _absFilename;
}
/** Add an IncludeEntry to the list of files which this included
file includes. */
public void addInclude (IncludeEntry entry)
{
includeList.addElement (entry);
} // addInclude
/** Get the list of files which this file includes. */
public Vector includes ()
{
return includeList;
} // includes
static IncludeGen includeGen;
/** List of files this file includes */
private Vector includeList = new Vector ();
//d44810
/** Absolute file name for .u file generation. */
private String _absFilename = null;
} // class IncludeEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface IncludeGen extends Generator
{
void generate (Hashtable symbolTable, IncludeEntry entry, PrintWriter stream);
} // interface IncludeGen

View File

@@ -0,0 +1,355 @@
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for interfaces.
**/
public class InterfaceEntry extends SymtabEntry implements InterfaceType
{
protected InterfaceEntry ()
{
super ();
} // ctor
protected InterfaceEntry (InterfaceEntry that)
{
super (that);
_derivedFromNames = (Vector)that._derivedFromNames.clone ();
_derivedFrom = (Vector)that._derivedFrom.clone ();
_methods = (Vector)that._methods.clone ();
_allMethods = (Vector)that._allMethods.clone ();
forwardedDerivers = (Vector)that.forwardedDerivers.clone ();
_contained = (Vector)that._contained.clone ();
_interfaceType = that._interfaceType;
} // ctor
protected InterfaceEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
public boolean isAbstract()
{
return _interfaceType == ABSTRACT ;
}
public boolean isLocal()
{
return _interfaceType == LOCAL ;
}
public boolean isLocalServant()
{
return _interfaceType == LOCALSERVANT ;
}
public boolean isLocalSignature()
{
return _interfaceType == LOCAL_SIGNATURE_ONLY ;
}
public Object clone ()
{
return new InterfaceEntry (this);
} // clone
/** Invoke the interface generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
interfaceGen.generate (symbolTable, this, stream);
} // generate
/** Access the interface generator.
@returns an object which implements the InterfaceGen interface.
@see InterfaceGen */
public Generator generator ()
{
return interfaceGen;
} // generator
/** Add an InterfaceEntry to the list of interfaces which this interface
is derivedFrom. During parsing, the parameter to this method COULD
be a ForwardEntry, but when parsing is complete, calling derivedFrom
will return a vector which only contains InterfaceEntry's. */
public void addDerivedFrom (SymtabEntry derivedFrom)
{
_derivedFrom.addElement (derivedFrom);
} // addDerivedFrom
/** This method returns a vector of InterfaceEntry's. */
public Vector derivedFrom ()
{
return _derivedFrom;
} // derivedFrom
/** Add to the list of derivedFrom names. */
public void addDerivedFromName (String name)
{
_derivedFromNames.addElement (name);
} // addDerivedFromName
/** This method returns a vector of Strings, each of which is a fully
qualified name of an interface. This vector corresponds to the
derivedFrom vector. The first element of this vector is the name
of the first element of the derivedFrom vector, etc. */
public Vector derivedFromNames ()
{
return _derivedFromNames;
} // derivedFromNames
/** Add a method/attribute to the list of methods. */
public void addMethod (MethodEntry method)
{
_methods.addElement (method);
} // addMethod
/** This is a vector of MethodEntry's. These are the methods and
attributes contained within this Interface. */
public Vector methods ()
{
return _methods;
} // methods
/** Add a symbol table entry to this interface's contained vector. */
public void addContained (SymtabEntry entry)
{
_contained.addElement (entry);
} // addContained
/** This is a vector of SymtabEntry's. Valid entries in this vector are:
AttributeEntry, ConstEntry, EnumEntry, ExceptionEntry, MethodEntry,
StructEntry, NativeEntry, TypedefEntry, UnionEntry.
Note that the methods vector is a subset of this vector. */
public Vector contained ()
{
return _contained;
} // contained
void methodsAddElement (MethodEntry method, Scanner scanner)
{
if (verifyMethod (method, scanner, false))
{
addMethod (method);
_allMethods.addElement (method);
// Add this method to the 'allMethods' list of any interfaces
// which may have inherited this one when it was a forward
// reference.
addToForwardedAllMethods (method, scanner);
}
} // methodsAddElement
void addToForwardedAllMethods (MethodEntry method, Scanner scanner)
{
Enumeration e = forwardedDerivers.elements ();
while (e.hasMoreElements ())
{
InterfaceEntry derived = (InterfaceEntry)e.nextElement ();
if (derived.verifyMethod (method, scanner, true))
derived._allMethods.addElement (method);
}
} // addToForwardedAllMethods
// Make sure a method by this name doesn't exist in this class or
// in this class's parents
private boolean verifyMethod (MethodEntry method, Scanner scanner, boolean clash)
{
boolean unique = true;
String lcName = method.name ().toLowerCase ();
Enumeration e = _allMethods.elements ();
while (e.hasMoreElements ())
{
MethodEntry emethod = (MethodEntry)e.nextElement ();
// Make sure the method doesn't exist either in its
// original name or in all lower case. In IDL, identifiers
// which differ only in case are collisions.
String lceName = emethod.name ().toLowerCase ();
if (method != emethod && lcName.equals (lceName))
{
if (clash)
ParseException.methodClash (scanner, fullName (), method.name ());
else
ParseException.alreadyDeclared (scanner, method.name ());
unique = false;
break;
}
}
return unique;
} // verifyMethod
void derivedFromAddElement (SymtabEntry e, Scanner scanner)
{
addDerivedFrom (e);
addDerivedFromName (e.fullName ());
addParentType( e, scanner );
} // derivedFromAddElement
void addParentType (SymtabEntry e, Scanner scanner)
{
if (e instanceof ForwardEntry)
addToDerivers ((ForwardEntry)e);
else
{ // e instanceof InterfaceEntry
InterfaceEntry derivedFrom = (InterfaceEntry)e;
// Compare all of the parent's methods to the methods on this
// interface, looking for name clashes:
for ( Enumeration enumeration = derivedFrom._allMethods.elements ();
enumeration.hasMoreElements (); )
{
MethodEntry method = (MethodEntry)enumeration.nextElement ();
if ( verifyMethod (method, scanner, true))
_allMethods.addElement (method);
// Add this method to the 'allMethods' list of any interfaces
// which may have inherited this one when it was a forward
// reference:
addToForwardedAllMethods (method, scanner);
}
// If any of the parent's parents are forward entries, make
// sure this interface gets added to their derivers list so
// that when the forward entry is defined, the 'allMethods'
// list of this interface can be updated.
lookForForwardEntrys (scanner, derivedFrom);
}
} // addParentType
private void lookForForwardEntrys (Scanner scanner, InterfaceEntry entry)
{
Enumeration parents = entry.derivedFrom ().elements ();
while (parents.hasMoreElements ())
{
SymtabEntry parent = (SymtabEntry)parents.nextElement ();
if (parent instanceof ForwardEntry)
addToDerivers ((ForwardEntry)parent);
else if (parent == entry)
ParseException.selfInherit (scanner, entry.fullName ());
else // it must be an InterfaceEntry
lookForForwardEntrys (scanner, (InterfaceEntry)parent);
}
} // lookForForwardEntrys
public boolean replaceForwardDecl (ForwardEntry oldEntry, InterfaceEntry newEntry)
{
int index = _derivedFrom.indexOf( oldEntry );
if ( index >= 0 )
_derivedFrom.setElementAt( newEntry, index );
return (index >= 0);
} // replaceForwardDecl
private void addToDerivers (ForwardEntry forward)
{
// Add this interface to the derivers list on the forward entry
// so that when the forward entry is defined, the 'allMethods'
// list of this interface can be updated.
forward.derivers.addElement (this);
Enumeration e = forwardedDerivers.elements ();
while (e.hasMoreElements ())
forward.derivers.addElement ((InterfaceEntry)e.nextElement ());
} // addToDerivers
/** This method returns a vector of the elements in the state block.
If it is null, this is not a stateful interface. If it is non-null,
but of zero length, then it is still stateful; it has no state
entries itself, but it has an ancestor which does. */
public Vector state ()
{
return _state;
} // state
public void initState ()
{
_state = new Vector ();
} // initState
public void addStateElement (InterfaceState state, Scanner scanner)
{
if (_state == null)
_state = new Vector ();
String name = state.entry.name ();
for (Enumeration e = _state.elements (); e.hasMoreElements ();)
if (name.equals (((InterfaceState) e.nextElement ()).entry.name ()))
ParseException.duplicateState (scanner, name);
_state.addElement (state);
} // state
public int getInterfaceType ()
{
return _interfaceType;
}
public void setInterfaceType (int type)
{
_interfaceType = type;
}
/** Get the allMethods vector. */
public Vector allMethods ()
{
return _allMethods;
}
private Vector _derivedFromNames = new Vector();
private Vector _derivedFrom = new Vector();
private Vector _methods = new Vector();
Vector _allMethods = new Vector();
Vector forwardedDerivers = new Vector();
private Vector _contained = new Vector();
private Vector _state = null;
private int _interfaceType = NORMAL;
static InterfaceGen interfaceGen;
} // class InterfaceEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface InterfaceGen extends Generator
{
void generate (Hashtable symbolTable, InterfaceEntry entry, PrintWriter stream);
} // interface InterfaceGen

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
/**
* This class is only used within an InterfaceEntry. If the interface
* is stateful, then its state vector will contain one or more of these
* InterfaceStates.
**/
public class InterfaceState
{
public static final int Private = 0,
Protected = 1,
Public = 2;
public InterfaceState (int m, TypedefEntry e)
{
modifier = m;
entry = e;
if (modifier < Private || modifier > Public)
modifier = Public;
} // ctor
public int modifier = Public;
public TypedefEntry entry = null;
} // class InterfaceState

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface InterfaceType
{
public static final int NORMAL = 0 ;
public static final int ABSTRACT = 1 ;
// LOCAL generates code according to the Local interfaces
// Here helper and holder classes are the only ones generated
public static final int LOCAL = 2 ;
// intermediate solution to enable people to extend ServantLocatorPOA
// and ServantActivatorPOA for interoperability. This is until the
// POA is declared Local officially by OMG
public static final int LOCALSERVANT = 3 ;
// generate only signature interfaces, no helper/holders are generated
public static final int LOCAL_SIGNATURE_ONLY = 4 ;
public int getInterfaceType ();
public void setInterfaceType( int type ) ;
} // interface InterfaceType

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
/**
* An invalid argument for the compiler has been encountered.
**/
public class InvalidArgument extends Exception
{
/** @param arg the invalid argument. */
public InvalidArgument (String arg)
{
message = Util.getMessage ("InvalidArgument.1", arg) + "\n\n" + Util.getMessage ("usage");
} // ctor
public InvalidArgument ()
{
message = Util.getMessage ("InvalidArgument.2") + "\n\n" + Util.getMessage ("usage");
} // ctor
public String getMessage ()
{
return message;
} // getMessage
private String message = null;
} // class InvalidArgument

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
// -D62023<daz> Cast char to byte for JDK 1.2 compatability.
import java.io.IOException;
public class InvalidCharacter extends IOException
{
public InvalidCharacter (String filename, String line, int lineNumber, int pos, char ch)
{
String pointer = "^";
if (pos > 1)
{
byte[] bytes = new byte [pos - 1];
for (int i = 0; i < pos - 1; ++i)
bytes[i] = (byte)' '; // <d62023>
pointer = new String (bytes) + pointer;
}
String[] parameters = {filename, Integer.toString (lineNumber), "" + ch, Integer.toString ((int)ch), line, pointer};
message = Util.getMessage ("InvalidCharacter.1", parameters);
}
public String getMessage ()
{
return message;
} // getMessage
private String message = null;
} // class InvalidCharacter

View File

@@ -0,0 +1,197 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
// - What does oneway mean?
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for methods.
**/
public class MethodEntry extends SymtabEntry
{
protected MethodEntry ()
{
super ();
} // ctor
protected MethodEntry (MethodEntry that)
{
super (that);
_exceptionNames = (Vector)that._exceptionNames.clone ();
_exceptions = (Vector)that._exceptions.clone ();
_contexts = (Vector)that._contexts.clone ();
_parameters = (Vector)that._parameters.clone ();
_oneway = that._oneway;
} // ctor
protected MethodEntry (InterfaceEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
public Object clone ()
{
return new MethodEntry (this);
} // clone
/** Invoke the method generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
methodGen.generate (symbolTable, this, stream);
} // generate
/** Access the method generator.
@returns an object which implements the MethodGen interface.
@see MethodGen */
public Generator generator ()
{
return methodGen;
} // generator
public void type (SymtabEntry newType)
{
super.type (newType);
if (newType == null)
typeName ("void");
} // type
/** Add an exception to the exception list. */
public void addException (ExceptionEntry exception)
{
_exceptions.addElement (exception);
} // addException
/** This a a vector of the exceptions which this method raises. */
public Vector exceptions ()
{
return _exceptions;
} // exceptions
/** Add an exception name to the list of exception names. */
public void addExceptionName (String name)
{
_exceptionNames.addElement (name);
} // addExceptionName
/** This is a vector of strings, each of which is the full name of an
exception which this method throws. This vector corresponds to the
exceptions vector. The first element of this vector is the name
of the first element of the exceptions vector, etc. */
public Vector exceptionNames ()
{
return _exceptionNames;
} // exceptionNames
/* Add a context to the context list. */
public void addContext (String context)
{
_contexts.addElement (context);
} // addContext
/** This is a vector of strings, each of which is the name of a context. */
public Vector contexts ()
{
return _contexts;
} // contexts
/** Add a parameter to the parameter list. */
public void addParameter (ParameterEntry parameter)
{
_parameters.addElement (parameter);
} // addParameter
/** This is a vector of ParameterEntry's. They are the parameters on
this method and their order in the vector is the order they appear
on the method. */
public Vector parameters ()
{
return _parameters;
} // parameters
/** Is this a oneway method? */
public void oneway (boolean yes)
{
_oneway = yes;
} // oneway
/** Is this a oneway method? */
public boolean oneway ()
{
return _oneway;
} // oneway
/** Is this a value method? */
public void valueMethod (boolean yes)
{
_valueMethod = yes;
} // valueMethod
/** Is this a value method? */
public boolean valueMethod ()
{
return _valueMethod;
} // valueMethod
void exceptionsAddElement (ExceptionEntry e)
{
addException (e);
addExceptionName (e.fullName ());
} // exceptionsAddElement
private Vector _exceptionNames = new Vector ();
private Vector _exceptions = new Vector ();
private Vector _contexts = new Vector ();
private Vector _parameters = new Vector ();
private boolean _oneway = false;
private boolean _valueMethod = false;
static MethodGen methodGen;
} // class MethodEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface MethodGen extends Generator
{
void generate (Hashtable symbolTable, MethodEntry entry, PrintWriter stream);
} // interface MethodGen

View File

@@ -0,0 +1,113 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Vector;
/**
* This is the symbol table entry for modules.
**/
public class ModuleEntry extends SymtabEntry
{
protected ModuleEntry ()
{
super ();
} // ctor
protected ModuleEntry (ModuleEntry that)
{
super (that);
_contained = (Vector)that._contained.clone ();
} // ctor
protected ModuleEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
public Object clone ()
{
return new ModuleEntry (this);
} // clone
/** Invoke the module generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
moduleGen.generate (symbolTable, this, stream);
} // generate
/** Access the module generator.
@returns an object which implements the ModuleGen interface.
@see ModuleGen */
public Generator generator ()
{
return moduleGen;
} // generator
/** alid entries in this vector are: TypedefEntry, ExceptionEntry,
StructEntry, UnionEntry, EnumEntry, ConstEntry, InterfaceEntry,
ModuleEntry. */
public void addContained (SymtabEntry entry)
{
_contained.addElement (entry);
} // addContained
/** This is a vector of SymtabEntry's. Valid entries in this vector are:
TypedefEntry, ExceptionEntry, StructEntry, UnionEntry, EnumEntry,
ConstEntry, InterfaceEntry, ModuleEntry. */
public Vector contained ()
{
return _contained;
} // contained
private Vector _contained = new Vector ();
static ModuleGen moduleGen;
} // class ModuleEntry

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
import com.sun.tools.corba.se.idl.*;
public interface ModuleGen extends Generator
{
void generate (Hashtable symbolTable, ModuleEntry entry, PrintWriter stream);
} // interface ModuleGen

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
/**
* This is the symbol table entry for constants.
**/
public class NativeEntry extends SymtabEntry
{
protected NativeEntry ()
{
super ();
repositoryID (Util.emptyID);
} // ctor
protected NativeEntry (SymtabEntry that, IDLID clone)
{
super (that, clone);
if (module ().equals (""))
module (name ());
else if (!name ().equals (""))
module (module () + "/" + name ());
} // ctor
protected NativeEntry (NativeEntry that)
{
super (that);
} // ctor
/** This is a shallow copy clone. */
public Object clone ()
{
return new NativeEntry (this);
} // clone
/** Invoke the constant generator.
@param symbolTable the symbol table is a hash table whose key is
a fully qualified type name and whose value is a SymtabEntry or
a subclass of SymtabEntry.
@param stream the stream to which the generator should sent its output.
@see SymtabEntry */
public void generate (Hashtable symbolTable, PrintWriter stream)
{
nativeGen.generate(symbolTable, this, stream);
} // generate
/** Access the constant generator.
@returns an object which implements the ConstGen interface.
@see ConstGen */
public Generator generator ()
{
return nativeGen;
} // generator
static NativeGen nativeGen;
} // class NativeEntry

View File

@@ -0,0 +1,36 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.corba.se.idl;
// NOTES:
import java.io.PrintWriter;
import java.util.Hashtable;
public interface NativeGen extends Generator
{
void generate (Hashtable symbolTable, NativeEntry entry, PrintWriter stream);
} // interface NativeGen

Some files were not shown because too many files have changed in this diff Show More