# MicroEJ Core Engine¶

The MicroEJ Core Engine and its components represent the core of the Architecture. It is used to compile and execute at runtime the MicroEJ Application code.

## Functional Description¶

The following diagram shows the overall process. The first two steps are performed within the MicroEJ Workbench. The remaining steps are performed within the C IDE.

MicroEJ Core Engine Flow

1. Step 1 consists in writing a MicroEJ Application against a set of Foundation Libraries available in the platform.
2. Step 2 consists in compiling the MicroEJ Application code and the required libraries in an ELF library, using the SOAR.
3. Step 3 consists in linking the previous ELF file with the MicroEJ Core Engine library and a third-party BSP (OS, drivers, etc.). This step may require a third-party linker provided by a C toolchain.

## Architecture¶

The MicroEJ Core Engine and its components have been compiled for one specific CPU architecture and for use with a specific C compiler.

The architecture of the platform engine is called green thread architecture, it runs in a single RTOS task. Its behavior consists in scheduling MicroEJ threads. The scheduler implements a priority preemptive scheduling policy with round robin for the MicroEJ threads with the same priority. In the following explanations the term “RTOS task” refers to the tasks scheduled by the underlying OS; and the term “MicroEJ thread” refers to the Java threads scheduled by the MicroEJ Core Engine.

The activity of the platform is defined by the MicroEJ Application. When the MicroEJ Application is blocked (when all MicroEJ threads are sleeping), the platform sleeps entirely: The RTOS task that runs the platform sleeps.

The platform is responsible for providing the time to the MicroEJ world: the precision is 1 millisecond.

## Capabilities¶

MicroEJ Core Engine defines 3 exclusive capabilities:

• Mono-sandbox: capability to produce a monolithic firmware (default one).
• Multi-Sandbox: capability to produce a extensible firmware on which new applications can be dynamically installed. See section Multi-Sandbox.
• Tiny application: capability to produce a compacted firmware (optimized for size). See section Tiny Application.

All MicroEJ Core Engine capabilities may not be available on all architectures. Refer to section Supported MicroEJ Core Engine Capabilities by Architecture Matrix for more details.

## Implementation¶

The MicroEJ Core Engine implements the [SNI] specification. It is created and initialized with the C function SNI_createVM. Then it is started and executed in the current RTOS task by calling SNI_startVM. The function SNI_startVM returns when the MicroEJ Application exits or if an error occurs (see section Error Codes). The function SNI_destroyVM handles the platform termination.

The file LLMJVM_impl.h that comes with the platform defines the API to be implemented. See section LLMJVM: MicroEJ Core Engine.

### Initialization¶

The Low Level MicroEJ Core Engine API deals with two objects: the structure that represents the platform, and the RTOS task that runs the platform. Two callbacks allow engineers to interact with the initialization of both objects:

• LLMJVM_IMPL_initialize: Called once the structure representing the platform is initialized.
• LLMJVM_IMPL_vmTaskStarted: Called when the platform starts its execution. This function is called within the RTOS task of the platform.

### Scheduling¶

To support the green thread round-robin policy, the platform assumes there is an RTOS timer or some other mechanism that counts (down) and fires a call-back when it reaches a specified value. The platform initializes the timer using the LLMJVM_IMPL_scheduleRequest function with one argument: the absolute time at which the timer should fire. When the timer fires, it must call the LLMJVM_schedule function, which tells the platform to execute a green thread context switch (which gives another MicroEJ thread a chance to run).

### Idle Mode¶

When the platform has no activity to execute, it calls the LLMJVM_IMPL_idleVM function, which is assumed to put the RTOS task of the platform into a sleep state. LLMJVM_IMPL_wakeupVM is called to wake up the platform task. When the platform task really starts to execute again, it calls the LLMJVM_IMPL_ackWakeup function to acknowledge the restart of its activity.

### Time¶

The platform defines two times:

• the application time: The difference, measured in milliseconds, between the current time and midnight, January 1, 1970, UTC.
• the system time: The time since the start of the device. This time is independent of any user considerations, and cannot be set.

The platform relies on the following C functions to provide those times to the MicroEJ world:

• LLMJVM_IMPL_getCurrentTime: Depending on the parameter (true / false) must return the application time or the system time. This function is called by the MicroEJ method System.currentTimeMillis(). It is also used by the platform scheduler, and should be implemented efficiently.
• LLMJVM_IMPL_getTimeNanos: must return the system time in nanoseconds.
• LLMJVM_IMPL_setApplicationTime: must set the difference between the current time and midnight, January 1, 1970, UTC.

### Error Codes¶

The C function SNI_createVM returns a negative value if an error occurred during the MicroEJ Core Engine initialization or execution. The file LLMJVM.h defines the platform-specific error code constants. The following table describes these error codes.

MicroEJ Core Engine Error Codes
Error Code Meaning
0 The MicroEJ Application ended normally (i.e., all the non-daemon threads are terminated or System.exit(exitCode) has been called). See section Exit Codes.
-1 The microejapp.o produced by SOAR is not compatible with the MicroEJ Core Engine (microejruntime.a). The object file has been built from another MicroEJ Platform.
-2 Internal error. Invalid link configuration in the MicroEJ Architecture or the MicroEJ Platform.
-3 Evaluation version limitations reached: termination of the application. See section Limitations.
-5 Not enough resources to start the very first MicroEJ thread that executes main method. See section Option(text): Java heap size (in bytes).
-12 Number of threads limitation reached. See sections Limitations and Option(text): Number of threads.
-13 Fail to start the MicroEJ Application because the specified MicroEJ heap is too large or too small. See section Option(text): Java heap size (in bytes).
-14 Invalid MicroEJ Application stack configuration. The stack start or end is not eight-byte aligned, or stack block size is too small. See section Option(text): Number of blocks in pool.
-16 The MicroEJ Core Engine cannot be restarted.
-17

The MicroEJ Core Engine is not in a valid state because of one of the following situations:

• SNI_startVM called before SNI_createVM.
• SNI_startVM called while the MicroEJ Appplication is running.
• SNI_createVM called several times.
-18 The memory used for the MicroEJ heap or immortal heap does not work properly. Read/Write memory checks failed. This may be caused by an invalid external RAM configuration. Verify _java_heap and _java_immortals sections locations.
-19 The memory used for the MicroEJ Application static fields does not work properly. Read/Write memory checks failed. This may be caused by an invalid external RAM configuration. Verify .bss.soar section location.
-20 KF configuration internal error. Invalid link configuration in the MicroEJ Architecture or the MicroEJ Platform.
-21 Number of monitors per thread limitation reached. See sections Limitations and Options .
-22 Internal error. Invalid FPU configuration in the MicroEJ Architecture.
-23 The function LLMJVM_IMPL_initialize defined in the Abstraction Layer implementation returns an error.
-24 The function LLMJVM_IMPL_vmTaskStarted defined in the Abstraction Layer implementation returns an error.
-25 The function LLMJVM_IMPL_shutdown defined in the Abstraction Layer implementation returns an error.

### Example¶

The following example shows how to create and launch the MicroEJ Core Engine from the C world. This function (microej_main) should be called from a dedicated RTOS task.

#include <stdio.h>
#include "microej_main.h"
#include "LLMJVM.h"
#include "sni.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
* @brief Creates and starts a MicroEJ instance. This function returns when the MicroEJ execution ends.
*/
void microej_main(int argc, char **argv)
{
void* vm;
int32_t err;
int32_t exitcode;

// create VM
vm = SNI_createVM();

if(vm == NULL)
{
printf("MicroEJ initialization error.\n");
}
else
{
printf("MicroEJ START\n");

// Error codes documentation is available in LLMJVM.h
err = SNI_startVM(vm, argc, argv);

if(err < 0)
{
// Error occurred
if(err == LLMJVM_E_EVAL_LIMIT)
{
printf("Evaluation limits reached.\n");
}
else
{
printf("MicroEJ execution error (err = %d).\n", err);
}
}
else
{
// VM execution ends normally
exitcode = SNI_getExitCode(vm);
printf("MicroEJ END (exit code = %d)\n", exitcode);
}

// delete VM
SNI_destroyVM(vm);
}
}

#ifdef __cplusplus
}
#endif


### Dump the States of the Core Engine¶

The internal MicroEJ Core Engine function called LLMJVM_dump allows you to dump the state of all MicroEJ threads: name, priority, stack trace, etc. This function must only be called from the MicroJvm virtual machine thread context and only from a native function or callback. Calling this function from another context may lead to undefined behavior and should be done only for debug purpose.

This is an example of a dump:

=================================== VM Dump ====================================
Last executed native function: 0x90035E3D
Last executed external hook function: 0x00000000
State: running
--------------------------------------------------------------------------------
name="main" prio=5 state=RUNNING max_java_stack=456 current_java_stack=184

[email protected]:
at (native) [0x90003F65]
at com.microej.demo.widget.main.MainPage.getContentWidget(MainPage.java:95)
Object References:
- [email protected]
- [email protected]
- [email protected]
- [email protected]
Object References:
- [email protected]
Object References:
- [email protected]
- [email protected]
Object References:
- [email protected]
Object References:
- j[email protected]
Object References:
- [email protected]
--------------------------------------------------------------------------------
name="UIPump" prio=5 state=WAITING timeout(ms)=INF max_java_stack=120 current_java_stack=117
external event: status=waiting

[email protected]:
Object References:
- [email protected]
at ej.microui.MicroUIPump.run(MicroUIPump.java:176)
Object References:
- [email protected]
Object References:
- [email protected]
Object References:
- [email protected]
--------------------------------------------------------------------------------

[email protected]:
Object References:
- [email protected]
================================================================================

============================== Garbage Collector ===============================
State: Stopped
Last analyzed object: null
Total memory: 15500
Current allocated memory: 7068
Current free memory: 8432
Allocated memory after last GC: 0
Free memory after last GC: 15500
================================================================================

=============================== Native Resources ===============================
Id         CloseFunc  Owner            Description
--------------------------------------------------------------------------------
================================================================================


See Stack Trace Reader for additional info related to working with VM dumps.

#### Dump The State Of All MicroEJ Threads From A Fault Handler¶

It is recommended to call the LLMJVM_dump API as a last resort in a fault handler. Calling LLMJVM_dump is undefined if the VM is not paused. The call to LLMJVM_dump MUST be done last in the fault handler.

#### Trigger VM Dump From Debugger¶

To trigger a VM dump from the debugger, set the PC register to the LLMJVM_dump physical memory address.

The symbol for the LLMJVM_dump API is defined in the header file LLMJVM.h. Search for this symbol in the appropriate C toolchain .map file.

Note

LLMJVM_dump (in LLMJVM.h) needs to be called explicitly. A linker optimization may remove the symbol if it is not used anywhere in the code.

Requirements:

• Embedded debugger is attached and the processor is halted in an exception handler.
• A way to read stdout (usually UART).

### Check Internal Structure Integrity¶

The internal MicroEJ Core Engine function called LLMJVM_checkIntegrity checks the internal structure integrity of the MicroJvm virtual machine and returns its checksum.

• If an integrity error is detected, the LLMJVM_on_CheckIntegrity_error hook is called and this method returns 0.
• If no integrity error is detected, a non-zero checksum is returned.

This function must only be called from the MicroJvm virtual machine thread context and only from a native function or callback. Calling this function multiple times in a native function must always produce the same checksum. If the checksums returned are different, a corruption must have occurred.

Please note that returning a non-zero checksum does not mean the MicroJvm virtual machine data has not been corrupted, as it is not possible for the MicroJvm virtual machine to detect the complete memory integrity.

MicroJvm virtual machine internal structures allowed to be modified by a native function are not taken into account for the checksum computation. The internal structures allowed are:

• basetype fields in Java objects or content of Java arrays of base type,
• internal structures modified by a LLMJVM function call (e.g. set a pending Java exception, suspend or resume the Java thread, register a resource, …).

This function affects performance and should only be used for debug purpose. A typical use of this API is to verify that a native implementation does not corrupt the internal structures:

void Java_com_mycompany_MyClass_myNativeFunction(void) {
int32_t crcBefore = LLMJVM_checkIntegrity();
myNativeFunctionDo();
int32_t crcAfter = LLMJVM_checkIntegrity();
if(crcBefore != crcAfter){
// Corrupted MicroJVM virtual machine internal structures
while(1);
}
}


## Generic Output¶

The System.err stream is connected to the System.out print stream. See below for how to configure the destination of these streams.

## Dependencies¶

The MicroEJ Core Engine requires an implementation of its low level APIs in order to run. Refer to the chapter Implementation for more information.

## Installation¶

The MicroEJ Core Engine and its components are mandatory. In the platform configuration file, check Multi Applications to install the MicroEJ Core Engine in “Multi-Sandbox” mode. Otherwise, the “Single application” mode is installed.

## Use¶

The EDC API Module must be added to the module.ivy of the MicroEJ Application Project. This MicroEJ module is always required in the build path of a MicroEJ project; and all others libraries depend on it. This library provides a set of options. Refer to the chapter Application Options which lists all available options.

<dependency org="ej.api" name="edc" rev="1.3.3"/>


The BON API Module must also be added to the module.ivy of the MicroEJ Application project in order to access the [BON] library.

<dependency org="ej.api" name="bon" rev="1.4.0"/>