Sie sind auf Seite 1von 18

JAVA

ASSIGNMENT 1

karandeep Singh ater

05813202717

CSE 1
Java – Overview

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread
popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write
Once, Run Anywhere.
Java is −
 Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object
model.
 Platform Independent − Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This
byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it
is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be
easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive applications that can
run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
The development process is more rapid and analytical since the linking is an incremental and light-weight
process.
 High Performance − With the use of Just-In-Time compilers, Java enables high performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
Compilation and Execution of a Java Program

Java, being a platform independent programming language, doesn’t work on one-step-compilation. Instead, it involves
a two-step execution, first through an OS independent compiler; and second, in a virtual machine (JVM) which is
custom-built for every operating system. The two principle stages are explained below:

Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes the source code into a machine
independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate
‘.class’ file. While converting the source code into the bytecode, the compiler follows the following steps:
 Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax Tree)-
Nodes.
 Enter: Enters symbols for the definitions into the symbol table.
 Process annotations: If Requested, processes annotations found in the specifed compilation units.
 Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant folding.
 Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments and
reachability.
 Desugar: Rewrites the AST and translates away some syntactic sugar.
 Generate: Generates ‘.Class’ files.

Execution
The class files generated by the compiler are independent of the machine or the OS, which allows them to be run on
any system. To run, the main class file (the class that contains the method main) is passed to the JVM, and then goes
through three main stages before the final machine code is executed. These stages are:

Class Loader
The main class is loaded into the memory by passing its ‘.class’ file to the JVM, through invoking the latter.
All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat name space of class bodies that are referenced by a string
name. The method definition is:
// loadClass function prototype
Class r = loadClass(String className, boolean resolveIt);
// className: name of the class to be loaded
// resolveIt: flag to decide whether any referenced class should be loaded or not.

There are two types of class loaders: primodial, and non-primodial. Primodial class loader is embedded into all
the JVMs, and is the default class loader. A non-primodial class loader is a user-defined class loader, which can
be coded in order to customize class-loading process. Non-primodial class loader, if defined, is preferred over
the default one, to load classes.

Bytecode Verifier

After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier, whose
job is to check that the instructions don’t perform damaging actions. The following are some of the checks
carried out:

 Variables are initialized before they are used.


 Method calls match the types of object references.
 Rules for accessing private data and methods are not violated.
 Local variable accesses fall within the runtime stack.
 The run time stack does not overflow.
If any of the above checks fails, the verifier doesn’t allow the class to be loaded.

Just-In-Time Compiler

This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into
machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having the
JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy
translation process. This can lead to performance gains in the execution speed, unless methods are executed less
frequently.

Due to the two-step execution process described above, a java program is independent of the target operating system.
However, because of the same, the execution time is way more than a similar program written in a compiled platform-
dependent program.
JVM Organization

Think of the JVM as a virtual processor connected to three memory areas:

Class Area
All Java methods are compiled into Bytecodes which are stored in this area.

Heap
Every time new is invoked, memory for an instance of a class is allocated in this area.
When the heap runs low, objects no longer in use get automatically recycled by a program called the garbage collector
(gc).

Java Stack
Every time a method is invoked a stack frame is created and pushed onto the Java Stack. When the method terminates,
this frame is popped off the stack. Thus, the top-most frame of the Java stack always belongs to the method that is
currently being executed by the JVM.

Stack Frames
The format of a stack frame is important to understand. There are three areas contained in the stack frame:

The control array contains a reference to the current method (in the class area), a reference to the calling frame (which
is the frame below) and a program counter (PC) pointing to the next Bytecode instruction of the current method.
The locals array contains all local variables and parameters of the currently executing method.
There are two types of processors: register machines and stack machines. Register machines store intermediate results
of lengthy calculations in registers. Stack machines store these results on a stack. The JVM is a stack machine. Each
method gets its own operands stack where it can store the intermediate values of a calculation.
JVM is an Emulator and Interpreter

The difficult part of creating Java byte code is that the source code is compiled for a machine that does not exist. This
machine is called the Java Virtual Machine, and it exists only in the memory of our computer. Fooling the Java
compiler into creating byte code for a nonexistent machine is only one-half of the ingenious process that makes the
Java architecture neutral. The Java interpreter must also make our computer and the byte code file believe they are
running on a real machine. It does this by acting as the intermediary between the Virtual Machine and our real
machine. (See figure below.)

The Java Virtual Machine is responsible for interpreting Java byte code and translating this into actions or Operating
System calls. For example, a request to establish a socket connection to a remote machine will involve an Operating
System call. Different Operating Systems handle sockets in different ways - but the programmer doesn't need to worry
about such details. It is the responsibility of the JVM to handle these translations so that the Operating System and the
CPU architecture on which the Java software is running is completely irrelevant to the developer. (See figure below.)

The Basic Parts of the Java Virtual Machine

Creating a Virtual Machine within our computer's memory requires building every major function of a real computer
down to the very environment within which programs operate. These functions can be broken down into seven basic
parts:

 A set of registers
 A stack
 An execution environment
 A garbage-collected heap
 A constant pool
 A method storage area
 An instruction set
JVM is a software "execution engine" that safely and compatibly executes the byte codes in Java class files on a
microprocessor (whether in a computer or in another electronic device) while interpreter is a module that alternately
decodes and executes every statement in some body of code. The Java interpreter decodes and executes bytecode for
the Java virtual machine.

The JAVA INTERPRETER IS ACTUALLY A PART OF JVM. Virtual machine is not just executing the bytecodes, it
has lot of tasks to do. That full-fledged environment is referred to as a JVM.

Basically the interpreters job is to read the Java byte code, then decide how to make the operating system do
what it is that the byte code says.
When asked which is the interpreter and which is the compiler, the simplest answer is that the compiler takes the
.java text file and turns it into java byte code in a .class file. The interpreter, or JVM, is what reads the byte code,
the .class file, and causes it to execute.

The Java Instruction Set

The Java instruction set is the assembly-language equivalent of an Java application. Java applications are compiled
down to the Java instruction set just like C applications are compiled down to the instruction set of a microprocessor.
An instruction of the Java instruction set consists of an opcode specifying the operation to be performed, and zero or
more operands supplying parameters or data that will be used by the operation. Many instructions have no operands
and consist only of an opcode.

The opcodes of the Java instruction set are always one byte long, while operands may be of various sizes.

When operands are more than one byte long they are stored in "big-endian" order -- high order byte first. For example,
a 16-bit parameter is stored as two bytes whose value is:

first_byte * 256 + second_byte

Operands that are larger than 8 bits are typically constructed from byte-sized quantities at runtime -- the instruction
stream is only byte-aligned and alignment of larger quantities is not guaranteed. (An exception to this rule are the
tableswitch and lookupswitch instructions.) These decisions keep the virtual machine code for a compiled Java
program compact and reflect a conscious bias in favor of compactness possibly at some cost in performance.

Class File Format

Overview

Class files are used to hold compiled versions of both Java classes and Java Interfaces. Compliant Java interpreters
must be capable of dealing with all class files that conform to the following specification.

An Java .class file consists of a stream of 8-bit bytes. All 16-bit and 32-bit quantities are constructed by reading in two
or four 8-bit bytes, respectively. The bytes are joined together in big-endian order.

The class file format is described in terms similar to a C structure. However, unlike a C structure,

 There is no "padding" or "alignment" between pieces of the structure.


 Each field of the structure may be of variable size.
 An array may be of variable size. In this case, some field prior to the array will give the array's dimension.

We use the types u1, u2, and u4 to mean an unsigned one-, two-, or four-byte quantity, respectively.

Attributes are used at several different places in the class format. All attributes have the following format:

GenericAttribute_info {

u2 attribute_name;

u4 attribute_length;

u1 info[attribute_length];

The attribute_name is a 16-bit index into the class's constant pool; the value of constant_pool[attribute_name] will be a
string giving the name of the attribute. The field attribute_length gives the length of the subsequent information in
bytes. This length does not include the four bytes of the attribute_name and attribute_length.

In the following text, whenever we allow attributes, we give the name of the attributes that are currently understood. In
the future, more attributes will be added. Class file readers are expected to skip over and ignore the information in any
attributes that they do not understand.

The following pseudo-structure gives a top-level description of the format of a class file:

ClassFile {

u4 magic;

u4 version;

u2 constant_pool_count;

cp_info constant_pool[constant_pool_count - 1];

u2 access_flags;

u2 this_class;

u2 super_class;

u2 interfaces_count;

u2 interfaces[interfaces_count];

u2 fields_count;

field_info fields[fields_count];

u2 methods_count;

method_info methods[methods_count];

u2 attributes_count;

attribute_info attributes[attribute_count];
}

magic
This field must have the value 0xCAFEBABE.

version
This field contains the version number of the Java compiler that produced this class file. Different version numbers
indicate incompatible changes to either the format of the class file or to the bytecodes.

The current Java version number is 45.

constant_pool_count
This field indicates the number of entries in the constant pool table.

constant_pool
The constant pool is an array of values. These values are the various string constants, class names, field names, and
others that are referred to by the class structure or by the code.

constant_pool[0] is always unused. The values of constant_pool entries 1 through constant_pool_count-1 are described
by the bytes that follow. These bytes are explained more fully in the section "The Constant Pool."

access_flags
This field is a set of sixteen flags used by classes, methods, and fields to describe various properties of the field,
method, or class. The flags are also used to show how they can be accessed by methods in other classes. Below is a
table of all the access flags. The flags that are used by classes are ACC_PUBLIC, ACC_FINAL, and
ACC_INTERFACE.

this_class
This value is an index into the constant pool. constant_pool[this_class] must be a class, and gives the index of this class
in the constant pool.

super_class
This value is an index into the constant pool. If the value of super_class is non-zero, then constant_pool[super_class]
must be a class, and gives the index of this class's superclass in the constant pool.

If the value of super_class is zero, then the class being defined must be Object, and it has no superclass.
interfaces_count
This field gives the number of interfaces that this class implements.

interfaces
Each value in the array is an index into the constant pool. If an array value is non-zero, then
constant_pool[interfaces[i]], for 0 <= i < interfaces_count, must be a class, and gives the index of an interface that this
class implements.

fields_count
This value gives the number of instance variables, both static and dynamic, defined by this class. This array only
includes those variables that are defined explicitly by this class. It does not include those instance variables that are
accessible from this class but are inherited from super classes.

fields
Each value is a more complete description of a field in the class. See the section "Fields" for more information on the
field_info structure.

methods_count
This value gives the number of methods, both static and dynamic, defined by this class. This array only includes those
methods that are explicitly defined by this class. It does not include inherited methods.

methods
Each value is a more complete description of a method in the class. See the section "Methods" for more information on
the method_info structure.

attributes_count
This value gives the number of additional attributes about this class.

attributes
A class can have any number of optional attributes associated with it. Currently, the only class attribute recognized is
the "SourceFile" attribute, which gives the name of the source file from which this class file was compiled.

Source File Attribute


The "SourceFile" attribute has the following format:

SourceFile_attribute {

u2 attribute_name_index;

u2 attribute_length;

u2 sourcefile_index;}

attribute_name_index
constant_pool[attribute_name_index] is the string "SourceFile."

attribute_length
The length of a SourceFile_attribute must be 2.

sourcefile_index
constant_pool[sourcefile_index] is a string giving the source file from which this class file was compiled.
Fields
The information for each field immediately follows the field_count field in the class file. Each field is described by a
variable length field_info structure. The format of this structure is as follows:
field_info {

u2 access_flags;

u2 name_index;

u2 signature_index;

u2 attributes_count;

attribute_info attributes[attribute_count];

access_flags
This is a set of sixteen flags used by classes, methods, and fields to describe various properties and how they many be
accessed by methods in other classes. See the table "Access Flags" on page 53 which gives the meaning of the bits in
this field.

The possible fields that can be set for a field are ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED,
ACC_STATIC, ACC_FINAL, ACC_THREADSAFE, and ACC_TRANSIENT.

At most one of ACC_PUBLIC and ACC_PRIVATE can be set for any method.

name_index
constant_pool[name_index] is a string which is the name of the field.

signature_index
constant_pool[signature_index] is a string which is the signature of the field. See the section "Signatures" for more
information on signatures.

attributes_count
This value gives the number of additional attributes about this field.

attributes
A field can have any number of optional attributes associated with it. Currently, the only field attribute recognized is
the "ConstantValue" attribute, which indicates that this field is a static numeric constant, and gives the constant value
of that field.

Any other attributes are skipped.

Constant Value Attribute


The "ConstantValue" attribute has the following format:
ConstantValue_attribute {

u2 attribute_name_index;

u2 attribute_length;

u2 constantvalue_index;
}

attribute_name_index
constant_pool[attribute_name_index] is the string "SourceFile."

attribute_length
The length of a SourceFile_attribute must be 2.

constantvalue_index
constant_pool[constantvalue_index]gives the constant value for this field.

The constant pool entry must be of a type appropriate to the field, as shown by the following table:

Verification in Java (JVM)

After the class loader in the JVM loads the byte code of .class file to the machine the Bytecode is first checked for
validity by the verifier and this process is called as verification. The verifier performs as much checking as possible at
the Linking so that expensive operation performed by the interpreter at the run time can be eliminated. It enhances the
performances of the interpreter.
Some of the checks that verifier performs:
 Uninitialized Variables
 Access rules for private data and methods are not violated.
 Method calls match the object Reference.
 There are no operand stack overflows or underflows.
 The arguments to all the Java Virtual Machine instructions are of valid types.
 Ensuring that final classes are not subclassed and that final methods are not overridden
 Checking that all field references and method references have valid names, valid classes, and a valid type
descriptor. (source)
If any of these checks fails JVM throws a “java.lang.VerifyError” error. However, we can disable these checks using
java -noverify VerifyGeekFile
One might think how a program could have been manipulated since compiler checks these above validations before
generating .class file. But the class file is vulnerable to change before JVM loads it. The bytecode used in the class file
is well documented and someone having some knowledge of hex can change the values of hex codes in the .class file
thus change the behavior of the program.
For example : The Applets in the web browsers do not download source code instead they download precompiled class
files. The browser on your computer determines whether this class file is trustworthy to run or the file have been
exploited by a “hostile compiler”
Class Area

public class Area


extends Object
implements Shape, Cloneable

An Area object stores and manipulates a resolution-independent description of an enclosed area of 2-dimensional
space. Area objects can be transformed and can perform various Constructive Area Geometry (CAG) operations when
combined with other Area objects. The CAG operations include area addition, subtraction, intersection, and exclusive
or. See the linked method documentation for examples of the various operations.

The Area class implements the Shape interface and provides full support for all of its hit-testing and path iteration
facilities, but an Area is more specific than a generalized path in a number of ways:

 Only closed paths and sub-paths are stored. Area objects constructed from unclosed paths are implicitly
closed during construction as if those paths had been filled by the Graphics2D.fill method.
 The interiors of the individual stored sub-paths are all non-empty and non-overlapping. Paths are
decomposed during construction into separate component non-overlapping parts, empty pieces of the path
are discarded, and then these non-empty and non-overlapping properties are maintained through all
subsequent CAG operations. Outlines of different component sub-paths may touch each other, as long as
they do not cross so that their enclosed areas overlap.
 The geometry of the path describing the outline of the Area resembles the path from which it was
constructed only in that it describes the same enclosed 2-dimensional area, but may use entirely different
types and ordering of the path segments to do so.

Interesting issues which are not always obvious when using the Area include:

 Creating an Area from an unclosed (open) Shape results in a closed outline in the Area object.
 Creating an Area from a Shape which encloses no area (even when "closed") produces an empty Area. A
common example of this issue is that producing an Area from a line will be empty since the line encloses no
area. An empty Areawill iterate no geometry in its PathIterator objects.
 A self-intersecting Shape may be split into two (or more) sub-paths each enclosing one of the non-
intersecting portions of the original path.
 An Area may take more path segments to describe the same geometry even when the original outline is
simple and obvious. The analysis that the Area class must perform on the path may not reflect the same
concepts of "simple and obvious" as a human being perceives.

Java Stack

Here’s the definition of a Java stack, with a few pieces removed for clarity:

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the
thread. A Java virtual machine stack stores frames.
A Java virtual machine stack is analogous to the stack of a conventional language such as C: it holds local
variables and partial results, and plays a part in method invocation and return. Because the Java virtual
machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.

In layman’s terms, a simplification is to say that local variables and methods are on the Java stack.

Java Heap

Here’s the definition of a Java heap, again with a few pieces removed for clarity:

The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the
runtime data area from which memory for all class instances and arrays is allocated.

The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic
storage management system (known as a garbage collector); objects are never explicitly deallocated.

The heap may be of a fixed size or may be expanded as required by the computation and may be
contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be
contiguous.

A Java virtual machine implementation may provide the programmer or the user control over the initial
size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the
maximum and minimum heap size.

Again, in lay terms, things like objects, class variables, and instance variables go on the heap. Another way to think
about this is that if you end up having “memory leaks” in your code, the memory leaks will be in the heap, and a Java
profiling tool can help you debug this problem.

Garbage Collection in Java

Introduction

 In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer neglects
destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient
memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors.
 But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector
destroys these objects.
 Garbage collector is best example of Daemon thread as it is always running in background.
 Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.
Important terms :
1. Unreachable objects : An object is said to be unreachable iff it doesn’t contain any reference to it. Also note that
objects which are part of island of isolation are also unreachable.
2. Eligibility for garbage collection : An object is said to be eligible for GC(garbage collection) iff it is
unreachable.

Ways to make an object eligible for GC


 Even though the programmer is not responsible to destroy useless objects but it is highly recommended to make
an object unreachable(thus eligible for GC) if it is no longer required.
 There are generally four different ways to make an object eligible for garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. Object created inside method
4. Island of Isolation

Security Promises of the JVM

Here are some of the promises the Java virtual machine makes about programs that have passed the verification
algorithm:

o Every object is constructed exactly once before it is used.


o Every object is an instance of exactly one class, which does not change through the life of the object.
o If a field or method is marked private, then the only code that ever accesses it is found within the class itself.
o Fields and methods marked protected are used only by code that participates in the implementation of the class.
o Every local variable is initialized before it is used.
o Every field is initialized before it is used.
o It is impossible to underflow or overflow the stack.
o It is impossible to read or write past the end of an array or before the beginning of the array.
o It is impossible to change the length of an array once it has been created.
o Final methods cannot be overridden, and final classes cannot be subclassed.
o Attempts to use a null reference as the receiver of a method invocation or source of a field cause
a NullPointerException to be thrown.

The Java platform security architecture depends on all these promises and many more. The verification algorithm,
which enforces these promises, was outlined in chapter 6. A more complete description is available in The Java Virtual
Machine Specification, chapter 4. You can check the algorithms out for yourself. Part of the strength of the Java
platform security architecture lies in the fact that many independent reviewers have checked the algorithms.

Security Architecture and Security Policy

The Java platform builds a security architecture on top of the protections promised by the JVM. A security architecture
is a way of organizing the software that makes up the Java platform so that potentially harmful operations are isolated
from unprivileged code but available to privileged code. Most code is unprivileged; only carefully selected pieces of
code are privileged to perform potentially dangerous operations. The security architecture is responsible for making
sure that unprivileged code does not masquerade as privileged code.

The core of the Java platform security architecture under Java platforms 1.0 and 1.1 is
the SecurityManager class.[1] This class decides which pieces of code can perform certain operations and which cannot.
Collectively, these decisions are called the security policy. The security policy is enforced by the Java platform classes,
which check the SecurityManager before proceeding with any operations under the control of the SecurityManager.
[1]
On the Java 2 platform, the core of the security architecture is shifted to a class called AccessController, which falls
outside the scope of this book. See http//java.sun.com for more information.

Only one instance of the SecurityManager can be installed, and once it is installed it cannot be removed. It is called
the security manager. By default, there is no security manager, and all operations are permitted. The
class java.lang.System is responsible for ensuring that there is only one security manager. It provides the static
methods getSecurityManager and setSecurityManager to get and set the security manager.

The SecurityManager class has a set of methods that are called by the Java platform code before proceeding with
certain potentially harmful operations. These methods throw a SecurityException if the operation is forbidden. If no
exception is thrown, then the caller may assume that the operation is permitted, and it can proceed with the operation.
Table 15.1 describes the operations that are checked by the SecurityManager in the Java 1.02 platform.

The security manager uses a variety of factors to determine whether an operation is permitted or not. These factors
include the source of the code attempting the operation and the preferences of the user (discussed further in sections
15.3.2 and 15.3.3). First we present an example of how the security architecture and the security policy interact.

Table 15.1. Security checks


Method Operation checked Called by

checkAccept (String host, int port) Accepting a socket connection from host on port ServerSocket.accept

checkAccess (Thread g) Modifying the thread g Thread.stop

Thread.suspend

Thread.resume

Thread.setPriority

Thread.setName

Thread.setDaemon
checkAccess (ThreadGroup g) Modifying the thread group g ThreadGroup.<init>

ThreadGroup.setDaemon

ThreadGroup.setMaxPriority

ThreadGroup.stop

ThreadGroup.resume

ThreadGroup.destroy
checkConnect (String host, int port) Opening a socket to host on port Socket.connect

checkCreateClassLoader() Creating a class loader ClassLoader.<init>

checkDelete(String file) Deleting a file File.delete

checkExec(String cmd) Creating a subprocess Runtime.exec

checkExit(int status) Exiting the JVM Runtime.exit

checkLink(String lib) Loading a library Runtime.load

Runtime.loadLibrary
checkListen(int port) Listening at a port Socket.listen

checkPackageAccess (String package) Attempting to access package ClassLoader.loadClass

checkPackageDefinition (String package) Defining a class in package ClassLoader.loadClass

checkPropertiesAccess() Reading or writing properties System.getProperties

System.setProperties
checkPropertyAccess (String property) Reading the property named property System.getProperty

checkRead (FileDescriptor fd) Reading from the file descriptor fd FileInputStream.<init>


checkRead(String file) Reading from the file named file FileInputStream.<init>

checkSetFactory() Setting a socket factory ServerSocket

SetSocketFactory
checkWrite (FileDescriptor fd) Writing to a file descriptor FileOutputStream.<init>

checkWrite(String f) Writing to a file named file FileOutputStream.<init>

Security and the Class Loader


There are two instances where the class loader plays an important role in the Java security model: it must coordinate
with Java's security manager or access controller, and it must enforce certain rules about the namespace used by Java
classes.

Class Loaders and Security Aspects

The class loader must coordinate with the security manager and access controller of the virtual machine in order to
determine the security policy for a Java program. We'll explore this in more detail in the next few chapters when we
discuss these various security mechanisms; for now, we'll just consider the motivation for the following connection. As
we know, a Java applet cannot (normally) read a file when the applet is being run in a browser such as HotJava.[1] The
HotJava browser itself, however, can read files, even while it is also running applets. Both the browser and the applets
are using the same classes to (attempt to) read a file, so clearly there must be something that allows the java.io classes
to determine that one case should fail while the other case should succeed. That differentiation is the by-product of the
class loader: the class loader allows the security manager to find out particular information about the class, which
allows the security manager to apply the correct security policy depending on the context of the request. When we
discuss the security manager, we'll discuss the specific mechanics by which this can be achieved. For now, it is only
important to keep in mind that the class loader is the piece of the Java architecture that is able to make this distinction.
Since it loaded the class, it knows if the class came from the network (i.e., the class is part of the applet and should not
be trusted) or if the class came from the local filesystem (i.e., the class is part of the browser and should be trusted). It
also knows if the class was delivered with a digital signature, and the exact location from which the class was loaded.
All these pieces of information may be used by the security manager and access controller to establish a security
policy.

Sandbox Security Model

In computer security, a sandbox is a security mechanism for separating running programs, usually in order to minimize
system failures or software vulnerabilities from spreading. In general, a sandbox is an isolated computing environment
in which a program or file can be executed without affecting the application in which it runs. Sandboxes are used by
software developers to test new programming code.
 A sandbox typically provides a tightly controlled set of resources for guest programs to run in, such as limited
space on disk and memory.
 In a Java programming language, the sandbox is the program area and it has some set of rules that programmers
need to follow when creating Java code (like an applet) that is sent as part of a page.
 Since a Java applet is sent automatically as part of the page and can be executed as soon as it arrives, the applet
can easily do harm, either accidentally or intentionally
 The sandbox restrictions provide strict limitations on which system resources the applet can request or access.The
programmer must write code that “plays” only within the sandbox, such as children are allowed to play within the
confined limits of a place. The sandbox can be conceived as a small area within your computer where an applet’s
code can play freely – but it’s not allowed to play anywhere else.

Security in Java
 The original security model provided by the Java platform is known as the sandbox model, which existed in order
to provide a very restricted environment in which to run untrusted code obtained from the open network.
 The essence of the sandbox model is that local code is trusted to have full access to vital system resources (such
as the file system) while downloaded remote code (an applet) is not trusted and can access only the limited
resources provided inside the sandbox.

Das könnte Ihnen auch gefallen