Copyright © 2001, 2002 Southern Storm Software, Pty Ltd.
Permission to distribute unmodified copies of this work is hereby granted.
internalcall
methods that
pnetlib assumes are provided by any Common Language Runtime (CLR)
implementation that uses it.
Portable.NET
is one such implementation.We take a slightly different approach to native methods than Microsoft and Mono. Their base class libraries contain a lot of platform-specific PInvoke's and other assumptions. They both assume that a new version of the base class libraries must be compiled for each individual platform.
Intel's OCL library uses a
different approach. It abstracts the details of the engine into an
interface called IVirtualExecutionSystem
, and the details
of the operating system into an interface called IOperatingSystem
.
All methods that need these services are diverted to instances of these
interfaces which provide the underlying implementation.
There are two drawbacks to Intel's approach. The first is that it still requires a different library for each platform. The second is that these two interfaces will eventually contain hundreds of methods, all virtual. This will create a huge maintainence burden, and will impact overall performance.
We try to isolate things a bit better, while maintaining an acceptable
level of performance. The overriding design goal is: there is only one
base class library. The C# parts of our library are the same on every
platform. Platform-specific functionality is provided through native
methods that the runtime engine provides in the form of
internalcall
methods.
The methods fall into two categories: System
and
Platform
. The methods in System
provide
facilities that are platform-independent but need to be implemented in
the runtime engine. e.g. reflection must be implemented in C because
there are no IL bytecodes for implementing it. The Decimal
operators are implemented in C for speed, but they are otherwise
platform-independent.
The methods in Platform
are where the platform-specific
bits are plugged in. These methods may behave very differently on
different platforms, and under different security policies.
All System
methods should be implemented by all runtime engines.
Some Platform
natives may be stubbed out if the platform or
security policy does not allow the operation to complete.
All classes defined in Platform
must be declared
"internal
" so that programs can only get access through
the public interfaces in System, and so that the Platform
namespace does not pollute the global namespace of programs
that use the library.
public ArgIterator(RuntimeArgumentHandle); public ArgIterator(RuntimeArgumentHandle, void *);
Construct a new argument iterator object.
public TypedReference GetNextArg(); public TypedReference GetNextArg(RuntimeTypeHandle type);
Get the next argument from an argument iterator object, and advance
the iterator. If type
is supplied, then it indicates to
get the next argument with the specified type.
public RuntimeTypeHandle GetNextArgType();
Get the type of the next argument, but do not advance the iterator.
public int GetRemainingCount();
Get the number of arguments that remain to be processed by the iterator.
public static void Clear(Array array, int index, int length);
Clear the contents of an array sub-range to all-zeroes, or all-nulls, depending upon the element type. The CLR is responsible for checking the arguments and throwing exceptions where necessary.
public void Initialize();
Call the default value type constructor for all elements within the array. If the array does not contain value types, or the types do not have a default constructor, then this method does nothing.
public static void Copy(Array sourceArray, int sourceIndex, Array destArray, int destIndex, int length);
Copy the contents of a source array to a destination array. This may involve converting the elements into the destination array's element type. See the ECMA specifications for further information on the behaviour of this method, and the exceptions that it may throw.
private static Array CreateArray(IntPtr elementType, int rank, int length1, int length2, int length3);
Create an array of elements. This may be called for single, two, or three-dimensional arrays that have no lower bounds. The number oflength
arguments to use is specified byrank
. The CLR can assume that all arguments have been validated.
private static Array CreateArray(IntPtr elementType, int[] lengths, int[] lowerBounds);
Create an array of elements. This is called for creating arbitrarily-sized arrays. The CLR can assume that all arguments have been validated.
private int GetLength();
Get the length of the array. If the array is single-dimensional,
this will be the same as calling GetLength(0)
. If
the array is multi-dimensional, this will be the product of the
length of all dimensions.
public int GetLength(int dimension);
Get the length of a specific array dimension.
public int GetLowerBound(int dimension);
Get the lower bound of a specific array dimension.
public int GetUpperBound(int dimension);
Get the upper bound of a specific array dimension.
private int GetRank();
Get the rank of the array.
private Object Get(int index1, int index2, int index3);
Get the value at a specific position within the array. Throws
IndexOutOfRangeException
if any of the indices are
out of range. This method is called for arrays with 1, 2, and 3
dimensions. The CLR should ignore extraneous arguments.
private Object Get(int[] indices);
Get the value at a specific position within the array. Throws
IndexOutOfRangeException
if any of the indices are
out of range.
private void Set(Object value, int index1, int index2, int index3);
Set the value at a specific position within the array. Throws
IndexOutOfRangeException
if any of the indices are
out of range. This method is called for arrays with 1, 2, and 3
dimensions. The CLR should ignore extraneous arguments.
private void Set(Object value, int[] indices);
Set the value at a specific position within the array. Throws
IndexOutOfRangeException
if any of the indices are
out of range.
The high bit ofprivate int flags, high, middle, low;
flags
is non-zero to indicate a negative
number. Bits 16-23 hold a scale factor, between 0 and 28 inclusive.
The three words high
, middle
, and
low
form a 96-bit mantissa for the Decimal
value, with the power of 10 specified by the scale factor.
The Decimal
operators use the "round half even" rounding
mode. Values less than 0.5 round down. Values greater than 0.5 round
up. Values equal to 0.5 round either up or down, depending upon which
will give an even result.
Further information on the representation of Decimal
may
be found in the ECMA specifications for C# and in the pnetlib source code.
The CLR can call the
The CLR can call the
The CLR can call the
The
The
String objects begin with the above header and are variable in length.
The length is determined by the constructor. The entire string is stored
in a single heap memory block. Other implementations, particularly Java,
store the string header and character array separately.
It is possible for
It is possible for
It is possible for
Note: the Microsoft .NET Framework ignores the
Exception constructor calls can be recognised on the stack by looking
for methods called "
If an exception constructor did throw an exception, it will appear to
have come from the method that threw the original exception. The impact
of this is not serious, because stack frames are typically only used for
debug string output.
The runtime engine can assume that all of the reflection classes that
it needs to instantiate have the following representation:
The engine is also responsible for checking the permissions of the caller
against the access levels of the program constructs. For example, an
application cannot access a
Permission checking proceeds as follows:
The convention that we have adopted is that a method that needs
private access will have the
Note: Microsoft's .NET framework requires that names of 128 or more
characters will cause
Note: this method may return
If the name is 128 or more characters in length, then
This method returns the member,
The
Note: Microsoft's .NET framework requires that names of 128 or more
characters will cause
Note: in the current system, it is impossible to construct an object
that isn't already boxed, so it is unclear what this is supposed to
achieve other than always returning
If the system is single-threaded, this method will always return
Every system has its own error numbering system. It is the responsibility
of the CLR to convert the system error numbers into the constants from
the
Note: it is usually possible to access these standard streams as
file descriptors 0, 1, and 2 through regular filesystem operations
such as those in
Some operating systems, particularly for embedded systems, may not
have standard input and output streams in the same sense as desktop
platforms. They may not have a regular filesystem at all. However,
they may have functions that can be used to report messages to
debuggers or logging facilities. This class can be used to
redirect
CLR's on GUI systems may wish to disable
The methods below use the descriptors 0, 1, and 2 to mean standard
input, standard output, and standard error, respectively. The
CLR is free to disable any of these. For example, it may always
indicate EOF when
This is usually implemented with a large lookup table. Some
systems may have functions to perform this lookup already, and
other CLR's may have to provide their own implementation.
CLR implementations on small memory footprint devices may want
to use a smaller table that is tailored to a particular locale.
Making this
This method returns -1.0 if there is no numeric value associated
with the character.
This value is only used if the
This value is different from that passed to the
Some systems have no way to discover the time since reboot.
The CLR may return the time since the engine was started instead.
public Decimal(float value);
public Decimal(double value);
Construct
Decimal
values from float
and double
values. If value
is out of range,
NaN, or an infinity, then throw an OverflowException
exception.Decimal.ThrowOverflow()
method to
throw the exception. This will ensure that the exception message will
be appropriately translated into foreign languages. The same applies
for all of the remaining Decimal
methods that throw
exceptions.
public static float ToSingle(decimal value);
public static float ToDouble(decimal value);
Convert
Decimal
values into either float
or double
. No exceptions are thrown.
public static decimal Add(decimal x, decimal y);
Add two
Decimal
values, throwing an exception on overflow.
public static int Compare(decimal x, decimal y);
Compare two
Decimal
values. Returns -1, 0, or 1, depending
upon whether the comparison is less than, equal to, or greater than.
public static decimal Divide(decimal x, decimal y);
Divide two
Decimal
values and return the quotient.
Throws OverflowException
if the result is too large to
be represented as a Decimal
value. Throws
DivideByZeroException
if y
is zero.Decimal.ThrowDivZero()
method to
throw the exception. This will ensure that the exception message will
be appropriately translated into foreign languages. The same applies
for the Remainder
method.
public static decimal Floor(decimal x);
Compute the next lower integer value below or equal to
x
.
public static decimal Remainder(decimal x, decimal y);
Divide two
Decimal
values and return the remainder.
Throws OverflowException
if the quotient is too large to
be represented as a Decimal
value. Throws
DivideByZeroException
if y
is zero.
public static decimal Multiply(decimal x, decimal y);
Multiply two
Decimal
values and return the product.
Throws OverflowException
if overflow occurs.
public static decimal Negate(decimal x);
Negate a
Decimal
value. No exceptions are thrown.
public static decimal Round(decimal x, int decimals);
Round a
Decimal
value to a specific number of decimal
places. The decimals
value must be between 0 and 28
inclusive, or an ArgumentOutOfRangeException
is thrown.
Overflow will cause an OverflowException
to be thrown.Decimal.ThrowDecimals()
method to
throw the ArgumentOutOfRangeException
. This will ensure
that the exception message will be appropriately translated into
foreign languages.
public static decimal Subtract(decimal x, decimal y);
Subtract two
Decimal
values, throwing an exception on overflow.
public static decimal Truncate(decimal x);
Truncate a
Decimal
value to an integer, towards zero.
System.Delegate
The CLR can assume that the System.Delegate
and
System.MulticastDelegate
classes have the
following field definitions:
The CLR will use these structures when creating delegates from function
pointers. The correct delegate creation algorithm is as follows:
public abstract class Delegate
{
internal Object target;
internal MethodInfo method;
}
public abstract class MulticastDelegate : Delegate
{
private MulticastDelegate prev;
}
The target
and method
fields with the correct values based on the function pointer
data.prev
to null
.prev
field can be used by the runtime engine to optimise
the invocation of multicast delegates. If it is null
, then
the delegate's invocation list consists of a single entry defined
by target
and method
. Otherwise, the
delegate should be invoked by doing a recursive call on prev
,
and then invoking the main entry defined by target
and method
.private static Delegate CreateBlankDelegate(Type type, ClrMethod method);
Creates an object which is an instance of the specified
type
,
but does not call the constructor or otherwise initialize the object fields.
This is used by Delegate.CreateDelegate
to construct an
object that it will fill in with method details later.method
parameter is used to validate the delegate's
signature. If the delegate's Invoke
method does not
have the same signature as method
, then
CreateBlankDelegate
should return null
.method
parameter will be null
if the
method is not a runtime engine method. In this case,
CreateBlankDelegate
should return a new delegate only if
the delegate type has no signature (i.e., no Invoke
method).
System.Double
public static bool IsNaN(double d);
Returns
true
if d
is not a number.
private static int TestInfinity(double d);
Returns -1 if
d
is negative infinity, 1 if d
is positive infinity, and 0 otherwise.
System.Enum
private Object GetEnumValue();
Get the value of this enumerated type instance as a boxed object.
The type of the returned value will be one of
System.Byte
,
System.SByte
, System.Int16
,
System.UInt16
, System.Int32
,
System.UInt32
, System.Int64
,
and System.UInt64
, depending upon the enumerated type's
underlying type.
private static String GetEnumName(Type enumType, Object value);
Get the name of an enumerated constant given a value in the
underlying type of the specified enumerated type. Returns
null
if the value does not correspond to an enumerated constant in the type.
private static bool IsEnumValue(Type enumType, Object value);
Determine if
value
is a legitimate value for the specified
enumerated type. The value will be a member of the enumerated type's
underlying type.
private static Object GetEnumValueFromName
(Type enumType, Object value, bool ignoreCase);
Get an enumerated value by name. The name may either be a constant name,
or an integer value. The return type is either an enumerated value in
the specified type, or
null
if the name is invalid.
private static Object EnumValueOr(Object value1, Object value2);
Form the OR of two enumerated values to produce a new enumerated value
of the same type.
private static Object EnumIntToObject(Type enumType, int value);
Convert an integer value into a boxed enumerated value of the specified type.
private static Object EnumLongToObject(Type enumType, int value);
Convert a long integer value into a boxed enumerated value of
the specified type.
private static String FormatEnumWithFlags(Type enumType, Object value);
Format an enumerated value that may involve flag bits.
System.GC
public static void KeepAlive(Object obj);
Keep an object reference alive.
public static void ReRegisterForFinalize(Object obj);
Re-register an object for finalization that had previously been
de-registered by
SuppressFinalize
. Use of this is
security-sensitive, and the CLR may choose to ignore the call.
public static void SuppressFinalize(Object obj);
Suppress finalization for an object. Use of this is security-sensitive,
and the CLR may choose to ignore the call.
public static void WaitForPendingFinalizers();
Wait for all pending object finalizers to be run.
System.Guid
public static Guid NewGuid();
Create a new, random, GUID value and return it. Note: it is recommended
that this be the output of a secure random number generator, and not be
based on host-specific or user-specific information. GUID's based on
host or user information can be a threat to the user's privacy.
System.Math
public static double Acos(double d);
public static double Asin(double d);
public static double Atan(double d);
public static double Atan2(double y, double x);
public static double Cos(double d);
public static double Cosh(double d);
public static double Sin(double d);
public static double Sinh(double d);
public static double Tan(double d);
public static double Tanh(double d);
Perform various trigonometric functions on
double
values.
public static double Ceiling(double d);
Compute the ceiling of a
double
value.
public static double Floor(double d);
Compute the floor of a
double
value.
public static double Exp(double d);
Compute e raised to the power of a
double
value.
public static double Pow(double x, double y);
Compute
x
raised to the power of y
.
public static double IEEERemainder(double x, double y);
Compute the IEEE remainder of dividing two
double
values.
public static double Log(double d);
Compute the logarithm, in base e, of a
double
value.
public static double Log10(double d);
Compute the logarithm, in base 10, of a
double
value.
public static double Round(double d);
Round a
double
value to the nearest integer.
private static double RoundDouble(double d, int digits);
Round a
double
value to a certain number of decimal
digits. The CLR can assume that digits
has already
been validated by the caller.
public static double Sqrt(double d);
Compute the square root of a
double
value.
System.Object
public Type GetType();
Get the type associated with the object. The same value must be
returned for multiple calls on the same object, and for two objects
with identical types. The returned value will typically be an
instance of
ClrType
, which subclasses Type
.
public virtual int GetHashCode();
Get the default hash code associated with the object. Normally this
is just the object pointer, cast to
int
. On platforms
with 64-bit pointers, this may either truncate the pointer or attempt
to combine the high and low words into the final hash value.
public virtual bool Equals(Object obj);
Default implementation of "Equals". Returns true only if
this
and obj
refer to the same object.
protected Object MemberwiseClone();
Perform a memberwise clone on the object.
System.RuntimeFieldHandle
Runtime field handles are pushed onto the evaluation stack using
the ldtoken
instruction. We assume that the data structure
contains a single IntPtr
value that points to CLR-specific
data. The class library does not attempt to interpret this value any
further, but it will pass it to various internalcall
API's
that deal with field reflection.System.RuntimeMethodHandle
Runtime method handles are pushed onto the evaluation stack using
the ldtoken
instruction. We assume that the data structure
contains a single IntPtr
value that points to CLR-specific
data. The class library does not attempt to interpret this value any
further, but it will pass it to various internalcall
API's
that deal with method reflection.public IntPtr GetFunctionPointer();
Get the function pointer that corresponds to a method handle. The
returned value may be a native function pointer value, or it may simply
be the method handle as a pointer. The behaviour is CLR-specific.
System.RuntimeTypeHandle
Runtime type handles are pushed onto the evaluation stack using
the ldtoken
instruction. We assume that the data structure
contains a single IntPtr
value that points to CLR-specific
data. The class library does not attempt to interpret this value any
further, but it will pass it to various internalcall
API's
that deal with type reflection.System.Single
public static bool IsNaN(float f);
Returns
true
if f
is not a number.
private static int TestInfinity(float f);
Returns -1 if
f
is negative infinity, 1 if f
is positive infinity, and 0 otherwise.
System.String
The class library assumes that strings are represented in a particular
manner by the runtime engine. The definition of the fields within
the class library is as follows:
The length of the string is class String
{
private int capacity;
private int length;
private char firstChar;
}
length
, and the first character
starts at the address of capacity
in memory. The
capacity
field will typically be equal to or greater
than length
, and indicates how many characters of space
are available in the string. This is used by the StringBuilder
class to insert additional characters into a string while it is being
built.public String(char[] value, int startIndex, int length);
public String(char[] value);
public String(char c, int count);
public String(char *value, int startIndex, int length);
public String(char *value);
public String(sbyte *value, int startIndex, int length, Encoding enc);
public String(sbyte *value, int startIndex, int length);
public String(sbyte *value);
Construct a new string object with the specified contents.
public static int Compare(String strA, String strB);
Compare two strings using the prevailing locale settings. The comparison
is case-sensitive.
private static int InternalCompare(String strA, int indexA, int lengthA,
String strB, int indexB, int lengthB,
bool ignoreCase, CultureInfo culture);
Compare two sub-strings using the specified culture settings. If
culture
is null
, then use the prevailing
locale settings. The comparison is case-insensitive if
ignoreCase
is false
.lengthA
and lengthB
to
be different: e.g., if lengthA
is less than lengthB
and the first lengthA
characters of strA
are
identical to the first lengthA
characters of strB
,
then strA
is less than strB
.
private static int InternalOrdinal(String strA, int indexA, int lengthA,
String strB, int indexB, int lengthB);
Compare two sub-strings using ordinal character comparisons. Locale
and culture information is not used. It is possible for
lengthA
and lengthB
to be different:
e.g., if lengthA
is less than lengthB
and the first lengthA
characters of strA
are
identical to the first lengthA
characters of strB
,
then strA
is less than strB
.
internal static String NewString(int length);
Allocate a string of the specified
length
, and populate
it with zeroes. This is used by methods such as Concat
and Insert
to build blank strings ready to be filled
with new characters. The CLR can assume that the length
argument is valid.
internal static String NewBuilder(int capacity);
Allocate a string object with its capacity initialized
to
capacity
, and its length
initialized
to zero. This is used by the StringBuilder
class
to assist in the process of building strings.
internal static void Copy(String dest, int destPos, String src);
Copy the entire contents of
src
to dest
,
starting at destPos
. The CLR can assume that all
arguments are valid.destPos
to be greater than or equal to
the length of dest
if the string object is being constructed
by a StringBuilder
. The CLR should not range-check this value.
internal static void Copy(String dest, int destPos,
String src, int srcPos, int length);
Copy
length
characters from the contents of the string
src
, starting at srcPos
, to the contents of
dest
The CLR can assume that all arguments are valid.destPos
to be greater than or equal to
the length of dest
if the string object is being constructed
by a StringBuilder
. The CLR should not range-check this value.
internal static void InsertSpace(String str, int srcPos, int destPos);
Insert space into a string by moving all characters starting at
srcPos
to a new location starting at destPos
.
internal static void RemoveSpace(String str, int index, int length);
Remove
length
characters from a string starting at
index
.
public static String Concat(String str1, String str2);
public static String Concat(String str1, String str2, String str3);
Concatenate two (or three) strings together. These are specified as
internalcall
methods because the runtime engine may have
an efficient mechanism to concatenate strings.
private void CopyToChecked(int sourceIndex, char[] dest,
int destIndex, int count);
Copy the contents of a string into a destination array. The CLR can
assume that the arguments have already been checked for validity.
public static bool Equals(String a, String b);
Compare two strings for ordinal equality.
private bool EqualRange(int srcIndex, int count,
String dest, int destIndex);
Compare sub-ranges of two strings for ordinal equality. The CLR
can assume that the arguments are valid.
public override int GetHashCode();
Get a hash value for the string.
public int IndexOf(char value, int startIndex, int count);
Get the index of a specific character within the string. See the ECMA
specification for information on the exceptions that this method may throw.
public int IndexOfAny(char[] anyOf, int startIndex, int count);
Get the index of a character within the string that appears in the
anyOf
array. See the ECMA specification for information on
the exceptions that this method may throw.
public int LastIndexOf(char value, int startIndex, int count);
Get the last index of a specific character within the string. See the ECMA
specification for information on the exceptions that this method may throw.
public int LastIndexOfAny(char[] anyOf, int startIndex, int count);
Get the last index of a character within the string that appears in the
anyOf
array. See the ECMA specification for information on
the exceptions that this method may throw.
public static String Intern(String str);
Intern a string and return the new value. If
str
is already
intern'ed or null
, this method will return str
.
public static String IsInterned(String str);
Determine if
str
is intern'ed. If it is, then return
str
. Otherwise return null
.
private static void CharFill(String str, int start, int count, char ch);
Fill a sub-range within a string with a specified character. The CLR
can assume that the arguments are valid.
private static void CharFill(String str, int start, char[] chars,
int count, char ch);
Fill a sub-range within a string with a range of characters from an array.
public String Replace(char oldChar, char newChar);
Replace all occurrences of
oldChar
in the string with
newChar
, and return a newly allocated string with the
replacements.
public String Replace(String oldValue, String newValue);
Replace all occurrences of
oldValue
in the string with
newValue
, and return a newly allocated string with the
replacements.
private String Trim(char[] trimChars, int trimFlags);
Trim any characters that are contained in the specified array from
the string. The
trimFlags
argument specifies where the
characters should be trimmed from: the bit TrimFlag_Front
(1)
indicates the front, and the bit TrimFlag_End
(2)
indicates the end. Setting both bits will trim both ends of the string.
private char GetChar(int posn);
Gets the character at
posn
within the string. Throws
an IndexOutOfRangeException
if posn
is
invalid.
private void SetChar(int posn, char ch);
Sets the character at
posn
within the string to ch
.
Throws an IndexOutOfRangeException
if posn
is
invalid.
System.Type
public static Type GetType(String name, bool throwOnError, bool ignoreCase);
Get a type by name from the executing image. If
throwOnError
is true
, then throw a TypeLoadException
if the
type cannot be found. Otherwise return null
. If
ignoreCase
is true, then ignore case when comparing names.ignoreCase
value
if the name is 128 or more characters in length, and performs a
case-sensitive search regardless.
public static RuntimeTypeHandle GetTypeHandle(Object obj);
Get the type handle associated with the type of the specified object.
public static Type GetTypeFromHandle(RuntimeTypeHandle handle);
Get the type that corresponds to the specified
handle
.
The returned value will typically be an instance of ClrType
,
which subclasses Type
. The CLR is required to return the
same object for multiple calls to this method with the same handle.
System.TypedReference
private static TypedReference ClrMakeTypedReference(Object target, FieldInfo[] flds);
Make a typed reference from a target and a set of fields. The fields are
guaranteed to be non-null and members of the
ClrField
class.
This method may throw an exception if the fields are not valid for the object.
public static void SetTypedReference(TypedReference target, Object value);
Set the value within a typed reference.
public static Object ToObject(TypedReference value);
Convert a typed reference into an object.
System.Diagnostics
System.Diagnostics.Debugger
private static bool InternalIsAttached();
Determine if a debugger is currently attached to the executing process.
If the CLR does not support debugging, this will always return
false
.
public static void Break();
Cause an explicit breakpoint to occur within the attached debugger.
If the CLR does not support debugging, or there is no debugger attached,
calls to this method are ignored.
public static bool IsLogging();
Determine if the attached debugger is currently logging messages.
If the CLR does not support debugging, or log message during debugging,
this method will always return
false
.
private static bool InternalLaunch();
Launch the debugger and attach it to this process if it is not already
attached. If the CLR does not support debugging, or attaching a debugger
to a running process, then this method will always return
false
.
If the debugger is already attached, this method will simply return
true
.
public static void Log(int level, String category, String message);
Log a message with the debugger's logging facility. If the CLR does
not support debug logging, or it is currently disabled, then calls
to this method will be ignored.
System.Diagnostics.StackFrame
private static int InternalGetTotalFrames();
Get the total number of stack frames that are on the stack in the
current thread, excluding the frame that was set up to call
InternalGetTotalFrames
.
private static RuntimeMethodHandle InternalGetMethod(int skipFrames);
Get the method handle from a stack frame that is
skipFrames
items up the stack. The value 0 indicates the method that called
InternalGetMethod
.
private static int InternalGetILOffset(int skipFrames);
Get the offset within the Intermediate Language (IL) bytecode of
the current execution position within the method that is
skipFrames
items up the stack. If the offset cannot
be determined, this method should return -1.
private static int InternalGetNativeOffset(int skipFrames);
Get the offset within the native code of the current execution position
within the method that is
skipFrames
items up the stack.
If the offset cannot be determined, this method should return -1.
private static String InternalGetDebugInfo(RuntimeMethodHandle method, int offset,
out int line, out int column);
Get debug line number information about a specific IL offset within
the specified method. The line number is returned in
line
(0 if the line number cannot be determined). The column number is returned
in column
(0 if the column number cannot be determined).
The filename is returned from the method (null
if the filename
cannot be determined).
private static PackedStackFrame[] GetExceptionStackTrace();
Get the stack trace for the current position in the program in response
to an exception object being created. The CLR must skip over any method
frames that correspond to exception constructor calls, and then begin
collecting information. The data is returned in an array of
PackedStackFrame
structures. The first element in this
array corresponds to the stack frame that threw the exception.
The PackedStackFrame
structure has the following definition:
This information can usually be collected very quickly, without having
to consult the reflection system to resolve method objects. The exception
object caches this information until it is needed.internal struct PackedStackFrame
{
public RuntimeMethodHandle method;
public int offset;
public int nativeOffset;
}
.ctor
" in a class that inherits from
System.Exception
. Because exception constructors normally
do not throw exceptions, this should be sufficient in most cases.System.Reflection
The following sections describe the internalcall methods that must be
supplied by the runtime engine to implement reflection. In many cases,
the runtime engine is expected to construct an object that represents
an underlying program construct. e.g. an assembly, method, type, etc.
That is, the objects contain a single pointer field. The runtime engine
is responsible for filling in this field with an appropriate value that
can be used to perform other reflection operations. The engine must return
the same object for multiple requests for the same program construct.class Name
{
private IntPtr privateData;
}
private
member unless it is
in the application's assembly or the application has
ReflectionPermission
.
Sometimes it is necessary for the system library to get private
access to the internals of an object even if the caller does not
have the necessary permissions. The ReflectionPermission
, then access is denied.ValueType
class
is one such example.ClrReflection
attribute.
This attribute can only be used on methods within the system library
assembly. It will be ignored on methods in other assemblies.System.Reflection.Assembly
public static Assembly GetCallingAssembly();
Get the assembly object that contains the method that called the method
that called
GetCallingAssembly
.
public static Assembly GetExecutingAssembly();
Get the assembly object that contains the method that called
GetExecutingAssembly
.
public static Assembly GetEntryAssembly();
Get the assembly object that contains the entry point method
for the application.
public virtual Type[] GetExportedTypes();
Return an array of all types that have been exported from the assembly.
public virtual FileStream GetFile(String name);
Description TBD.
public virtual Type GetType(String name, bool throwOnError, bool ignoreCase);
Locate a specific type within the assembly and return it to the caller.
If
throwOnError
is true
, then an exception should
be thrown if the type does not exist. If ignoreCase
is
true
, then the name match is case-insensitive.ignoreCase
to be ignored, and a
case-sensitive search to be performed regardless.
public virtual Type[] GetTypes();
Get an array of all types within the assembly. Note: the array will not
include types that the caller cannot access.
private static Assembly LoadFromName(String name, out int error);
Load an assembly given its base name. e.g. "
System
". The
exact file resolution algorithm used is system-dependent. This method
returns null
if an error occurs, with the reason for the
error returned in error
:
LoadError_InvalidName
: the name string was invalid.
The caller will have already checked for null
, so
it isn't necessary for the engine to handle this case.LoadError_FileNotFound
: the file containing the
assembly could not be located.LoadError_BadImage
: there was something wrong with
the assembly image.LoadError_Security
: the caller has insufficient
security credentials to load the assembly.private static Assembly LoadFromFile(String name, out int error);
Load an assembly given its actual filename. Unlike
LoadFromName
,
this will not perform name resolution.
System.Reflection.ClrConstructor
public override Object Invoke(BindingFlags invokeAttr, Binder binder,
Object[] parameters, CultureInfo culture);
Invoke this constructor with the specified parameters and return the
new object.
System.Reflection.ClrField
public override Object GetValue(Object obj);
Get the value of a field within a specified object. The object will
be
null
for a static field. If the field has an associated
literal, then this will return the value of the literal.
public override void SetValue(Object obj, Object value);
Set the value of a field within a specified object. The object will
be
null
for a static field.
private static Type GetFieldType(IntPtr item);
Get the type of a field program item. The
item
value will
be the same as the privateData
member within the
ClrField
class.
public override Object GetValueDirect(TypedReference obj);
Get the value of a field within a specified object that is represented
as a typed reference.
public override void SetValueDirect(TypedReference obj, Object value);
Set the value of a field within a specified object that is represented
as a typed reference.
System.Reflection.ClrHelpers
The ClrHelpers
class contains a number of common methods
that are used across multiple program construct kinds. These methods
take an IntPtr
argument which corresponds to the
privateData
field in the program construct's object.public static Object[] GetCustomAttributes(IntPtr item, IntPtr type, bool inherit);
Get an array of all custom attributes on the specified
item
that match the given type
. If type
is zero,
then get all custom attributes irrespective of type. If inherit
is true
, then inspect ancestor classes in the inheritance
hierarchy for additional attributes.
public static bool IsDefined(IntPtr item, IntPtr type, bool inherit);
Determine if attributes of a specified type are defined on the program item.
public static IntPtr GetDeclaringType(IntPtr item);
Get the
privateData
value for the type in which the
specified item member is declared. The return value will be turned
into a RuntimeTypeHandle
value, and then into a
Type
.
public static String GetName(IntPtr item);
Get the name that is associated with a particular program item.
public static IntPtr GetParameter(IntPtr item, int num);
Get a parameter information block for a specific parameter on the
given method or property
item
. The value num
will be zero to get information about the return type, and 1 for the
first parameter. If there is no parameter information associated
with the parameter, this method should return zero.
public static Type GetParameterType(IntPtr item, int num);
Get a parameter type for a specific parameter on the given method or
property
item
. The value num
will be zero
to get information about the return type, or 1 for the first parameter.
public static int GetNumParameters(IntPtr item);
Get the number of parameters that are declared for the specified
method or property
item
.
public static int GetMemberAttrs(IntPtr item);
Get the attribute flags that are associated with a specific type member
item (field, method, event, or property).
public static CallingConventions GetCallConv(IntPtr item);
Get the calling conventions for a specified method
item
.
public static MethodImplAttributes GetImplAttrs(IntPtr item);
Get the method implementation attributes that are associated with
a specific method
item
.
public static MethodInfo GetSemantics
(IntPtr item, MethodSemanticsAttributes type, bool nonPublic);
Get the method that corresponds to a particular semantics
type
and on event or property item
. The return value will typically
be an instance of ClrMethod
. If nonPublic
is
false
, then only return public semantics methods.null
if the method is not
accessible to the caller due to permissions issues.
public static bool HasSemantics
(IntPtr item, MethodSemanticsAttributes type, bool nonPublic);
Determine if the event or property
item
has the specified
method semantics type
. If nonPublic
is
false
, then only return public semantics methods.
public static bool CanAccess(IntPtr item);
Determine if the caller has sufficient permissions to access the
specified program item (type, field, constructor, method, event,
or property). This is used by the library to check an item that
was obtained previously and cached, but which may not be accessible
in the context in which it is now used.
System.Reflection.ClrMethod
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder,
Object[] parameters, CultureInfo culture);
Invoke this method with the specified parameters and return the result.
private static MethodInfo GetBaseDefinition(IntPtr handle);
If the specified method is virtual, then find the base definition in
the parent class or in an ancestor class. Returns
null
if no suitable method found.
System.Reflection.ClrParameter
private static ParameterAttributes GetParamAttrs(IntPtr item);
Get the attributes for a specified parameter
item
. This
value is from a previous call to ClrHelpers.GetParameter
.
private static String GetParamName(IntPtr item);
Get the name that is associated with a specified parameter
item
.
Returns null
if the parameter does not have a name.
private static Object GetDefault(IntPtr item);
Get the default value that is associated with a specified parameter
item
. Returns null
if the parameter does
not have a default value.
System.Reflection.ClrProperty
private static Type GetPropertyType(IntPtr item);
Get the type of a property program item. The
item
value will
be the same as the privateData
member within the
ClrProperty
class.
System.Reflection.ClrType
private int GetClrArrayRank();
Get the rank of this array type. If the type is not an array, this
should return zero.
protected override TypeAttributes GetAttributeFlagsImpl();
Get the attribute flags for this type.
public override Type GetElementType();
Get the element type if this type is an array, pointer, or byref.
Returns
null
otherwise.
public override Type GetInterface(String name, bool ignoreCase);
Get a particular interface that this type implements. Returns
null
if the type does not implement the interface,
or the interface is inaccessible due to permission issues.ignoreCase
is itself ignored. This is a requirement
of Microsoft's .NET Framework.
public override Type[] GetInterfaces();
Get an array of all interfaces that this type implements. The runtime
engine will exclude interfaces that are not accessible to the caller
due to permission issues.
private MemberInfo GetMemberImpl(String name, MemberTypes memberTypes,
BindingFlags bindingAttr, Binder binder,
CallingConventions callingConventions,
Type[] types, ParameterModifier[] modifiers);
Search the type for a member that matches the specified conditions.
This method is called for any kind of type member: methods, constructors,
fields, events, properties, or nested types. The
memberTypes
parameter is a bitmask that specifies the kinds of members that should
be inspected. The other parameters provide information to further narrow
the search.null
, or throws an
AmbiguousMatchException
if there is more than one member
that matches the specified conditions. The returned member will usually be
an instance of ClrMethod
, ClrConstructor
,
ClrField
, ClrEvent
, ClrProperty
,
or ClrType
.
private Object GetMembersImpl(MemberTypes memberTypes,
BindingFlags bindingAttr,
Type arrayType, String name);
Get an array of all members that match the specified conditions.
The
memberTypes
parameter indicates the kind of members
that should be returned. If name
is not null
,
then only return members with the given name.arrayType
parameter indicates the type of the array to
be created. This is normally one of MemberInfo[]
,
MethodInfo[]
, ConstructorInfo[]
,
FieldInfo[]
, EventInfo[]
,
PropertyInfo[]
, or Type[]
, depending
upon the type of lookup that is being performed.
private ClrTypeCategory GetClrTypeCategory();
Get the category value for this type. Array, pointer, etc. See the
ClrTypeCategory
enumeration for a list of values.
private bool IsSubclassOf(Type c);
Determine if this type is a subclass of
c
.
private bool IsClrNestedType();
Determine if this type is nested within another type.
private Assembly GetClrAssembly();
Get the assembly that this type is a member of.
private Type GetClrBaseType();
Get the base type for this type, or
null
if it has no
base type (i.e. System.Object
).
private String GetClrFullName();
Get the full name of this type, including name, namespace, and suffixes
that indicate arrays, pointers, etc.
private Guid GetClrGUID();
Get the GUID value for this type. If the runtime engine does not
support GUID's, then it should return a value that is cleared to
all-zeroes.
private Module GetClrModule();
Get the module that this type is a member of.
private Type GetClrNestedDeclaringType();
Get the declaring type that contains this type if it is nested.
Returns
null
if the type is not nested.
private String GetClrName();
Get this type's name.
private String GetClrNamespace();
Get this type's namespace.
System.Reflection.FieldInfo
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle);
Get a field object given its handle. This will typically return an
instance of
ClrField
.
System.Reflection.MethodBase
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle);
Get a method object given its handle. This will typically return an
instance of either
ClrMethod
or ClrConstructor
.
public static MethodBase GetCurrentMethod();
Get the current method that called
GetCurrentMethod
.
System.Reflection.Module
public virtual Type GetType(String name, bool throwOnError, bool ignoreCase);
Locate a specific type within the module and return it to the caller.
If
throwOnError
is true
, then an exception should
be thrown if the type does not exist. If ignoreCase
is
true
, then the name match is case-insensitive.ignoreCase
to be ignored, and a
case-sensitive search to be performed regardless.
public virtual Type[] GetTypes();
Get an array of all types in this module.
public bool IsResource();
Determine if this module only contains resources.
internal virtual Type GetModuleType();
Get the type information object for the global "
<Module>
"
type within the module.
private Assembly GetAssembly();
Get the assembly that this module resides in.
private String GetFullName();
Get the full name of the module.
System.Runtime
System.Runtime.CompilerServices.RuntimeHelpers
public static void InitializeArray(Array array, RuntimeFieldHandle field);
Initialize the contents of a primitive array from the contents of an
RVA-based field.
public static void RunClassConstructor(RuntimeTypeHandle type);
Run the static class constructor for a specified type. The CLR may provide
a facility to mark a class constructor once it has been executed so that
subsequent calls to this method will do nothing.
public static int InternalOffsetToStringData();
Returns the offset from the start of an object of the
String.firstChar
field on the current platform. This is
provided as an internalcall method because different systems may
layout the System.String
class differently.
public static Object GetObjectValue(Object value);
Box the specified
value
and return it as an object.
If the object is already boxed, return value
.value
. It is provided
for compatibility with the Microsoft .NET Framework.
System.Runtime.InteropServices.GCHandle
private static IntPtr GCAddrOfPinnedObject(int handle);
Get the physical address that is associated with a pinned GC object handle.
private static int GCAlloc(Object value, GCHandleType type);
Allocate a new GC object handle for the specified value and type.
private static void GCFree(int handle);
Free a GC object handle that is no longer required.
private static bool GCValidate(int handle);
Validate a GC object handle. Returns
false
if the handle
has been free'd or it was never allocated as a GC object.
private static Object GCGetTarget(int handle);
Get the target object that is associated with a GC object handle.
private static void GCGetTarget(int handle, Object value, bool isPinned);
Set the target that is associated with a GC object handle and
optionally pin it.
System.Text
System.Text.DefaultEncoding
The System.Text.DefaultEncoding
class implements the default
character set encoding on the underlying platform. The CLR is responsible
for converting between the default encoding and Unicode by providing
the facilities in this class. The CLR can assume that the arguments to
the following methods have been fully validated.private static int InternalGetByteCount(char[] chars, int index, int count);
Get the number of bytes in the default encoding that are required to encode
the characters in the specified range of the
chars
array.
private static int InternalGetByteCount(String s, int index, int count);
Get the number of bytes in the default encoding that are required to encode
the characters in the specified range of the
s
string.
private static int InternalGetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex);
Get the bytes in the default encoding that correspond to the characters
in the specified range of the
chars
array. The bytes
are written to the array bytes
, starting at
byteIndex
. The number of bytes written is returned
from the method. If insufficient space is available in the bytes
array for the bytes, then this method should return -1.
private static int InternalGetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex);
Get the bytes in the default encoding that correspond to the characters
in the specified range of the
s
string. The bytes
are written to the array bytes
, starting at
byteIndex
. The number of bytes written is returned
from the method. If insufficient space is available in the bytes
array for the bytes, then this method should return -1.
private static int InternalGetCharCount(byte[] bytes, int index, int count);
Get the number of characters that are required to decode the specified
range of bytes from the
bytes
array.
private static int InternalGetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex);
Convert the characters in the default encoding into Unicode characters
from the specified range of the
bytes
array. The characters
are written to the array chars
, starting at
charIndex
. The number of characters written is returned
from the method. If insufficient space is available in the chars
array for the characters, then this method should return -1.
private static int InternalGetMaxByteCount(int charCount);
Get the maximum number of bytes of buffer space that may be required
to convert
charCount
characters into the default encoding.
private static int InternalGetMaxCharCount(int byteCount);
Get the maximum number of characters of buffer space that may be required
to convert
byteCount
bytes from the default encoding.
private static String InternalGetString(byte[] bytes, int index, int count);
Convert the specified range of bytes within the
bytes
array
into a string.
System.Threading
System.Threading.Interlocked
The System.Threading.Interlocked
class provides a number
of methods for performing atomic operations in a multi-threaded environment.
The CLR must perform these operations in an atomic manner.
public static int CompareExchange(ref int location1, int value, int comparand);
public static float CompareExchange(ref float location1, float value, float comparand);
public static Object CompareExchange(ref Object location1, Object value, Object comparand);
Compare the contents of
location1
with comparand
.
If they are the same, then write value
to that location and
return the original value of location1
from the method.
Otherwise return the value of location1
.
public static int Decrement(ref int location);
public static long Decrement(ref long location);
Decrement the contents of
location
and return its new value.
public static int Exchange(ref int location1, int value);
public static float Exchange(ref float location1, float value);
public static Object Exchange(ref Object location1, Object value);
Exchange the contents of
location1
with value
and return the original value of location1
.
public static int Increment(ref int location);
public static long Increment(ref long location);
Increment the contents of
location
and return its new value.
System.Threading.Monitor
public static void Enter(Object obj);
Enter a monitor on an object. If the system is single-threaded,
this does nothing because there are no other threads to block
the operation.
public static bool InternalTryEnter(Object obj, int timeout);
Try to enter a monitor, with a specified timeout in milliseconds.
A timeout value of -1 means "wait indefinitely", and a value of 0
means "test and return immediately". Returns
true
if the monitor was successfully entered. If the system is
single-threaded, this always returns true
because
there are no other threads to block the operation.
public static void Exit(Object obj);
Exit from a monitor on an object. If the system is single-threaded,
this does nothing.
public static bool InternalWait(Object obj, int timeout);
Release the monitor lock on an object and wait for a pulse to
reawaken the current thread. A timeout value of -1 means
"wait indefinitely", and a value of 0 means "test and return
immediately". Returns
false
if the timeout expired.
The timeout is in milliseconds.false
. Using Wait
, Pulse
,
and PulseAll
in a single-threaded environment is
not recommended.
public static void Pulse(Object obj);
Notify the next waiting thread on a monitor that it can wake up and
reacquire the monitor lock. If the system is single-threaded, then
this method does nothing.
public static void PulseAll(Object obj);
Notify all waiting threads on a monitor that they can wake up and
reacquire the monitor lock. If the system is single-threaded, then
this method does nothing.
System.Threading.Mutex
private static IntPtr InternalCreateMutex(bool initiallyOwned, String name, out bool gotOwnership);
Create a CLR mutex object and return a handle for it.
If
initiallyOwned
is true
, then
acquire the ownership of the mutex for the current thread.
If name
is not null
, then the
mutex is attached to the specified name. The gotOwnership
parameter will be set to true
if ownership of the
mutex could be initially acquired. The returned value must be
usable as a WaitHandle
.
private static void InternalReleaseMutex(IntPtr mutex);
Release a mutex that was previously acquired with a
Wait
operation.
System.Threading.Thread
The CLR can assume that the Thread
class starts with the
following fields:
There may be other fields besides these, but these will always be present
at the start of the object in the specified order.public sealed class Thread
{
private IntPtr privateData;
private Object stateInfo;
private ThreadStart start;
private String name;
}
private void FinalizeThread();
This method is called when the
Thread
object is collected
by the garbage collector. If the thread is still active, it should
be shut down.
public void Abort();
Abort this thread.
private void InternalJoin(int timeout);
Attempt to join the executing thread with the thread represented
by this thread object. A timeout value of -1 indicates "wait
indefinitely" and a timeout value of 0 indicates "test and return
immediately". The timeout value is in milliseconds.
public static void MemoryBarrier();
Insert a memory barrier at this point in thread execution, to ensure
that all pending memory loads and stores will be flushed.
public static void ResetAbort();
Reset the pending abort on the current thread.
private static void InternalSleep(int timeout);
Put the current thread to sleep for a certain period of time.
A timeout value of -1 indicates that the thread should be put
to sleep forever (or at least until it is aborted). A timeout
value of 0 indicates that control should return the thread
immediately, perhaps after yielding a timeslice.
public void Start();
Start execution of the thread represented by
this
.
public static byte VolatileRead(ref byte address);
public static sbyte VolatileRead(ref sbyte address);
public static short VolatileRead(ref short address);
public static ushort VolatileRead(ref ushort address);
public static int VolatileRead(ref int address);
public static uint VolatileRead(ref uint address);
public static long VolatileRead(ref long address);
public static ulong VolatileRead(ref ulong address);
public static IntPtr VolatileRead(ref IntPtr address);
public static UIntPtr VolatileRead(ref UIntPtr address);
public static float VolatileRead(ref float address);
public static double VolatileRead(ref double address);
public static Object VolatileRead(ref Object address);
Read a value from a specific address in such a way that the value
will be treated as volatile. This method will ensure that the
operation is performed atomically with respect to volatile writes
to the same address.
public static void VolatileWrite(ref byte address, byte value);
public static void VolatileWrite(ref sbyte address, sbyte value);
public static void VolatileWrite(ref short address, short value);
public static void VolatileWrite(ref ushort address, ushort value);
public static void VolatileWrite(ref int address, int value);
public static void VolatileWrite(ref uint address, uint value);
public static void VolatileWrite(ref long address, long value);
public static void VolatileWrite(ref ulong address, ulong value);
public static void VolatileWrite(ref IntPtr address, IntPtr value);
public static void VolatileWrite(ref UIntPtr address, UIntPtr value);
public static void VolatileWrite(ref float address, float value);
public static void VolatileWrite(ref double address, double value);
public static void VolatileWrite(ref Object address, Object value);
Read a value to a specific address in such a way that the value
will be treated as volatile. This method will ensure that the
operation is performed atomically with respect to volatile reads
from the same address.
private static Thread InternalCurrentThread();
Get the object that represents the currently executing thread.
private void InternalSetBackground(bool value);
Set the background state of the thread. The program will exit when
all non-background threads have terminated. Setting a thread to
background prevents it from keeping the program alive when the
"main" thread exits.
private ThreadPriority InternalGetPriority();
Get the priority of the thread.
private void InternalSetPriority(ThreadPriority value);
Set the priority of the thread to
value
.
private ThreadState InternalGetState();
Get the current state of the thread. i.e. Running, Stopped, Waiting,
Background, etc.
System.Threading.WaitHandle
The WaitHandle
class is the base for a number of different
"waiting objects" within the library, including Mutex
.
The CLR can assume that the field definition of this class is as follows:
The public abstract class WaitHandle
{
private IntPtr privateData;
}
privateData
field holds a pointer to a CLR-specific
handle that represents the wait object.private static void InternalClose(IntPtr privateData);
Close a CLR wait object.
private static bool InternalWaitAll(WaitHandle[] waitHandles, int timeout,
bool exitContext);
Wait until all handles in an array become active. The CLR can assume
that the parameters have been validated. A timeout value of -1 indicates
"wait indefinitely" and a timeout value of 0 indicates "test and return
immediately". Returns
true
if any of the handles have
become active, or false
if a timeout occurred. The timeout
is in milliseconds.
private static int InternalWaitAny(WaitHandle[] waitHandles, int timeout,
bool exitContext);
Wait until any handle in an array become active. The CLR can assume
that the parameters have been validated. A timeout value of -1 indicates
"wait indefinitely" and a timeout value of 0 indicates "test and return
immediately". Returns the index of the handle that became active,
or -1 if a timeout occurred. The timeout is in milliseconds.
private static bool InternalWaitOne(IntPtr privateData, int timeout);
Wait until a particular handle becomes active. A timeout value of -1
indicates "wait indefinitely" and a timeout value of 0 indicates
"test and return immediately". Returns
true
if the handle
became active, or false
if a timeout occurred. The timeout
is in milliseconds.
Platform
Platform.DirMethods
This class contains directory manipulation functions for the filesystem.public static PathInfo GetPathInfo();
Retrieves path character information from the runtime engine.
i.e. the separators to be used for directories, PATH's, etc.
The following is the definition of
Platform.PathInfo
:
struct PathInfo
{
public char dirSeparator;
public char altDirSeparator;
public char volumeSeparator;
public char pathSeparator;
public char[] invalidPathChars;
}
The fields have the following meaning:
dirSeparator
'/'
for Unix systems and '\'
for Windows
systems. This must be set to a non-zero value.altDirSeparator
0
for Unix systems and '/'
for Windows systems. The value 0
is used to indicate
that there is no alternative directory separator.volumeSeparator
0
for Unix systems and ':'
for Windows systems.
The value 0
is used to indicate that there is no
volume separator.pathSeparator
':'
for Unix systems and ';'
for Windows systems.
This must be set to a non-zero value.invalidPathChars
null
indicates that
all characters are valid, with special meanings only for the
separator characters listed above.public static String GetSystemDirectory();
Get the full pathname of the "System" directory on this machine.
This is highly Windows-specific. If the platform does not have
such a directory, this method should return
null
.
public static Errno GetLastAccess(string path, out long lastac);
Gets the most recent access of
path
and stores it in
lastac
; The correct errno value is returned
corresponding to the type of error.
On Unix this call and all similar calls could be implemented with a
stat
call
public static Errno GetLastModification(string path, out long lastac);
Gets the time of most recent modification(writes, etc.) to
path
and puts it in lastac
public static Errno GetCreationTime(string path, out long ctime);
Gets the time of the creation of
path
, and puts it in
lastac
returns the approiate Platform.Errno value if there are errors.
public static Errno Copy(string src, string dest);
Copies
src
to dest
returns appropriate
Platform.Errno value.
public static Errno Delete(string path);
Deletes
path
returns appropriate Errno value.
public static Errno Rename(string old, string new);
Renames(or moves)
old
to new
. Returns
appropriate Errno value.
Platform.FileMethods
The FileMethods
class provides a number of primitive methods
for accessing raw binary file streams within the underlying operating
system's filespace.public static IntPtr GetInvalidHandle();
Get a value that represents an invalid operating system file handle.
Usually this is some sentinel value such as 0 or -1, coerced to
IntPtr
. It can be any value, as long as it is not
possible to encounter a legitimate file handle with this value.
public static bool ValidatePathname(String path);
Validate that the supplied pathname is legitimate according to
the underlying filesystem's pathname rules.
public static bool Open(String path, FileMode mode, FileAccess access,
FileShare share, out IntPtr handle);
Attempt to open a file with the specified mode, access, and sharing flags.
If the file could be opened, a handle is returned in
handle
,
and the method returns true
. If the file could not be
opened, the method returns false
, and GetErrno
should be consulted to determine the reason for the failure.
public static bool HasAsync();
Determine if the system has support for asynchronous file handle operations.
public static bool CanSeek(IntPtr handle);
Determine if it is possible to seek on the specified file handle.
This method must leave the current file position unchanged.
public static bool CheckHandleAccess(IntPtr handle, FileAccess access);
Check to see if an existing file handle was opened for the specified access.
public static long Seek(IntPtr handle, long offset, SeekOrigin origin);
Seek to a particular position on a file handle. Returns -1 if the offset
is out of range, or an error occurred. Consult
GetErrno
for the reason for the error.
public static bool Write(IntPtr handle, byte[] buffer, int offset, int count);
Write the contents of a buffer to a file handle. Returns false if
an I/O error occurred. Consult
GetErrno
for the reason for
an I/O error.
public static int Read(IntPtr handle, byte[] buffer, int offset, int count);
Read data from a file handle into a supplied buffer. Returns -1 in
an I/O error occurred, 0 at end of file, or the number of bytes
read otherwise. Console
GetErrno
for the reason for
an I/O error.
public static bool Close(IntPtr handle);
Close a particular file handle. Returns
false
if an
I/O error occurred. Consult GetErrno
for the reason
for an I/O error.
public static bool FlushWrite(IntPtr handle);
Flush all data that was previously written to a file handle,
in response to a user-level "Flush" request. Normally thi will
do nothing unless the platform provides its own buffering.
Returns
false
if an I/O error occurred.
Consult GetErrno
for the reason for an I/O error.
public static bool SetLength(IntPtr handle, long value);
Set the length of a file to a new value. Returns
false
if an I/O error occurred. Consult GetErrno
for the
reason for an I/O error.
public static Errno GetErrno();
Get the last-occurring system error code for the currently
executing thread.
public static String GetErrnoMessage(Errno errno);
Get a descriptive message for the error code
errno
from
the underlying system. If the system does not have an appropriate
message, this method will return null
.
Platform.Errno
The Errno
enumerated type defines a large number of
Posix-style error codes that may be returned for failed operating
system calls.Errno
type so that the C# library has a consistent set
of values to use, regardless of the underlying platform.Platform.Stdio
The Stdio
class provides a number of primitive methods
for manipulating stdin
, stdout
, and
stderr from the System.Console
class.
It can only be used to access these three streams, and only for
character-based data. Binary file streams are handled by
Platform.FileMethods
.Platform.FileMethods
, but that usage
is not portable between systems.System.Console
to those functions.System.Console
or divert it to a logging facility, because it isn't normally
visible in the GUI. This class provides a convenient place where
such diversion can be performed.StdRead
is called if reading from
standard input is disallowed.public static void StdClose(int fd);
Close the specified stream. The CLR may ignore this call if closing
a standard stream has been disallowed for security reasons.
public static void StdFlush(int fd);
Flush the contents of the specified stream.
public static void StdWrite(int fd, char value);
public static void StdWrite(int fd, char[] value, int index, int count);
public static void StdWrite(int fd, String value);
Write values of various types to the specified output stream. This
may convert from Unicode into a local character set.
public static int StdRead(int fd);
Read a single character from the specified input stream. Returns the
char
value, coerced to int
, or -1 at EOF or
on error. This method may convert from a local character set into
Unicode.
public static int StdRead(int fd, char[] value, int index, int count);
Read a buffer of characters from the specified input stream. Returns the
number of characters read, 0 at EOF, or -1 on error. This method may
convert from a local character set into Unicode.
public static int StdPeek(int fd);
Peek at the next character from the specified input stream, but leave
the current stream position unchanged. Returns the
char
value, coerced to int
, or -1 at EOF or on error.
This method may convert from a local character set into Unicode.
Platform.SysCharInfo
public static UnicodeCategory GetUnicodeCategory(char ch);
Get the category that a specific Unicode character falls
within (uppercase, lowercase, digit, space, currency, etc).
internalcall
gives the CLR maximum flexibility
as to how this is implemented, and what trade-offs may apply.
public static double GetNumericValue(char ch);
Get the numeric value associated with a Unicode character.
e.g. the "1/4" character ('\u00BC') returns "0.25". This is also
usually implemented with a lookup table.
public static String GetNewLine();
Get the newline string to be used on this platform. This
will typically be either
"\n"
or "\r\n"
.
This value is cached by Environment.NewLine
, which
is the portable way to obtain the string.
Platform.TaskMethods
Contains methods related to tasks, such as processes and threads.public static void Exit(int exitCode);
Exit from the current process. This will only be called if
the program has the necessary security permissions, so it is
safe to exit immediately.
public static void SetExitCode(int exitCode);
Set the exit code to use when the current process exits by
returning from its
Main
method. The default
value should be zero.Main
method is
declared as returning void
.
public static String[] GetCommandLineArgs();
Get the command-line arguments for the current process.
Returns
null
if the platform does not support
command-line arguments. The first returned argument is the
name of the executable.Main
method. The argument to Main
does not include
the name of the executable.public static String GetEnvironmentVariable(String variable);
Get the value of a named environment variable. Returns
null
if the variable is not present.
public static int GetEnvironmentCount();
Get the number of environment variables that are associated
with the current task. Returns zero if the environment is empty,
or not accessible to the program.
public static String GetEnvironmentKey(int posn);
Get the key (or variable name) associated with the environment
variable at a specific index. Returns
null
if the index is invalid.
public static String GetEnvironmentValue(int posn);
Get the value associated with the environment variable at a
specific index. Returns
null
if the index is invalid.
Platform.TimeMethods
public static long GetCurrentTime();
Get the current time in tenths of a microsecond since
12:00am 1 Jan 0001 as a 64-bit value. This returns local time.
It is the responsibility of the CLR to convert from the system's
epoch into this one, and to handle local timezone conversions.
The CLR should return the most accurate time value that it can
obtain, even if it isn't accurate to a tenth of a microsecond.
public static long GetCurrentUtcTime();
Get the current time in tenths of a microsecond since
12:00am 1 Jan 0001 as a 64-bit value. This returns UTC time
(sometimes incorrectly called "GMT"). It is the responsibility of
the CLR to convert from the system's epoch into this one. The
CLR should return the most accurate time value that it can obtain,
even if it isn't accurate to a tenth of a microsecond.
public static int GetTimeZoneAdjust();
Gets the number of seconds West of UTC for the local timezone,
including any applicable daylight savings adjustments.
public static int GetUpTime();
Get the number of milliseconds since the system was last rebooted.
This is typically called
GetTickCount
under Windows.