%% -*- mode: LaTeX -*-
%%
%% Copyright (c) 2002 University of Utah and the Flux Group.
%% All rights reserved.
%% This file is part of the JanosVM documentation.
%% 
%% Permission to use, copy, modify, distribute, and sell this
%% documentation for any purpose is hereby granted without fee,
%% provided that the above copyright notice(s) appear in all copies.
%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter{Java OS Substrate}
\label{cha:Java OS Substrate}

This chapter will concentrate on the interfaces and mechanisms for creating a
Java Operating System on the \JanosVM{}.  Because a great deal of
infrastructure has already been implemented, the task of creating a Java \OS{}
boils down to using these tools in a middle-ware library that consists of the
following:

\begin{itemize}
  \item The server code which manages any shared resources and/or data.
  Typically, these classes would run in one or more isolated contexts in order
  to compartmentalize the data and provide fault tolerance.

  \item The user visible classes which provide a safe path, through language
  based protection, for untrusted code to access the shared data.
\end{itemize}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Teams}
\label{sec:Teams}

The method for isolating computations and tracking their resource usage is the
Team, as in, ``team'' of threads.  Isolation is primarily provided by the semantics of the Java language,
therefore, the \JanosVM{} doesn't need to rely on any underlying \OS{} or
hardware support.  However, the vast amount of infrastructure needed to execute
Java code is shared and needs to be protected or duplicated for each
computation.  For example, at the \JVM{} level:

\begin{itemize}
  \item Garbage collectors are created for each team to separate the amount of
	time they spend marking and sweeping objects.

  \item The class path can be specified per-team in order to allow fine grained
	control.

  \item A separate class name space is created for each team, eliminating some
	intermingling of internal data structures and allowing name remapping.
% XXX what is a root name space?  Its not the filesystem or the classpath...
\end{itemize}

In addition, there are quite a few Java objects and classes that need to be
shared, these are held by the ``kernel'' team which is created by the system
upon initialization.

Creating a team is done using the \javaid{create} static method of the
\javaid{edu.utah.janosvm.sys.Team} class:

\begin{javacode}
TeamHandle th = Team.create();

th = Team.create(``Important Server Team'');

th = Team.find(``Important Server Team'');
\end{javacode}

The first line creates a team with the default amount of memory, class path,
and other resources, while the second does the same as well as giving it a name
which can be searched for using the \javaid{find} method.  Once the resources
for the new team have been allocated and initialized, the system will return a
\javaid{TeamHandle} object that gives limited access to the team.  
Notice that the system will not
start up any threads or run any user code, the next section will introduce some
methods for bootstrapping the new team.  The \javaid{create} method can also
take an array of resource specifications that override the defaults, these will
be discussed later in section~\ref{sec:Resources}.

Failure to create a team can occur if the current team is already terminated or
there was a failure to allocate a resource.  In the case of resource failure
the \javaid{create} method will throw a \javaid{ResourceSpecException} with a
reference to the specification that couldn't be satisfied, unless the default
was used, in which case there is no indication of what failed.  In the future
this should change to more accurately reflect the failure.

Besides the \javaid{TeamHandle} object, there is also a \javaid{Team} object
which only exists local to the team.  It is a subclass of \javaid{TeamHandle}
and possesses a few methods for manipulating state pertinent to the current
team.  The current \javaid{Team} object can be retrieved through the
\javaid{current} method in the \javaid{Team} class.

\begin{javacode}
Team curr = Team.current();
curr.setDescription(``Insert Descriptive Text Here'');
\end{javacode}

Unlike many other systems, there is no strict hierarchy maintained by the
system, every team is a peer of every other, including the kernel.  Therefore,
team's are not bound to the lifetime of their creator, nor do they inherit any
resource specifications.  Of course, there are methods for performing these
actions, however, the \JVM{} will not do them by default.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Visiting Teams}
\label{subsec:Visiting Teams}

%% XXX Add references here

A team will isolate untrusted user computation and resource usage from the rest
of the teams, however, system code requires a path for manipulating state in
foreign teams.  Therefore, the \JanosVM{} allows threads to visit other teams
if they need to perform some operation or communicate some data to the
destination team.  The migration of a thread is split into two stages
%
\begin{inparaenum}[(1)]
  \item reserving the current and destination team so they cannot be terminated
  and 
  \item switching the context of the current thread to the reserved team.
\end{inparaenum}
%
The first stage is used to protect any global structures that might be damaged
when the team's threads are stopped on termination.  For example, taking a
shared lock should be done within the context of a reservation since the \JVM{}
will not fix up the lock if the thread is terminated.  The second stage affects
any operations that reference data structures hanging off the current team, for
instance, creating threads and allocating memory.

Because the \JanosVM{} functions in a single address space, the end result of a
visit is the thread's ability to gain urestricted access to the resources of
all the team's involved.  The thread can then store references in its stack
that point to objects in visited teams, copy primitive data, and perform
restricted copies of references (\autoref{sec:Cross-Team Pointers}) without any
special mapping operations.  These relaxed conditions make it extremely easy to
write straightforward code for manipulating state and copying data, a desirable
alternative to a more heavyweight messaging system.

The actual act of reserving a team is a little involved because we have to
maintain the sanity of the internal team structures in the face of threads
jumping through stack frames.  For instance, Java code executing in the middle
of a reservation could throw an exception through the block that reserved the
team.  The current solution is to record each team reservation and context
switch on a secondary thread stack and then use these recordings to rollback
any changes.  Another solution might have been to mandate the use of a
\javaid{finally} clause in all code, however, the system would still need to
know when a visit had taken place so it could copy the exception to the
previous team.  In addition, the lack of automation in this approach places more
pressure on developer, leading to more places for coding errors.

Performing a visitation can be done in the above two stage form by using the
\javaid{pushReservation}/\javaid{pop} and
\javaid{visit}/\javaid{leave} methods.

\begin{javacode}
try
{
	TeamReservation tr = th.pushReservation();

	tr.visit();
	{
		/* Do something in the remote team context. */
	}
	tr.leave();

	/* Do something in the original team context. */

	tr.visit();
	{
		/* Do something in the remote team context. */
	}
	tr.leave();

	tr.pop();
}
catch(TeamEjectionException e)
{
	/*
	 * A ``catastrophe'' occurred in the remote team and our thread was
	 * forcefully thrown out.
	 */
}
catch(DeadTeamException e)
{
	/*
	 * Couldn't push a reservation since the current or remote team were 
	 * already dead...
	 */
}
\end{javacode}

The first line tries to push a reservation for the team referred to by the
\javaid{TeamHandle} object in the \javaid{th} variable.  If both teams are
still alive, the call will succeed and return a \javaid{TeamReservation} object
which can be used to visit the remote team.  However, if either team has been
terminated the method will throw a \javaid{DeadTeamException} which should be
dealt with appropriately.  It should be noted that the \javaid{TeamReservation}
object is not a dynamically allocated object, it is the actual object allocated
on the secondary stack.  So, the object must be popped off the secondary stack
with the \javaid{pop} method or automatically when an exception is thrown.
Next, we temporarily visit the other team two times to do some operations in
its context.  It is possible for the thread to panic or be
forcefully ejected during its visits so any \javaid{TeamEjectionException}s
will also need to be handled.  Currently, a thread is only ejected when the
\javaid{VMInstance.crash} method is called or if the \JVM{} is unable to
allocate memory for a stack back trace.

% XXX define the team context --- ``globals'' are accessed in the
%team's namespace; but classes are loaded in the ``owning'' team?!.  Anything else?
%Only data visible in both is data on the stack.  Object references
%on the stack can be used to create intra-process pointers.
% MUST BE CAREFUL WITH THOSE.  See cross-team pointers below.  See
% Name Space Resource below.

An alternative to the above visitation form is to use the all-in-one
\javaid{switchTo} and \javaid{returnFrom} methods which perform as their names
imply:

\begin{javacode}
try 
{
	th.switchTo();
	{
		/* Do something in the other team context. */
	}
	th.returnFrom();
}
catch(TeamEjectionException e)
{
	/*
	 * A ``catastrophe'' occurred in the remote team and our thread was
	 * forcefully thrown out.
	 */
}
catch(DeadTeamException e)
{
	/*
	 * Couldn't push a reservation since the current or remote team were 
	 * already dead...
	 */
}
\end{javacode}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Termination}
\label{subsec:Termination}

Termination of a team is done by calling the \javaid{terminate} method on the
team's \javaid{TeamHandle} object.  The actual process of termination involves
breaking any VM-maintained cross-team pointers, stopping the team's threads, and returning
its resources to the \JVM{}.  The first stage is responsible for maintaining
type safety because the terminated team's memory will soon be freed and the
garbage collectors in other teams need to be notified.  Next, the team is
``caged'' to stop any inside threads from leaving or any outside threads from
entering.  The purpose of the ``cage'' is to prevent the team from living in
perpetuity and to protect any shared data from being damaged when the threads
are stopped.  Once all the absent threads have returned to the terminated team
and the visitors have left, the threads are stopped.  This hard stop is
possible because any shared data is protected by team reservations and any
other data, damaged or not, is ignored during termination processing.  Finally,
the team's resources are returned to the \JVM{} for other teams to use.

The responsibility for doing the termination work falls partially on the
terminating thread, any other threads interacting with the team, and the
``Kernel Reaper'' thread.  First, the terminating thread is responsible for
breaking any Java level cross-team pointers and caging the team by marking it
as ``dying''.  Next, the first thread that notices there are no more
reservations for the team marks the team as ``dead'' and places it on a queue
managed by the ``Kernel Reaper'' thread.  Finally, the ``Kernel Reaper'' does
the work needed to break down the team's components and marks it as ``buried''.
%% Maybe it should be named the Kernel Bacteria thread?  Or 'kernel fungus'. 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Team Dependencies}
\label{subsec:Team Dependencies}

Teams in the \JanosVM{} are not totally independent entities, sometimes their
lifetimes need to be bounded by some other team in the system.  The need for
this restricted lifetime arises from the convenience of directly sharing
classes and other objects in the system.  For example, \javaid{static}
\javaid{final} values and static strings in classes, as well as several
internal data structures, can be directly referenced without using proxies or
team reservations.  In other words, without these strict lifetime guarantees a
team could have references to memory locations that were freed or reused.  In
addition, a Java \OS{} might have semantic requirements concerning the team's
spawned by a parent program.

Currently, dependencies are automatically generated by some resources or by
using the \javaid{addDependency} method on the \javaid{Team} object.  For
example:

\begin{javacode}
/*
 * Reserve the kernel so the Team.create() and Team.addDependency() calls are
 * atomic with respect to termination of either team.
 */
TeamReservation tr = kernel.pushReservation();
{
	Team parent = Team.current();
	TeamHandle th = Team.create();

	th.switchTo();
	{
		Team child = Team.current();

		/* Make the child depend on the parent team. */
		child.addDependency(parent);
	}
	th.returnFrom();
}
tr.pop();
\end{javacode}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Team Events}
\label{subsec:Team Events}

The creation, termination, and other important events in the lifetime of a team
are tracked by the kernel as well as broadcast to any listeners through a
\javaid{TeamList} object.  Adding a listener is done by creating a new
\javaid{TeamList}, adding a \javaid{TeamListHandler} event handler
implementation, and calling the \javaid{listen} method.  The kernel will then
call the \javaid{event} method on the \javaid{TeamListHandler} object whenever
one of the following events occurs:

\begin{optionlist}
  \item[CREATED]
  %
  A new team was created.

  \item[FINISHED]
  %
  All of the non-daemon threads in a team have exited.  Note, this is only sent
  if you've called the \javaid{notifyOnFinish} method on the \javaid{Team}
  object.

  \item[TERMINATED]
  %
  A team's \javaid{terminate} method has been called.

  \item[BURIED]
  %
  A team's resources have been returned to the system.
\end{optionlist}

The arguments to the \javaid{event} method are a \javaid{TeamReservation} for
the listener's team, since the handler is executing in the context of the
kernel team, and a \javaid{TeamEvent} object which describes the event and
which team it concerns.  Team identification is done using the unique integer
identifier given to each team upon creation.  This identifier is very similar
to a UNIX process identifier and is expected to be unused for some amount of
time after the death of the process.  Thus, a \javaid{TeamEvent} can properly
identify a buried team even though its objects no longer exist and the
\javaid{TeamHandle}s are invalid.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Cross-Team Pointers}
\label{sec:Cross-Team Pointers}

%% XXX This sucks
Sharing objects between teams is quite enticing considering the \JanosVM{} is a
single address space/language protected system, however, there are a number of
issues that need to be resolved.  For example, write barriers would be required
to notify garbage collectors that their objects were being referenced by other
teams.  The approach taken to solve these problems is to use a write barrier
with no side effects to deny most direct sharing between teams and a system of
object proxies for all other types of sharing.

%% Pat: Aren't there two types of inter-team sharing: unrestricted sharing
%% during a reservation, and kernel-maintained Importable/Exportable references.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Write Barrier}
\label{subsec:Write Barrier}

Unlike \KaffeOS{}, the write barrier used by the \JanosVM{} has no
side effects except to throw an
\javaid{edu.utah.janosvm.sys.SegmentationFaultError} when a thread
tries to write a reference from one team into another.  Unfortunately,
this is a bit draconian, so there are a number of exceptions:

\begin{itemize}
  \item Pointers from dependents into their parents, although the objects they
	refer to are expected to be part of the root set or have a lifetime
	greater than the dependents.

  \item Pointers in the proxy objects specified in the next section.  This
	allows the proxies to cache pointers without having to worry about
	triggering the write barrier.

  \item A number of exempt system classes.  For example, the \javaid{Thread}
	object is implemented to store the object it is waiting on in a field,
	so \javaid{Thread} uses the exempt class, \javaid{ThreadObjectHolder},
	to store the object.
\end{itemize}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Object Proxies}
\label{subsec:Object Proxies}

References between objects in peer teams cannot be allowed because one team
could tie up memory by artificially maintaining references to objects.
Alternatively, the \JanosVM{} offers system maintained object proxies in the
form of the \javaid{Exportable} and \javaid{Importable} base classes.  The
\javaid{Exportable} class serves as a base for objects that are exported to
other teams in the system.  Typically, a middeware library would provide
exports for protected objects in the system (i.e.,  files or sockets)
and middleware-specific shared data.
As you might have inferred, the \javaid{Importable} class is then used as a
base for classes that import the objects exported by other teams.  For example,
the \javaid{TeamHandle} class discussed earlier is an \javaid{Importable} that
refers to a \javaid{TeamBackEnd} object in the kernel.

Implementing imports and exports is a relatively simple process.  First, an
export can be created by extending the \javaid{Exportable} class and then using
an \javaid{ExportManager} to track the export and all of its importers.  The
\javaid{ExportManager} objects are created by the \javaid{PortAuthority} class
which can be accessed through the \javaid{Team} class.  For example, an object
can be exported under a given identifier by calling the \javaid{exportObject}
method on the current team's \javaid{Team} object.  It is also possible to
export the object under multiple identifiers resulting in multiple
\javaid{ExportManager}s.  Of course, an export doesn't always require a name so
the \javaid{exportAnonymousObject} method can be used to export the object and
obtain an \javaid{ExportManager}.  The export can then be revoked manually by
calling the \javaid{revokeObject} and \javaid{revokeAnonymousObject} methods in
the \javaid{Team} class.

Implementing an import is done by creating a class that extends the
\javaid{Importable} class and implements the \javaid{bindTo} and
\javaid{unbindFrom} methods.  These methods are used to control the direct
references held by the import to the export in the remote team.  In a typical
implementation the \javaid{Importable} subclass would contain a field of the
export's type which is initialized with the \javaid{Exportable} value passed
into \javaid{bindTo}.  The implementation for the \javaid{unbindFrom} method
would simply null this field to break the cross team reference.  The rest of
the class would then be made up of wrapper functions that may or may not visit
the team to execute the exports methods.  Actually importing an export is done
by calling the \javaid{importObject} method on the remote team's
\javaid{TeamHandle} with the export's identifier.  Or, executing the
\javaid{addImporter} method on the \javaid{ExportManager} while visiting the
remote team.  
% xxx:
Note that a badly-written Importable can violate the requirements of
its usage and cause the VM to crash.  Thus, only trusted code should
be allowed to use and create Importable and Exportable objects.

Currently, all methods on the \javaid{Importable} that access the
\javaid{Exportable} object must synchronize on the import object.  This
synchronize is needed to delay a terminating thread from revoking the reference
while it is still in use.  Unfortunately, this is a poor solution because
hostile code could hold the lock on the importable indefinitely as well as
requiring the developer to remember to use \javaid{synchronized} on all the
methods.  Alternatives are being investigated, however, a real solution has yet
to be decided upon.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsubsection{Naming Conventions}
\label{subsubsec:Naming Conventions}

We've adopted a specific naming convention when developing \javaid{Importable}
and \javaid{Exportable} classes and would like to see it used in outside
developments so as to avoid misunderstandings amongst users.  This convention
is to append \javaid{BackEnd} to all \javaid{Exportable} classes, for instance,
the \javaid{TeamBackEnd}.  Next, since there can be many types of
\javaid{Importable} classes importing the same \javaid{Exportable} class we
can't enumerate all forms, so we've chosen to mandate two forms, the primary
and secondary object handles.  The primary handle is simply given a regular
name (e.g. \javaid{MessagePort}) and can used to implicitly create an
\javaid{Exportable} upon instantiation.  The secondary handle has
\javaid{Handle} appended to its name and is used to grant restricted access to
the export.  For example, a team could use \javaid{new} \javaid{MessagePort} to
create a message port and its exportable.  The team could then create a
communication path by passing \javaid{MessagePortHandle} objects to other teams
in the system.  Since the \javaid{MessagePortHandle} is a restricted interface,
it only allows messages to be queued on the interface, while the
\javaid{MessagePort} can be used to enqueue and dequeue messages.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Resources}
\label{sec:Resources}

System primitives needed to execute and support a team are referred to as
resources.  These resources are specified at team creation, tracked and limited
on a per-team basis by the system, and automatically released upon termination.
Specifying the needs of a team is done through a resource specification, an
object or collection of objects that describes the team's requirements.  This
specification is then passed to the resource and used to construct a client
object that the team can use to access the resource.  For most resources the
client object is attached directly to the team and accessed by executing static
methods in the resource's class.

The classes described in this section can be found in the
\javaid{edu.utah.janosvm.resources} package in the \file{JanosVM.jar} file.
Describing all the resources required by the team is done by passing an array
of \javaid{ResourceSpec}s to the \javaid{Team.create}.  Constructing
\javaid{ResourceSpec}s can be done manually or by using the \javaid{current}
static method available in many of the classes to copy the current team's
specification.  As discussed before, if the system is able to satisfy the given
specs as well as any defaults needed to get the team going it will return a
\javaid{TeamHandle}.  Otherwise, it will throw a \javaid{ResourceSpecException}
possibly containing the unsatisfied spec.  For example, the following code will
try, and most likely fail, to allocate a gigabyte of memory.

\begin{javacode}
MemorySpec ms = null;

try
{
	Team.create(new ResourceSpec[] {
		ms = new MemorySpec(1024 * 1024 * 1024), // Gig of memory
	});
}
catch(ResourceSpecException e)
{
	if( e.getUnsatisfiedSpec() == ms )
		System.err.println(``Couldn't allocate a gig'');
	else
		System.err.println(``Some other resource was unsatisfied'');
}
\end{javacode}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Memory}
\label{subsec:Memory}

The memory requirements of a team are specified with a \javaid{MemorySpec}
object that describes the number of bytes required by the team and an optional
garbage collection policy.  The memory size is basically a guess that should be
refined through profiling, there is currently no prescribed method for picking
the number.  The optional garbage collection policy is the name of a subclass
of \javaid{GCPolicy} that is consulted when the collector needs to make a
decision.  Currently, the call-backs available to a policy are when, if ever,
to start the \GC{} and finalizer threads and when to trigger a collection.

Once the team has started it can access its memory client object through the
static methods in the \javaid{MemoryResource} class.  Currently, the class only
provides methods for getting simple statistics on current and peak memory
usage.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{CPU}
\label{subsec:CPU}

Unfortunately, the standard build of the \JanosVM{} only includes a simple
priority based scheduler that will not limit the \CPU{} usage of a team.
However, it is possible to take advantage of a proportional share scheduler in
the oskit/moab/\JanosVM{} configuration.  There are plans to include a
more advanced thread scheduler in future versions.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Name Space}
\label{subsec:Name Space}

The root class name space required by the Java language is serviced by the
NameSpace resource.  This resource tracks all classes loaded into a team and
any classes that are shared amongst the teams.  Basic interaction with the
resource is done through the usual Java interfaces like \javaid{Class.forName}
and class loaders.  Unfortunately, the actual loading of classes is very
sensitive to the context in which these methods are executed.  In the case of
\javaid{forName}, the class is loaded into the name space based on the caller's
class loader and owning team.  For example, if a class loaded into the root
name space of the kernel uses \javaid{forName} during a visit, the requested
class will be resolved in the context of the kernel.  Loading a class into the
current team irrespective of the caller's context can be done using the
\javaid{loadTeamClass} static method in \javaid{NameSpaceResource}.

In addition to satisfying the standard requirements of the Java language the
name space resource also manages any classes that are shared between teams.
The ability to share classes makes it possible to consolidate memory,
initialization, and information across all uses of the classes, but also
introduces a great deal of complexity.  Sharing in previous systems was usually
accomplished through some amount of class loader magic, however, \JanosVM{}'s
ultimate goal is to explore design alternatives so a new primitive called the
``class group'' was introduced.  A ``class group'' refers to a group of closely
related classes that can be used as an alternative to the standard class path
during loading.  Effectively, this allows one team to resolve names to classes
residing in another team.  This is accomplished by loading and resolving the
group's classes in a team and then exporting them to other teams.

Grouping classes together is done partly as an optimization to avoid tracking
every shared class and to reflect the property that few classes can exist in
isolation.  For example, the \javaid{Integer} class requires the
\javaid{String} class in order to generate a string version of an \javaid{int}.
Most class groups should be closed over the set of classes, in other words, any
types visible to untrusted code should be satisfied by other members of the
group.  Closure is not a requirement for sharing classes since multiple groups
may need to be combined to create a usable namespace, however, the combination
of groups must be the same as those used to resolve the classes in the
exporting team.  Additionally, types not exposed to the user are not required
to be in the group since they are always resolved in their original name space.
For example, \javaid{Importable}s can have a private field of their
\javaid{Exportable}s type without needing to include the \javaid{Exportable} in
the class group.  Defining the contents of a class group is done in the
configuration file that is passed to the \JVM{} on startup.  Each class group
is a subsection of the ``namespace-resource'' section and contains the list of
class names in the internal forward slash form
(e.g. \javaid{java/lang/String}).

The possibility of name clashes in this class sharing mechanism led to the
development of the ``view group'' and, in fact, is another reason for putting
classes into groups instead of managing them individually.  The main example of
name clashing has to do with \JanosVM{} not providing a JDK compatible Java
runtime, but still using the \javaid{java.lang} package.  The reasons for doing
this involve reducing the number of changes to the internals of Kaffe and the
standard Java tools.  Unfortunately, if a real java runtime was written for
\JanosVM{} then it would probably want its own version of the
\javaid{java.lang} classes instead of the \JanosVM{} specific ones.  Therefore,
class groups were designed to allow a team to view a set of classes through a
specific mapping.  Because the class group is usually a closed set, this is
mostly a matter of exchanging the names used in methods and class lookup to
refer to the alternatives.  Again, like a class group specification, the
mapping is specified in the config file as a subsection of the class group and
contains the list of class names paired with the mapped name.  By default,
every class group has an ``identity'' view group which, as you might expect,
makes the classes available under their builtin names.

The process of ``exporting'' a class group for other teams to use is done by
calling the \javaid{exportClassGroup} method in \javaid{NameSpaceResource}.
This method will load the classes into the current team and split them off of
the team's main group into the new class group.  The group can then be imported
during team creation by passing a \javaid{NameSpaceSpec} with an array of
\javaid{NameSpaceGroup}s specifying which view group of a class group to import
from a given team.  Because the imported classes are directly referenced, the
system will implicitly add a dependency on the exporting team.  Unfortunately,
you cannot dynamically import class groups from other teams or remove imported
groups.  These issues may be addressed in future versions by extending class
loaders to allow them to import class groups instead of limiting this to the
root class loader.

The following is an example of some config file entries for defining the
``MyServerClasses'' class group and the ``BarView'' view group.

%% XXX configcode?
\begin{javacode}
%begin namespace-resource
  %begin classgroup MyServerClasses
    edu/utah/myserver/Foo
    edu/utah/myserver/FooHandle

    %begin viewgroup BarView
      edu/utah/myserver/Foo Bar		     # Remap .../Foo -> Bar
      edu/utah/myserver/FooHandle BarHandle  # Remap .../FooHandle -> BarHandle
      %end

    %end
  %end
\end{javacode}

A server team can then export the classes using \javaid{exportClassGroup} and
then create a new team that imports them.

\begin{javacode}
NameSpaceResource.exportClassGroup(``MyServerClasses'');

nss = new NameSpaceSpec(new NameSpaceGroup[] {
	/* The kernel's class group and ``identity'' view. */
	new NameSpaceGroup(kernelTeam, ``kernel''),
	/* My server class group and ``BarView'' view group. */
	new NameSpaceGroup(Team.current(), ``MyServerClasses'', ``BarView''),
});
\end{javacode}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsubsection{Class Locals}
\label{subsubsec:Class Locals}

Unlike most other systems, the \JanosVM{} doesn't automatically create process
local static fields, instead a static always resolves to the same lvalue
regardless of the current team.  This approach is easier to implement and
allows classes to collect and reference global information, however, it
complicates some other aspects of the code.  In an attempt to alleviate these
problems the \JanosVM{} provides methods for storing \javaid{Object}s with a
class on a per-team basis.  This functionality is accessed through the
\javaid{getCurrentClassLocal} and \javaid{setCurrentClassLocal} methods in the
\javaid{Team} class.  The implementation simply stores an object in a team
local hash table that is keyed on the class reference.

% XXX: Thus middle-ware that wants to give each application it hosts
% the illusion of running in a vanilla JVM, must arrange things such
% that classes with visible static data are re-loaded in each
% application's Team.

Note, because the ``.class'' language form of getting a \javaid{Class} object
calls \javaid{Class.forName} it is advised that a static field be used to store
the class object reference.  Also, this interface is likely to change in favor
of something similar to \javaid{java.lang.ThreadLocal}.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Class Path}
\label{subsec:Class Path}

The class path resource allows the user to specify zero or more directories or
\JAR{} files that can be used as a source for class files.  The class path
given to the \JVM{} on startup determines the set available to any team and the
default given to a team on creation.  
% XXX doesn't default to parent's classpath value?
A more discriminating class path can be
given using a \javaid{ClassPathSpec} object with an array of strings
representing the desired elements of the path.  The \javaid{ClassPathResource}
class provides a number of static methods for querying the global class path if
the path strings are not given by the user.  Of course, its also possible to
specify an empty class path, in which case the classes must be available
through class groups imported into the team's root name space.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Standard I/O}
\label{subsec:Standard I/O}

The standard input and output streams available through
\javaid{System.in/out/err} are maintained as a sacrifice to compatibility and
ease of use .  By default, all teams share the \JVM{}'s standard I/O streams.
Specifying another set of streams can be done by creating a \javaid{StdioSpec}
with some \URI{} like strings.  The format is \javaid{<protocol>://<path>}
where the protocol and path values are as follows:

\begin{optionlist}
  \item[builtin]
  %
  The \JVM{}'s ``real'' stdio streams.  And the path is:
  \begin{optionlist}
    \item[none]
    %
    No stream.

    \item[stdin]
    %
    Standard input.

    \item[stdout]
    %
    Standard output.

    \item[stderr]
    %
    Standard error.
  \end{optionlist}

  \item[file]
  %
  A regular file and its path.

  \item[jsi]
  %
  The \JSI{} channel that was used to execute ``run of team x.''

  \item[fd]
  %
  A file descriptor in the \JVM, the fd given in the path is \cid{dup}'d and
  used to build a \cid{FILE} object.  This form is used by the
  \javaid{StdioSpec.currentFD} method which can be used for sharing streams
  with child teams.
\end{optionlist}

Again, for the sake of some amount of compatibility, these \javaid{public} and
\javaid{static} fields in \javaid{System} have been maintained even though it
results in the sharing of the same objects in all teams.  Because of this
sharing the input and output stream classes are written to indirect to the
current team's stream objects.  So, synchronizing on any of these stream
objects will block all other teams and, if not bracketed by a kernel
reservation, could result in memory corruption.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% End of file.

