Kernel

Module Kernel provides the runtime support for BlackBox applications.

Facilities include memory management, garbage collection, module loading, symbolic debugging using meta information, exception handling, and various other low-level support facilities.

The Kernel documentation is provided to support Framework development. Application developers are advised to use higher level facilities. Kernel routine interfaces and functionality may change between BlackBox releases.

Green color means COM-specific text.
??? indicates missing content.


DEFINITION Kernel	(* nonportable (i386) *);

	IMPORT SYSTEM, WinApi;

	CONST
		commNotFound = 7;
		commSyntaxError = 8;
		cyclicImport = 5;
		docType = "odc";
		done = 0;
		fileNotFound = 1;
		illegalFPrint = 4;
		littleEndian = TRUE;
		moduleNotFound = 9;
		nameLen = 256;
		noMem = 6;
		objNotFound = 3;
		objType = "ocf";
		processor = 10;
		symType = "osf";
		syntaxError = 2;
		timeResolution = 1000;

	TYPE
		Directory = POINTER TO RECORD [untagged] 
			num-: INTEGER;
			obj-: ARRAY OF ObjDesc
		END;

		ExcpFramePtr = POINTER TO ExcpFrame;
		ExcpFrame = EXTENSIBLE RECORD [untagged] 
			link: ExcpFramePtr;
			handler: PROCEDURE (excpRec: WinApi.PtrEXCEPTION_RECORD; estFrame: ExcpFramePtr;
												context: WinApi.PtrCONTEXT; dispCont: INTEGER): INTEGER
		END;

		ItemExt = POINTER TO ABSTRACT RECORD 
			(e: ItemExt) BaseTyp (): INTEGER, NEW, ABSTRACT;
			(e: ItemExt) BoolVal (): BOOLEAN, NEW, ABSTRACT;
			(e: ItemExt) Call (OUT ok: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) CharVal (): CHAR, NEW, ABSTRACT;
			(e: ItemExt) Deref (VAR ref: ANYREC), NEW, ABSTRACT;
			(e: ItemExt) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) Index (index: INTEGER; VAR elem: ANYREC), NEW, ABSTRACT;
			(e: ItemExt) IntVal (): INTEGER, NEW, ABSTRACT;
			(e: ItemExt) Len (): INTEGER, NEW, ABSTRACT;
			(e: ItemExt) LongVal (): LONGINT, NEW, ABSTRACT;
			(e: ItemExt) Lookup (name: ARRAY OF CHAR; VAR i: ANYREC), NEW, ABSTRACT;
			(e: ItemExt) PtrVal (): ANYPTR, NEW, ABSTRACT;
			(e: ItemExt) PutBoolVal (x: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) PutCharVal (x: CHAR), NEW, ABSTRACT;
			(e: ItemExt) PutIntVal (x: INTEGER), NEW, ABSTRACT;
			(e: ItemExt) PutLongVal (x: LONGINT), NEW, ABSTRACT;
			(e: ItemExt) PutPtrVal (x: ANYPTR), NEW, ABSTRACT;
			(e: ItemExt) PutRealVal (x: REAL), NEW, ABSTRACT;
			(e: ItemExt) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) PutSetVal (x: SET), NEW, ABSTRACT;
			(e: ItemExt) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
			(e: ItemExt) RealVal (): REAL, NEW, ABSTRACT;
			(e: ItemExt) SetVal (): SET, NEW, ABSTRACT;
			(e: ItemExt) Size (): INTEGER, NEW, ABSTRACT;
			(e: ItemExt) Valid (): BOOLEAN, NEW, ABSTRACT
		END;

		Module = POINTER TO RECORD [untagged] 
			next-: Module;
			opts-: SET;
			refcnt-: INTEGER;
			compTime-, loadTime-: ARRAY 6 OF SHORTINT;
			ext-: INTEGER;
			term-: Command;
			nofimps-, nofptrs-, csize-, dsize-, rsize-, code-, data-, refs-, procBase-, varBase-: INTEGER;
			names-: POINTER TO ARRAY [untagged] OF SHORTCHAR;
			ptrs-: POINTER TO ARRAY [untagged] OF INTEGER;
			imports-: POINTER TO ARRAY [untagged] OF Module;
			export-: Directory;
			name-: Utf8Name
		END;

		Object = POINTER TO ObjDesc;
		ObjDesc = RECORD [untagged] 
			fprint-, offs-, id-: INTEGER;
			struct-: Type
		END;

		Reducer = POINTER TO ABSTRACT RECORD 
			(r: Reducer) Reduce (full: BOOLEAN), NEW, ABSTRACT
		END;

		Signature = POINTER TO RECORD [untagged] 
			retStruct-: Type;
			num-: INTEGER;
			par-: ARRAY OF RECORD [untagged] 
					id-: INTEGER;
					struct-: Type
				END
		END;

		TrapCleaner = POINTER TO ABSTRACT RECORD 
			(c: TrapCleaner) Cleanup, NEW, EMPTY
		END;

		Type = POINTER TO RECORD [untagged] 
			size-: INTEGER;
			mod-: Module;
			id-: INTEGER;
			base-: ARRAY 16 OF Type;
			fields-: Directory;
			ptroffs-: ARRAY OF INTEGER
		END;

		Command = PROCEDURE;

		Handler = PROCEDURE;

		Identifier = ABSTRACT RECORD 
			typ: INTEGER;
			obj-: ANYPTR;
			(VAR id: Identifier) Identified (): BOOLEAN, NEW, ABSTRACT
		END;

		ItemAttr = RECORD 
			obj, vis, typ, adr: INTEGER;
			mod: Module;
			desc: Type;
			ptr: SYSTEM.PTR;
			ext: ItemExt
		END;

		Name = ARRAY 256 OF CHAR;

		TryHandler = PROCEDURE (a, b, c: INTEGER);

		Utf8Name = ARRAY 256 OF SHORTCHAR;

	VAR
		err-: INTEGER;
		fp-: INTEGER;
		mainWnd: INTEGER;
		modList-: Module;
		pc-: INTEGER;
		sp-: INTEGER;
		stack-: INTEGER;
		trapCount-: INTEGER;
		val-: INTEGER;
		watcher: PROCEDURE (event: INTEGER);

	PROCEDURE AddRef (p: INTEGER): INTEGER;
	PROCEDURE AllocModMem (descSize, modSize: INTEGER; VAR descAdr, modAdr: INTEGER);
	PROCEDURE Allocated (): INTEGER;
	PROCEDURE Beep;
	PROCEDURE Call (adr: INTEGER; sig: Signature; IN par: ARRAY OF INTEGER; n: INTEGER): LONGINT;
	PROCEDURE Cleanup;
	PROCEDURE Collect;
	PROCEDURE DeallocModMem (descSize, modSize, descAdr, modAdr: INTEGER);
	PROCEDURE FastCollect;
	PROCEDURE FatalError (id: INTEGER; str: ARRAY OF CHAR);
	PROCEDURE GetLoaderResult (OUT res: INTEGER; OUT importing, imported, object: ARRAY OF CHAR);
	PROCEDURE GetModName (mod: Module; OUT name: Name);
	PROCEDURE GetObjName (mod: Module; obj: Object; OUT name: Name);
	PROCEDURE GetRefProc (VAR ref: INTEGER; OUT adr: INTEGER; OUT name: Utf8Name);
	PROCEDURE GetRefVar (VAR ref: INTEGER; OUT mode, form: SHORTCHAR; OUT desc: Type; 
											OUT adr: INTEGER; OUT name: Utf8Name);
	PROCEDURE GetTypeName (t: Type; OUT name: Name);
	PROCEDURE InstallCleaner (p: Command);
	PROCEDURE [code] InstallExcp (VAR e: ExcpFrame);
	PROCEDURE InstallReducer (r: Reducer);
	PROCEDURE InstallTrapChecker (h: Handler);
	PROCEDURE InstallTrapViewer (h: Handler);
	PROCEDURE InterfaceTrapHandler (excpRec, estFrame, context, dispCont: INTEGER): INTEGER;
	PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
	PROCEDURE IsLower (ch: CHAR): BOOLEAN;
	PROCEDURE IsReadable (from, to: INTEGER): BOOLEAN;
	PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
	PROCEDURE LevelOf (t: Type): SHORTINT;
	PROCEDURE LoadDll (IN name: ARRAY OF CHAR; VAR ok: BOOLEAN);
	PROCEDURE LoadMod (IN name: ARRAY OF CHAR);
	PROCEDURE Lower (ch: CHAR): CHAR;
	PROCEDURE MakeFileName (VAR name: ARRAY OF CHAR; type: ARRAY OF CHAR);
	PROCEDURE NewArr (eltyp, nofelem, nofdim: INTEGER): INTEGER;
	PROCEDURE NewObj (VAR o: SYSTEM.PTR; t: Type);
	PROCEDURE NewRec (typ: INTEGER): INTEGER;
	PROCEDURE PopTrapCleaner (c: TrapCleaner);
	PROCEDURE PushTrapCleaner (c: TrapCleaner);
	PROCEDURE Quit (exitCode: INTEGER);
	PROCEDURE RegisterMod (mod: Module);
	PROCEDURE Release (p: INTEGER): INTEGER;
	PROCEDURE Release2 (p: INTEGER): INTEGER;
	PROCEDURE RemoveCleaner (p: Command);
	PROCEDURE [code] RemoveExcp (VAR e: ExcpFrame);
	PROCEDURE Root (): INTEGER;
	PROCEDURE SearchProcVar (var: INTEGER; VAR m: Module; VAR adr: INTEGER);
	PROCEDURE SetTrapGuard (on: BOOLEAN);
	PROCEDURE SourcePos (mod: Module; codePos: INTEGER): INTEGER;
	PROCEDURE SplitName (name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR);
	PROCEDURE Start (code: Command);
	PROCEDURE StringToUtf8 (IN in: ARRAY OF CHAR; OUT out: ARRAY OF SHORTCHAR; 
											OUT res: INTEGER);
	PROCEDURE ThisCommand (mod: Module; IN name: ARRAY OF CHAR): Command;
	PROCEDURE ThisDesc (mod: Module; fprint: INTEGER): Object;
	PROCEDURE ThisDllObj (mode, fprint: INTEGER; IN dll, name: ARRAY OF CHAR): INTEGER;
	PROCEDURE ThisField (rec: Type; IN name: ARRAY OF CHAR): Object;
	PROCEDURE ThisFinObj (VAR id: Identifier): ANYPTR;
	PROCEDURE ThisLoadedMod (IN name: ARRAY OF CHAR): Module;
	PROCEDURE ThisMod (IN name: ARRAY OF CHAR): Module;
	PROCEDURE ThisObject (mod: Module; IN name: ARRAY OF CHAR): Object;
	PROCEDURE ThisType (mod: Module; IN name: ARRAY OF CHAR): Type;
	PROCEDURE Time (): LONGINT;
	PROCEDURE Try (h: TryHandler; a, b, c: INTEGER);
	PROCEDURE TypeOf (IN rec: ANYREC): Type;
	PROCEDURE UnloadMod (mod: Module);
	PROCEDURE Upper (ch: CHAR): CHAR;
	PROCEDURE Used (): INTEGER;
	PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR; 
											OUT res: INTEGER);
	PROCEDURE WouldFinalize (): BOOLEAN;

END Kernel.


It is generally advised that applications avoid calling Kernel routines directly where possible. There are usually higher level ways of accessing the required functionality; for example use Services.Ticks rather than Kernel.Time.

This document has been reverse engineered by people who were not involved with designing or implementing it. Hence it may contain errors and omissions. Please report any deficiencies to the Community Forum:

	BlackBox Component Builder Forums	http://community.blackboxframework.org
	Main area	BLACKBOX COMPONENT BUILER SUPPOPRT
	Group	BlackBox Framework
	Topic	Documentation issues.


CONST done, fileNotFound, syntaxError, objNotFound, illegalFPrint, cyclicImport, noMem, commNotFound, commSyntaxError, moduleNotFound
Error codes used by the loader.


CONST docType, symType, objType
The files extensions for BlackBox documents, symbol files, and code files.


CONST littleEndian = TRUE
Specifies the byte ordering within computer words.
Little-endian gives lower addresses to the lower numbered bits in the word, big-endian gives lower addresses to the higher numbered bits.
Intel x86 processors are little-endian.


CONST nameLen = 256
Specifies the length of type Name.


CONST processor = 10
The current hardware platform. The value of 10 corresponds to the platform x86.


CONST timeResolution = 1000;
Number of ticks of the system timer, corresponding to one second.


TYPE Directory
[untagged]
Type used to give external access to objects.

num-: INTEGER
The number of objects made available.

obj-: ARRAY OF ObjDesc
An array giving access to the objects.


TYPE ExcpFramePtr
POINTER TO ExcpFrame

TYPE ExcpFrame
EXTENSIBLE 
[untagged]
Type used to implement a list of exception handlers.

link: ExcpFramePtr
Pointer to the next exception handler

handler: PROCEDURE
The exception handler procedure.


TYPE ItemExt
ABSTRACT
Type that can be used to make the type Item defined in module Meta effectively extensible.
The following ABSTRACT procedures define the interfaces of that type that can be extended.
For the functionality of these procedures refer to the documentation for Meta.Item.

PROCEDURE (e: ItemExt) BaseTyp (): INTEGER
PROCEDURE (e: ItemExt) BoolVal (): BOOLEAN
PROCEDURE (e: ItemExt) Call (OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) CharVal (): CHAR
PROCEDURE (e: ItemExt) Deref (VAR ref: ANYREC)
PROCEDURE (e: ItemExt) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) Index (index: INTEGER; VAR elem: ANYREC)
PROCEDURE (e: ItemExt) IntVal (): INTEGER
PROCEDURE (e: ItemExt) Len (): INTEGER
PROCEDURE (e: ItemExt) LongVal (): LONGINT
PROCEDURE (e: ItemExt) Lookup (name: ARRAY OF CHAR; VAR i: ANYREC)
PROCEDURE (e: ItemExt) PtrVal (): ANYPTR
PROCEDURE (e: ItemExt) PutBoolVal (x: BOOLEAN)
PROCEDURE (e: ItemExt) PutCharVal (x: CHAR)
PROCEDURE (e: ItemExt) PutIntVal (x: INTEGER)
PROCEDURE (e: ItemExt) PutLongVal (x: LONGINT)
PROCEDURE (e: ItemExt) PutPtrVal (x: ANYPTR)
PROCEDURE (e: ItemExt) PutRealVal (x: REAL)
PROCEDURE (e: ItemExt) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) PutSetVal (x: SET)
PROCEDURE (e: ItemExt) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) RealVal (): REAL
PROCEDURE (e: ItemExt) SetVal (): SET
PROCEDURE (e: ItemExt) Size (): INTEGER
PROCEDURE (e: ItemExt) Valid (): BOOLEAN


TYPE Module
[untagged]
Type used to implement a list of records containing information about Modules.

next-: Module
The next Module in the list.

opts-: SET
Elements 0..15 are reserved for compiler options, 16..31 for kernel flags.
Element 16: Module has been initialised.
Element 17: Module has been dynamically loaded.
Element 24: The module is a DLL.
Element 30: The module has pointers to COM objects.

refcnt-: INTEGER
The number of other modules that import this module. If refcnt < 0 this module is not valid.

compTime-, loadTime-: ARRAY 6 OF SHORTINT
The times when this module was compiled and loaded into memory.
The time format is Year [0], Month [1], Day [2], Hour [3], Minute [0], & Second [5].

ext-: INTEGER
Currently not used.

term-: Command
Procedure called when the module is unloaded.

nofimps-: INTEGER
Number of modules imported by this module.

nofptrs-: INTEGER
Number of global pointers used by this module.

csize-, dsize-, rsize-: INTEGER
Sizes of the module's code section, data section, and symbol information sections.

code-, data-, refs-: INTEGER
Pointer to the start of the code section, data section, and symbol information section, respectively.
(The BlackBox variables in the data section are arranged in the reverse order of their declaration in the source code). 

procBase-, varBase-: INTEGER
Meta base address for calculating the displacement of procedures and variables, respectively.

names-: POINTER TO ARRAY OF SHORTCHAR
[untagged]

ptrs-: POINTER TO ARRAY OF INTEGER
[untagged]
List of offsets, relative to varBase, to specify pointers to objects.
It is used by the garbage collector, and the COM compiler additions.

imports-: POINTER TO ARRAY OF Module
[untagged]
List of modules directly imported by this module.

export-: Directory
List of objects exported by this module. The list is sorted in ascending order by object name.

name-: Utf8Name
The name of this module in UTF-8 format.


TYPE Object = POINTER TO ObjDesc
TYPE ObjDesc
[untagged] 
Contains information about objects.

fprint-: INTEGER
Object fingerprint used to implement version control.

offs-: INTEGER
Fingerprint for record types.

id-: INTEGER
Object properties in packaged form.

struct-: Type
Id of basic type, or pointer to typedesc / signature.


TYPE Reducer
ABSTRACT
List of objects used to (try to) reduce the amount of heap memory used.

PROCEDURE (r: Reducer) Reduce (full: BOOLEAN)
ABSTRACT
The procedure called to perform the reduction. It is called when new memory blocks are required, but there is not sufficient memory immediately available.
The first time it is called in each block allocation full is set FALSE.
If sufficient memory is still not available it may be called again with full set TRUE.


TYPE Signature
[untagged]
Record containing information about an object.

retStruct-: Type
Id of basic type, or pointer to typedesc, or 0

num-: INTEGER
Number of parameters

par-: ARRAY OF RECORD
[untagged]
Parameters

	id-: INTEGER
	Name index * 256  +  kind 

	struct-: Type
	Id of basic type or pointer to typedesc.


TYPE TrapCleaner
ABSTRACT
Base type for trap cleaners.

PROCEDURE (c: TrapCleaner) Cleanup
EMPTY
Performs cleanup operations as part of the trap handler.


TYPE Type
[untagged]
Information about a Component Pascal TYPE.
The pointer to the type's n-th method is at negative offset −4 * (n+1).

size-: INTEGER
The size of a RECORD, the number of elements in an ARRAY, 0 for a dynamic ARRAY, or the signature fingerprint for a PROCEDURE.
Multi-dimensional static ARRAYs are treated as one-dimensional arrays of ARRAYs.

mod-: Module
The type's module.

id-: INTEGER
Name index * 256  +  Level * 16  +  Attributes * 4  +  Form.
	Form: 1 = record, 2 = array, 3 = pointer.
	Attributes: 0 = final, 1 = EXTENSIBLE, 2 = LIMITED, 3 = ABSTRACT.
	Level: For RECORDs the extension level, for dynamic ARRAYs the number of dimensions
	Name index: its start position in mod.names.

base-: ARRAY 16 OF Type
	For records: Array of pointers to descriptors of its ancestor types.
	For arrays: base[0] points to the descriptor of its element's type, or the code of a basic CP type.
	For pointers: base[0] points to the descriptor of its target type

fields-: Directory
List of fields in declaration order.

ptroffs-: ARRAY OF INTEGER
For records: The list of fields of displacement-pointers. It is used by the garbage collector. The end of the list is indicated by a negative value.


TYPE Command
Procedure type used by several facilities.


TYPE Handler
Procedure type.


TYPE Identifier
ABSTRACT
Search criteria for ThisFinObj.

typ: INTEGER
The search is restricted to objects with this type tag.

obj-: ANYPTR
Set to point to objects found matching this type tag.

PROCEDURE (VAR id: Identifier) Identified (): BOOLEAN
ABSTRACT
Called successively for objects matching this type tag. It should return TRUE when the desired one is found.


TYPE ItemAttr
Item attributes. Used by module Meta to support meta programming.

obj, vis, typ, adr: INTEGER
mod: Module
desc: Type
ptr: SYSTEM.PTR
ext: ItemExt
Refer to module Meta for more information.


TYPE Name
String type used for names. Contents must be null (0X) terminated.


TYPE TryHandler = PROCEDURE (a, b, c: INTEGER)
The type of procedure that can be called with a local trap handler by means of Try.


TYPE Utf8Name
Short string type used for names. Contents is in UTF-8 format and null (0X) terminated.


VAR err-, val-: INTEGER
Information about the last exception; an error code err and possibly additional information in val.

	err		val	Comment
	< 0	Exception # |err|		e.g. DLL error
	129	Invalid WITH
	130	Invalid CASE
	131	Function without RETURN
	132	Type guard
	133	Implied type guard
	134	Value out of range
	135	Index out of range
	136	String too long
	137	Stack overflow
	138	Integer overflow
	139	Division by zero
	140	Infinite REAL result
	141	REAL underflow
	142	REAL overflow
	143	Undefined REAL result	FPU CW, FPU SW
	144	Not a number
	200	Keyboard interrupt
	201	NIL dereference
	202	Illegal instruction	The instruction code
	203	Illegal memory read	The illegal address
	204	Illegal memory write	The illegal address
	205	Illegal execution	The illegal address
	257	Out of memory
	10001H	Bus error
	10002H	Address error
	10007H	FPU error

fp-: INTEGER
Pointer to the stack frame when the last exception occurred.


mainWnd: INTEGER
Handle of the main Window.


modList-: Module
Root of the list of modules that have been loaded.
It contains descriptors of the modules, including those already unloaded. 


pc-: INTEGER
Instruction pointer (program counter) when the last exception occurred.


sp-: INTEGER
Stack pointer when the last exception occurred.


stack-: INTEGER
Pointer to the beginning of the stack when the last exception occurred.


trapCount-: INTEGER
The number of exceptions that have occurred since the application started.


watcher: PROCEDURE (event: INTEGER);
Procedure used for watching the memory management if the internal flag debug is set.
event = 1: Collect
event = 2: FastCollect
event = 3: allocate memory


PROCEDURE AddRef (p: INTEGER): INTEGER
Adds a reference to p.


PROCEDURE AllocModMem (descSize, modSize: INTEGER; VAR descAdr, modAdr: INTEGER)
Asks the operating system for memory blocks for a loadable module.
descSize is the size of the description section, modSize is the size of the data section and the code.
descAdr & modAdr are set to pointers to these memory blocks.


PROCEDURE Allocated (): INTEGER
Returns the amount of memory allocated to the BlackBox heap, in bytes.


PROCEDURE Beep
Emit a short beep sound. (Use Dialog.Beep!)


PROCEDURE Call (adr: INTEGER; sig: Signature; IN par: ARRAY OF INTEGER; n: INTEGER): LONGINT
Calls the procedure with the specified address adr, signature sig, and parameters par and returns the result cast into a LONGINT. The length of the parameter array is specified in n.


PROCEDURE Cleanup
Executes the do Commands of all the registered TrapCleaners.


PROCEDURE Collect
Performs a garbage collection.and calls the Finalizers of unreachable finalizable objects. Garbage collection uses the mark-and-sweep approach with refinements for oject finalization, and COM support.
The sequence of steps performed by Collect is:
(1) mark all global variables. The information for the global roots is precisely available from the module list. The information for pointers inside of records and arrays is available from the related type descriptor. Marking is done using a non-recursive algorithm. The chain for returning to the parent(s) of a referenced block is maintained by pointer reversals inside the marked blocks. When marking finishes, all pointer reversals are reset and the reachable memory blocks have a mark flag set (ODD(typeTag)).
(2) mark all local (stack based) variables. Since there are no type descriptors available for stack frames, this phase uses a so-called conservative approach. It marks all memory blocks reachable from any local variable no matter if it is a pointers or not. In order to avoid memory corruption, it collects the possible candidates first in an auxiliary array and scans the memory for deciding if a candidate is a heap block or not. By sorting the candidate array by ascending addresses it is possible to check the whole array in one scan. This approach guarantees that all blocks reachable via local variables are marked indeed but it can lead to marking blocks of memory that in reality cannot be reached. That's why this approach is called conservative.
(3) check for finalizable objects: scans the list of finalizable objects for unmarked objects and moves them to the list of objects that can be finalized now (hotFinalizers). This list is then marked in order to keep the finalizable objects (and everything reachable from them) from being freed in the following sweep phase.
(4) sweep: sequential scan over the whole memory for resetting the mark flag of reachable blocks and inserting unreachable blocks into the free list. This phase also merges adjacent free blocks into bigger blocks. The objects in hotFinalizers are not yet freed since they are marked. After sweeping the memory is again in a consistent state ready for executing arbitrary user programs.
(5) call finalizers: calls the FINALIZE method for all entries in hotFinalizers (unless the related module has been unloaded). A FINALIZE method is not restricted in any way by the needs of the memory managament. It can even re-establishes a reference to itself or anything reachable from itself in a global variable. It will, however, only be finalized once. In addition this phase calls Release for all affected COM interface records. This decrements the reference count of the COM interface object to zero and releases it.

The efficiency of garbage collection depends on the number of roots and reachable blocks during the mark phase, the stack size and number of candidates encountered when marking local variables, the number of reachable, unreachable and free blocks visited in the sweep phase and the efficiency of the finalizers.


PROCEDURE DeallocModMem (descSize, modSize, descAdr, modAdr: INTEGER)
Deallocates the memory blocks for a loaded module.
descSize is the size of the description section, modSize is the size of the data section and the code.
descAdr & modAdr are the pointers to these memory blocks.


PROCEDURE FastCollect
Performs a garbage collection without calling any Finalizers.
Objects with Finalizers are not deallocated, but remain queued until the next Collect.


PROCEDURE FatalError (id: INTEGER; str: ARRAY OF CHAR)
Immediately terminates the application process in the case of a fatal error.
The error number is id, and str is the associated comment.


PROCEDURE GetLoaderResult (OUT res: INTEGER; OUT importing, imported, object: ARRAY OF CHAR)
Returns the result of the last attempt to load the module (for the current thread).
res is set to one of the loader constants defined above.


PROCEDURE GetModName (mod: Module; OUT name: Name)
Sets name to the name of the module mod.


PROCEDURE GetObjName (mod: Module; obj: Object; OUT name: Name)
Returns the name, in name, of the object obj in the module mod.


PROCEDURE GetRefProc (VAR ref: INTEGER; OUT adr: INTEGER; OUT name: Utf8Name)
Returns the symbol information of the next procedures in a module and sets ref to the next symbol.
To scan all the module's procedures initialize ref with mod.refs and call GetRefProc until adr = 0.
For each procedure adr is set to the offset from the module's code section (mod.code), and name is set to the procedure's name.


PROCEDURE GetRefVar (VAR ref: INTEGER; OUT mode, form: SHORTCHAR; OUT desc: Type; OUT adr: INTEGER; OUT name: Utf8Name)
Returns the symbol information of the next variable in a module or the next local variable in a stack frame and sets ref to the next symbol.
mode: 1X = global variable, local variable, value parameter; 3X = reference parameter (VAR, IN, OUT)
form: cf. DevDebug.WriteName
desc: type descriptor for structured types
adr: address relative to module data or stack frame.
To scan all global variables of a module set ref to mod.refs and call GetRefVar while mode = 1X.
To scan all local variables of a procedure use ref as returned by GetRefProc and call GetRefVar until mode = 0X.
??? needs to be checked and completed


PROCEDURE GetTypeName (t: Type; VAR name: Name)
Returns the name of the type t.


PROCEDURE InstallCleaner (p: Command)
Registers a Command p, which will be assigned to the do Command of a new Cleaner, and added to the Cleaners list.
These Commands are invoked when Cleanup is called.
A Cleaner Command might reset database pointers for example.


PROCEDURE [code] InstallExcp (VAR e: ExcpFrame)
Installs an exception handler for the current stack frame.


PROCEDURE InstallReducer (r: Reducer)
Adds r to the Reducers list.
Reducers are only used once, then they are removed from the list (they may re-register themselves).


PROCEDURE InstallTrapChecker (h: Handler)
Sets h to be the trap checker. It will be called when a Command Traps.
Used by module Views to invalidate views that initiate traps.


PROCEDURE InstallTrapViewer (h: Handler)
Sets h to be the trap checker. It will be called when a Command Traps.
This is the procedure that implements the trap Window and any associated functionality.
Simple and more advanced viewers are registered by the modules StdDebug & DevDebug.


PROCEDURE InterfaceTrapHandler (excpRec, estFrame, context, dispCont: INTEGER): INTEGER
[specific to Direct-To-COM] 
Used for exception handling in COM. Access to it is generated by the BlackBox compiler. Not intended for use by developers.


PROCEDURE IsAlpha (ch: CHAR): BOOLEAN
Checks if ch is an alphabetical character, rather than a digit or symbol.


PROCEDURE IsLower (ch: CHAR): BOOLEAN
Checks if ch is a lower case alphabetical character.


PROCEDURE IsReadable (from, to: INTEGER): BOOLEAN
Check whether the memory between from (inclusive) and to (exclusive) may be read.


PROCEDURE IsUpper (ch: CHAR): BOOLEAN
Checks if ch is an upper case alphabetical character.


PROCEDURE LevelOf (t: Type): SHORTINT
Returns the extension level (i.e. the number of basic types in the hierarchy) to type t.


PROCEDURE LoadDll (IN name: ARRAY OF CHAR; VAR ok: BOOLEAN)
Loads into memory the dynamic library named name. ok reports if this was successful.


PROCEDURE LoadMod (IN name: ARRAY OF CHAR)
Loads into memory the module named name. 


PROCEDURE Lower (ch: CHAR): CHAR
Returns the lower case character corresponding to ch.


PROCEDURE MakeFileName (VAR name: ARRAY OF CHAR; type: ARRAY OF CHAR)
(Usually) Ensures that the file name name includes an extension.
If name already has a non-empty extension it is unaltered.
If name has an empty extension (i.e. its first "." is its last character) it is truncated prior to this ".".
If type is "" it is given the extension "odc", otherwise it is given the extension type, which should not include the leading "." - not checked.
Uppercase letters in type are converted to lower case.

Pre
	LEN (type$)  ≤ 7.  Not explicitly checked.


PROCEDURE NewArr (eltyp, nofelem, nofdim: INTEGER): INTEGER
Supports the NEW operation for dynamic arrays.
Creates a new array with the base elements of type eltyp, with total number of elements nofelem (defined as the product of the lengths of all dimensions of the array), and with nofdim dimensions.
If the element type is a COM interface pointer or if it contains COM interface pointers (ODD(eltyp)) the allocated memory block is inserted into the list of finalizable objects, which means that an additional memory block is allocated.
The values for eltyp are:
	eltyp	Type	Comment
	-1	COM Interface pointer	Supports the COM compiler
	0	POINTER
	1	SHORTCHAR
	2	SHORTINT
	3	BYTE
	4	INTEGER
	5	BOOLEAN
	6	SET
	7	SHORTREAL
	8	REAL
	9	CHAR
	10	LONGINT
	11	PROCEDURE
	12	Untagged POINTER
	ELSE	Element Type	ODD(eltyp) if COM interface pointers inside


PROCEDURE NewObj (VAR o: SYSTEM.PTR; t: Type)
Supports the Meta.Item.New operation for RECORDs.
Based on calling NewRec o is set to a pointer to the new object of type t.
If t.size = −1 or if the memory is exhausted o is set to NIL.
If t contains any COM interface pointers, calls NewRec with t + 1, i.e. ODD(t).


PROCEDURE NewRec (typ: INTEGER): INTEGER
Supports the NEW operation for RECORDs.
Creates a new record of type typ, and returns the address of the data section.
The address of the record's type descriptor is at offset -4.
If the memory is exhausted it returns 0.
If the record provides a FINALIZEr or if it contains COM interface pointers (ODD(typ)), 
the allocated record is inserted into the list of finalizable objects, 
which means that an additional memory block is allocated.


PROCEDURE PopTrapCleaner (c: TrapCleaner)
Deletes all the TrapCleaners on the TrapCleaner list prior to c.


PROCEDURE PushTrapCleaner (c: TrapCleaner)
Inserts c to the front of the TrapCleaner list.

Pre
20	c is not already on the list.


PROCEDURE Quit (exitCode: INTEGER)
Exits the application.
Calls the terminators of all the modules on the module list.
Calls all the 'hot' Finalizers, then all the other Finalizers.
Calls WinApi.ExitProcess with parameter exitCode.


PROCEDURE RegisterMod (mod: Module)
Initialises the module mod after it has been loaded into memory.


PROCEDURE Release (p: INTEGER): INTEGER
Removes a reference to p.


PROCEDURE Release2 (p: INTEGER): INTEGER
???


PROCEDURE RemoveCleaner (p: Command)
Removes a previously registered Cleaner (the one with do Command equal to p) from the Cleaners list.


PROCEDURE [code] RemoveExcp (VAR e: ExcpFrame)
Removes the specified exception handler.


PROCEDURE Root (): INTEGER
Returns the pointer to the root of the of the clusters comprising heap BlackBox's heap.


PROCEDURE SearchProcVar (var: INTEGER; VAR m: Module; VAR adr: INTEGER)
Returns the module m, and relative address offset adr (from m.code) of the symbol with address var.


PROCEDURE SetTrapGuard (on: BOOLEAN)
If called with on = TRUE subsequent TRAP displays are inhibited.


PROCEDURE SourcePos (mod: Module; codePos: INTEGER): INTEGER
Returns the position in the source code of Module mod for the instruction at address codePos.


PROCEDURE SplitName (name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR)
Splits the input name into two parts head and tail.
name is scanned for either a lower case to upper case  transition, or for a ".".
The text before the transition or "." is copied to head, the text after is copied to tail (the "." is discarded).
If this leaves tail empty then the text in head is moved to tail.


PROCEDURE Start (code: Command)
Called upon start of a BlackBox application.
Defines the stack base and initiates the Command code, which must never return.
The stack base is used by the garbage collector and by the trap handler.


PROCEDURE StringToUtf8 (IN in: ARRAY OF CHAR; OUT out: ARRAY OF SHORTCHAR; OUT res: INTEGER)
Copies the string from in to out while converting it from 16-bit Unicode to UTF-8 format.
Sets res to 0 if successful, or to 1 if the output needed to be truncated.


PROCEDURE ThisCommand (mod: Module; IN name: ARRAY OF CHAR): Command
Returns a pointer the Command (a parameterless PROCEDURE) in the module mod with name name.


PROCEDURE ThisDesc (mod: Module; fprint: INTEGER): Object
Returns a pointer to the object with fingerprint fprint in the module mod.


PROCEDURE ThisDllObj (mode, fprint: INTEGER; IN dll, name: ARRAY OF SHORTCHAR): INTEGER
Returns the address of the procedure called name in the DLL dll.
Currently mode must be set to 4 to indicate a procedure (rather than constant = 1, type = 2, variable = 3, or field = 5) or 0 is returned.
Currently fprint is ignored.


PROCEDURE ThisField (rec: Type; IN name: ARRAY OF CHAR): Object
Returns a pointer to the object within rec called name.


PROCEDURE ThisFinObj (VAR id: Identifier): ANYPTR
Searches the list of Finalizers until one contains a Block recognized by the Identifier id.
If found, the Block's last element is returned.


PROCEDURE ThisLoadedMod (IN name: ARRAY OF CHAR): Module
Returns a pointer to the module named name, provided it is already loaded. Otherwise it returns NIL.


PROCEDURE ThisMod (IN name: ARRAY OF CHAR): Module
Returns a pointer to the module named name. If the module is not loaded, it loads it.


PROCEDURE ThisObject (mod: Module; IN name: ARRAY OF CHAR): Object
Returns a pointer to the object in the module mod called name.


PROCEDURE ThisType (mod: Module; IN name: ARRAY OF CHAR): Type
Returns a pointer to the type in the module mod called name.


PROCEDURE Time (): LONGINT
Returns the current time since the system (the PC) was started in clock ticks.
These ticks have a resolution of timeResolution (1000) ticks per second.


PROCEDURE Try (h: TryHandler; a, b, c: INTEGER)
Calls the procedure h with parameters a, b, and c with a local trap handler.
If a trap occurs inside h a trap window is displayed and h is terminated but the execution is continued as if Try proceeded normally.


PROCEDURE TypeOf (IN rec: ANYREC): Type
Returns a pointer to the type descriptor of the record rec.


PROCEDURE UnloadMod (mod: Module)
Unloads the module mod, provided than no other loaded modules import it.


PROCEDURE Upper (ch: CHAR): CHAR
Returns the upper case character corresponding to ch.


PROCEDURE Used (): INTEGER
Returns the amount of memory allocated to the system heap, in bytes.


PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR; OUT res: INTEGER)
Copies the string from in to out while converting it from UTF-8 format to 16-bit Unicode.
Sets res to 0 if successful, or to 1 if the output needed to be truncated.
If a format error is detected in in, it is copied to out and res is set to 2.


PROCEDURE WouldFinalize (): BOOLEAN
Indicates if there are any objects that are ready to be deallocated, but have not yet had their Finalizers called.

This module has a private interface, it is only used internally.