cldc hotspot architecture

80
Sun Microsystems, Inc. www.sun.com CLDC HotSpot™ Implementation Architecture Guide CLDC HotSpot Implementation, Version 1.1.3 Java™ ME Platform July 2006

Upload: zdmilan

Post on 22-Apr-2015

2.959 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Cldc Hotspot Architecture

Sun Microsystems, Inc.www.sun.com

CLDC HotSpot™ ImplementationArchitecture Guide

CLDC HotSpot Implementation, Version 1.1.3

Java™ ME Platform

July 2006

Page 2: Cldc Hotspot Architecture

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. Inparticular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed athttp://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries.

Unpublished - rights reserved under the Copyright Laws of the United States.

THIS PRODUCT CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF SUN MICROSYSTEMS, INC. USE,DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR EXPRESS WRITTEN PERMISSION OF SUN MICROSYSTEMS,INC.

U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement andapplicable provisions of the FAR and its supplements. This distribution may include materials developed by third parties.

Sun, Sun Microsystems, the Sun logo, Java, HotSpot, JDK, and the Java Coffee Cup logo are trademarks or registered trademarks of SunMicrosystems, Inc. in the U.S. and other countries.

Products covered by and information contained in this service manual are controlled by U.S. Export Control laws and may be subject to theexport or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whetherdirect or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusionlists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited.

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.

Sun Microsystems, Inc. a les droits de propriété intellectuels relatants à la technologie incorporée dans le produit qui est décrit dans cedocument. En particulier, et sans la limitation, ces droits de propriété intellectuels peuvent inclure un ou plus des brevets américains énumérésà http://www.sun.com/patents et un ou les brevets plus supplémentaires ou les applications de brevet en attente dans les Etats - Unis etdans les autres pays.

Non publie - droits réservés selon la législation des Etats-Unis sur le droit d’auteur.

CE PRODUIT CONTIENT DES INFORMATIONS CONFIDENTIELLES ET DES SECRETS COMMERCIAUX DE SUN MICROSYSTEMS, INC.SON UTILISATION, SA DIVULGATION ET SA REPRODUCTION SONT INTERDITES SANS L AUTORISATION EXPRESSE, ECRITE ETPREALABLE DE SUN MICROSYSTEMS, INC. Cette distribution peut comprendre des composants développés par des tierces parties.

Sun, Sun Microsystems, le logo Sun, Java, HotSpot, JDK, et le logo Java Coffee Cup sont des marques de fabrique ou des marques déposées deSun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.

Les produits qui font l'objet de ce manuel d'entretien et les informations qu'il contient sont regis par la législation américaine en matière decontrôle des exportations et peut être soumis à la règlementation en vigueur dans d'autres pays dans le domaine des exportations etimportations. Les utilisations finales, ou utilisateurs finaux, pour des armes nucléaires,des missiles, des armes biologiques et chimiques ou dunucléaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou réexportations vers les pays sous embargoaméricain, ou vers des entités figurant sur les listes d'exclusion d'exportation américaines, y compris, mais de manière non exhaustive, la listede personnes qui font objet d'un ordre de ne pas participer, d'une façon directe ou indirecte, aux exportations des produits ou des services quisont régis par la législation américaine en matière de contrôle des exportations et la liste de ressortissants spécifiquement désignés, sontrigoureusement interdites.

Page 3: Cldc Hotspot Architecture

Contents

Preface xiii

1. CLDC HotSpot Implementation Virtual Machine 1–1

1.1 Processor and Memory Requirements 1–3

1.2 Compilation Performance 1–3

1.2.1 Faster Execution Consumes Less Power 1–4

2. Technical Overview 2–1

2.0.1 Portable Architecture 2–2

2.0.2 Dynamic Compiler 2–2

2.0.3 Optimized Interpreter 2–3

2.0.4 Lightweight Threading System 2–3

2.0.5 Compact Object Layout 2–4

2.0.6 Unified Resource Management 2–5

2.0.7 Generational Garbage Collection 2–6

2.0.8 Dedicated Heap Area for Compiled Code 2–6

2.0.9 Multitasking Support 2–7

2.0.10 Faster Virtual Machine Startup With Ahead-of-Time Compilation2–7

2.0.11 Faster Application Startup With In-Place Execution 2–8

2.0.12 Fast Synchronization 2–8

iii

Page 4: Cldc Hotspot Architecture

2.0.13 Integrated Class Prelinker 2–8

2.0.14 Fully Object-Oriented Internal Design and Upwards Scalability2–9

2.1 Additional Components 2–9

2.2 New Technical Features in This Release 2–10

2.2.1 In-Place Execution in Multitasking Mode 2–10

2.2.2 Multiple Profile Support 2–11

2.2.3 Dynamic Native Method Support 2–11

2.2.4 Vector Floating Point Support 2–11

2.2.5 Incremental JAR File Reader 2–11

2.2.6 Interpreter-Only Mode 2–12

2.2.7 Improved Debugger Support With Commercial IDEs 2–12

3. Heap Architecture andGarbage Collection 3–1

3.1 Garbage Collection 3–1

3.1.1 Structure of the Heap 3–2

3.1.2 Tracking Pointers Across Generations 3–2

3.1.3 Fast Allocation 3–2

4. Dynamic Compiler 4–1

4.1 Code Set Management 4–1

4.2 Tuning the Dynamic Compiler 4–2

5. Threading System 5–1

5.1 Long-Running Compared With Blocking Native Methods 5–1

5.2 Coding Styles for Long-Running Native Methods 5–2

5.3 Non-Blocking Scheduling Coding Style 5–3

5.4 Hybrid Threading Coding Style 5–5

6. Multitasking 6–1

iv CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 5: Cldc Hotspot Architecture

6.1 Introduction 6–1

6.1.1 Isolates 6–2

6.1.1.1 Example Program 6–2

6.1.2 Multitasking in MIDP 2.0 6–3

6.1.3 Reduced Isolate API 6–5

6.2 Isolate Implementation 6–5

6.2.1 Virtualization of Static Variables 6–5

6.2.2 Static Class Initialization 6–5

6.2.3 Isolate Creation 6–7

6.2.4 Synchronization 6–8

6.2.4.1 Synchronization of Java Classes 6–8

6.2.4.2 Synchronization of Interned String Objects 6–8

6.2.5 Resource Management 6–8

6.2.5.1 Scheduling and Priorities 6–9

6.2.5.2 Object Heap Sharing 6–9

6.2.6 JSR 121 6–9

7. Ahead-of-Time Compilation Support 7–1

7.1 Methods Eligible for AOT Compilation 7–1

7.2 Choosing Methods to AOT Compile 7–1

7.3 AOT Compilation of Downloaded Classes 7–2

8. In-Place Execution 8–1

8.1 Design Overview 8–1

8.2 Security Considerations 8–1

8.2.1 Storing Application Image Files 8–2

8.2.2 Warning Message 8–3

8.3 Integrating the In-Place Execution Feature 8–3

8.3.1 Running the Converter 8–3

Contents v

Page 6: Cldc Hotspot Architecture

8.3.2 Executing an Application Image 8–4

8.3.3 In-Place Execution Example 8–4

8.4 In-Place Execution from Flash 8–4

8.5 Experimenting With In-Place Execution 8–5

9. Jazelle Option for ARM Implementations 9–1

9.1 Flags to Enable Jazelle 9–1

10. ROMizer 10–1

10.1 Running the ROMizer 10–1

10.2 Requirement for System Classes 10–2

10.3 ROMizer Options 10–2

10.3.1 ROMizer Optimization Options 10–3

10.3.2 Example 10–8

10.4 Ahead-of-Time (AOT) Compilation 10–9

10.5 ROMizer Log File 10–10

11. Java Programming Language Debugging (KDWP) 11–1

11.1 KDWP Architecture 11–1

11.2 Debug Agent 11–3

11.2.1 Connections Between a Debuggerand CLDC HotSpot Implementation 11–3

11.2.2 Packet Processing 11–5

11.3 Debugger Support 11–6

11.3.1 Events 11–6

11.3.2 Breakpoints 11–7

11.3.3 Single Stepping 11–7

11.4 Using the Debug Agent and the JPDA Debugger 11–8

11.4.1 Starting a Debug Session 11–8

11.4.2 Debugging Example 11–10

vi CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 7: Cldc Hotspot Architecture

Index Index–1

Contents vii

Page 8: Cldc Hotspot Architecture

viii CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 9: Cldc Hotspot Architecture

Figures

FIGURE 1-1 Performance of Interpreted Mode Compared With Compiled Mode in CLDC HotSpotImplementation 1–4

FIGURE 2-1 Relationship Between Instance, Near Class, and Class 2–5

FIGURE 3-1 The CLDC HotSpot Implementation Two-Generational Garbage Collector 3–1

FIGURE 6-1 Multiple Java Program Event Queues 6–4

FIGURE 6-2 Isolate Creation 6–7

FIGURE 11-1 Java Programming Language Debugging Interface Architecture 11–2

FIGURE 11-2 Debugger and CLDC HotSpot Implementation Connections 11–4

ix

Page 10: Cldc Hotspot Architecture

x CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 11: Cldc Hotspot Architecture

Code Samples

CODE EXAMPLE 5-1 Coding With the Non-Blocking Scheduling Style 5-4

CODE EXAMPLE 5-2 Coding a Potentially Blocking Native Function 5-6

CODE EXAMPLE 6-1 isolate Constructor 6-3

xi

Page 12: Cldc Hotspot Architecture

xii CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 13: Cldc Hotspot Architecture

Preface

This book surveys the architecture of the Connected Limited Device ConfigurationHotSpot™ implementation virtual machine. CLDC HotSpot Implementation is ahigh-performance virtual machine that can be used as an execution engine for theConnected Limited Device Configuration platform.

Who Should Use This DocumentThis document is intended primarily for individuals and companies who want toport the CLDC HotSpot Implementation virtual machine to a new platform. It is alsoinvaluable for implementation engineers who wish to implement an entire Java™Platform, Micro Edition (Java ME) technology-based stack on top of the CLDCHotSpot Implementation virtual machine. The document is useful also to anyonewho wants to learn more about the internal details of the CLDC HotSpotImplementation virtual machine.

xiii

Page 14: Cldc Hotspot Architecture

How This Book Is OrganizedThis book has the following chapters:

Chapter 1 is a general overview of CLDC HotSpot Implementation.

Chapter 2 describes key ideas behind and components of CLDC HotSpotImplementation.

Chapter 3 describes the heap architecture and garbage collection features of CLDCHotSpot Implementation.

Chapter 4 describes the architecture of the dynamic, adaptive compiler of CLDCHotSpot Implementation.

Chapter 5 describes the threading system architecture of CLDC HotSpotImplementation.

Chapter 6 describes the multitasking feature of CLDC HotSpot Implementation.

Chapter 7 describes the ahead-of-time compilation feature of CLDC HotSpotImplementation.

Chapter 8 describes the in-place execution feature of CLDC HotSpotImplementation.

Chapter 9 describes the Jazelle support for ARM processors in CLDC HotSpotImplementation.

Chapter 10 describes the ROMizer utility of CLDC HotSpot Implementation, whichenables class compiled from the Java programming language to be linked directly inthe virtual machine.

Chapter 11 describes the support of Java programming language debuggingenvironments in CLDC HotSpot Implementation.

TerminologyThese terms related to the Java platform and Java technology are used throughoutthis manual.

Java techology-basedapplication (Java application)

class contained in aJava class file (Java class)

xiv CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 15: Cldc Hotspot Architecture

Java technology-based code (Java code)

Java programminglanguage debugger (Java debugger)

Java programminglanguage object heap (Java heap)

Java technology level (Java level)

Java technology-based object (Java object)

Java technology-basedpackages (Java packages)

Java programminglanguage profiler (Java profiler)

Java technology-basedprograms (Java programs)

thread in a Java virtualmachine representing a

Java programminglanguage thread (Java thread)

stack used by a Javathread (Java thread stack)

Related DocumentationThe CLDC HotSpot Implementation Virtual Machine, A Technical White Paper, SunMicrosystems, Inc. (2003), which can be downloaded fromhttp://java.sun.com/j2me/docs/.

Connected, Limited Device Configuration Specification, Version 1.0, Java CommunityProcess, Sun Microsystems, Inc., which can be downloaded fromhttp://www.jcp.org/en/jsr/detail?id=030.

Connected, Limited Device Configuration Specification, Version 1.1, Java CommunityProcess, Sun Microsystems, Inc, which can be downloaded fromhttp://www.jcp.org/en/jsr/detail?id=139.

The Java™ Language Specification (Java Series), Second Edition by James Gosling, BillJoy, Guy Steele, and Gilad Bracha (Addison-Wesley, 2000)

Preface xv

Page 16: Cldc Hotspot Architecture

The Java™ Virtual Machine Specification (Java Series), Second Edition by Tim Lindholmand Frank Yellin (Addison-Wesley, 1999)

Mobile Information Device Profile Specification, version 1.0, Java Community Process,Sun Microsystems, Inc., which can be downloaded fromhttp://www.jcp.org/en/jsr/detail?id=037.

Mobile Information Device Profile Specification, version 2.0, Java Community Process,Sun Microsystems, Inc., which can be downloaded fromhttp://www.jcp.org/en/jsr/detail?id=118.

The Java Hotspot™ Performance Engine Architecture, A White Paper (Sun Microsystems,Inc., 1999), which can be downloaded fromhttp://java.sun.com/products/hotspot/whitepaper.html.

K Native Interface (KNI) Specification, (Sun Microsystems, Inc., 2002)

Programming Wireless Devices with the Java™ 2 Platform, Micro Edition by Roger Riggs,Antero Taivalsaari and Mark VandenBrink (Addison-Wesley 2001)

Programming Wireless Devices with the Java™ 2 Platform, Micro Edition, Second Edition,by Roger Riggs, Antero Taivalsaari, Jim Van Peursem, Jyri Huopaniemi, Mark Patel,and Aleksi Uotila (Addison-Wesley 2003)

Java™ 2 Platform, Micro Edition, A White Paper (Sun Microsystems, Inc., 1999)http://java.sun.com/products/cldc/wp/KVMwp.pdf

KVM Debug Wire Protocol (KDWP) Specification, (Sun Microsystems, Inc., 2002)

xvi CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 17: Cldc Hotspot Architecture

CHAPTER 1

CLDC HotSpot ImplementationVirtual Machine

CLDC HotSpot Implementation is Sun’s high-performance Java virtual machine forwireless phones and communicator-type devices. The first generation of Javatechnology-enabled wireless devices were based on the KVM (K virtual machine).delivered as part of Sun Microsystems’ CLDC Reference Implementation. The mainobjectives of this reference design are to demonstrate how the CLDC Specificationcould be implemented, and to validate the accompanying Technology CompatibilityKit (TCK). It provides a common base that allows device manufacturers to port todifferent platforms, as well as a working environment against which developers cantest their CLDC-based applications.

Sun introduced the CLDC HotSpot Implementation in mid-2002 as an optimizedimplementation that focuses on performance and footprint. Not only does it complywith the CLDC specification, but it also includes a number of patented features thatpropel faster application execution as well as more efficient resource management. Itis also supported on a number of targeted platforms, which enables manufacturersto significantly reduce time to market.

CLDC HotSpot Implementation delivers nearly an order of magnitude betterperformance than the KVM, while running in the same small memory footprintrequired by mobile phones, wireless e-mail clients, and personal organizers. CLDCHotSpot Implementation is the best virtual machine technology for new productdeployments.

Sun developed the CLDC HotSpot Implementation Java virtual machine technologyto achieve the following objectives:

■ Faster performance■ More robust platform■ Faster time to market

CLDC HotSpot Implementation applies advanced tuning and performancetechniques utilized in the Java Platform, Standard Edition (Java SE) and JavaPlatform, Enterprise Edition (Java EE) technologies and further reduces footprint to

1-1

Page 18: Cldc Hotspot Architecture

fit in small devices. In addition, it incorporates several design innovations thatenable the virtual machine to run in resource-constrained devices. These techniquesadd the following features to the CLDC HotSpot Implementation:

■ Cutting-edge performance■ Fast application startup time■ Minimal footprint■ Reduced porting efforts■ Longer battery life

The version of CLDC HotSpot Implementation now being offered by SunMicrosystems supports either CLDC 1.0 or CLDC 1.1. It can be compiled to supporteither one of these. CLDC HotSpot Implementation conforms to the correspondingversion of the CLDC Specification and the TCK. To complete the Java technologystack, Sun also offers Sun Java Wireless Client, which integrates CLDC HotSpotImplementation with a high-performance implementation of the MIDP 2.0Specification and other commonly used standard extensions such as MMAPI 1.1 andWMA 1.1.

The HotSpot Virtual Machine

At about the same time that the first specification of Java ME platform CLDC wasreleased, Java SE and Java EE versions of a revolutionary Java virtual machinetechnology called HotSpot began product deployment. The HotSpot performanceengine was developed to address the perception that Java virtual machineperformance was insufficient for many mainstream applications, especially on bigservers. By implementing a host of performance enhancing techniques that wentbeyond innovations like just-in-time (JIT) compilers, the performance of the Javavirtual machine increased by an order of magnitude. HotSpot technology debuted inApril 1999. See the Java HotSpot Virtual Machine Technical White Paper, SunMicrosystems, 2001.

In 2001, these two technology trends converged to inspire the creation of the CLDCHotSpot Implementation virtual machine. In contrast to the referenceimplementation of CLDC and KVM, CLDC HotSpot Implementation is an optimizedimplementation. Creating Java technology-enabled consumer devices with KVM andCLDC was impressive, but the perception formed in the marketplace that, as inconventional Java technology, there was a need for faster performance (whileworking within the restricted resources of the target devices). CLDC HotSpotImplementation applies optimization techniques similar to those used in HotSpottechnology (but using considerably less memory and consuming less power) torealize nearly an order of magnitude improvement in CLDC-based devices.

1-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 19: Cldc Hotspot Architecture

1.1 Processor and Memory RequirementsThe first generation of Java technology-enabled mobile phones had processor andmemory requirements that were typical of the original design parameters of theKVM and CLDC. But, increasingly models are designed with considerably morecomputing power available. Now, the typical processor is a 32-bit processor with aclock speed of 60 megahertz or more. The typical memory resources in a targetdevice are 600 kilobytes of RAM and about 2 megabytes of flash and ROM.

The following table summarizes minimum and typical requirements for processorand memory which Java virtual machine technology must work within for nextgeneration mobile phones.

1.2 Compilation PerformanceTo improve the performance of a virtual machine beyond pure interpreterperformance, some kind of a static or dynamic compilation strategy is needed. Toapproach an order-of-magnitude improvement in performance (compared to aninterpreted virtual machine), while maintaining device-independent bytecode as thestandard for applications, the CLDC HotSpot Implementation virtual machine hasan innovative adaptive compiler. This compiler dynamically compiles the mostfrequently used, time-critical pieces of the applications into native code forsignificantly faster execution.

The dynamic compiler of CLDC HotSpot Implementation delivers performance andefficiency that surpasses an implementation that would compile everything. Onecould build in CLDC HotSpot Implementation an “always-compile” mode, but thiswould execute slower than the more common mixed mode (which uses the adaptivecompiler to optimize only the frequently called methods and uses an optimizedbytecode interpreter for infrequently used code). Worse, the RAM requirement

TABLE 1-1 Next-Generation Mobile Phone Minimum Requirements

Item High-Volume Devices Premium Devices

CPU type Mostly ARM Mostly ARM

CPU speed 50 megahertz 60 megahertz and higher

RAM 600 kilobytes (includingMIDP)

600 kilobytes (includingMIDP)

ROM and Flash 1 megabyte 2 megabytes

Chapter 1 CLDC HotSpot Implementation Virtual Machine 1-3

Page 20: Cldc Hotspot Architecture

would be dramatically larger because compiled code requires more heap space.CLDC HotSpot Implementation in dynamic compiler mode delivers executionspeeds that compare favorably even with desktop compilers such as the HotSpot1.4.1 technology client of the Java SE platform. Yet, the RAM requirement of CLDCHotSpot Implementation is only a fraction of that of the HotSpot 1.4.1 technologyclient, which is of course the objective in small, embedded devices.

The following diagram illustrates the order-of-magnitude performance improvementoffered by a dynamic compiler. On the left is the benchmark performance of theKVM, and the 2x performance improvement offered by the optimized bytecodeinterpreter of CLDC HotSpot Implementation. On the right is the performancemultiples that are currently realized by CLDC HotSpot Implementation.

FIGURE 1-1 Performance of Interpreted Mode Compared With Compiled Mode in CLDCHotSpot Implementation

Additional performance enhancement compared to straightforward virtual machinesis achieved with a HotSpot technology-style garbage collector and a fastsynchronization mechanism.

Note – The performance enhancement applies to bytecode execution, notnecessarily to processing graphics at the MIDP level.

1.2.1 Faster Execution Consumes Less PowerThe dramatic improvement in performance of CLDC HotSpot Implementation“turbocharges” application startup time and execution time, resulting in a positivesubjective experience. Just as importantly, it consumes battery power at aproportionally lower rate.

1-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 21: Cldc Hotspot Architecture

CHAPTER 2

Technical Overview

CLDC HotSpot Implementation is a high-performance alternative to the K VirtualMachine (KVM), which in the past was widely deployed on Java ME platform-enabled cellular telephones. KVM design places significant emphasis on ease ofportability and machine independence. The KVM is intended to be suitable for aslarge a number and as wide a variety of small devices as possible. Thus, anymachine-specific optimizations or the use of assembly code is generally avoided. Toensure maximum portability, KVM is written entirely using the ANSI Cprogramming language.

The CLDC HotSpot Implementation virtual machine is intended to take therevolution started by KVM to the next level. To deliver cutting-edge performance onmemory-constrained platforms, CLDC HotSpot Implementation employs a novelhigh-level architecture and a number of advanced, machine-specific optimizationtechniques. The system also borrows some key ideas from the HotSpot performanceengines for the Java SE and Java EE platforms.

Following are the key features of CLDC HotSpot Implementation:

■ Architecture designed for portability■ Dynamic, adaptive compiler, which compiles the most-used methods at runtime■ Compiler is incremental and schedulable■ Optimized interpreter (written in assembly language)■ Support for lightweight threads, which greatly simplifies porting■ Compact object layout■ Unified resource management■ Accurate generational garbage collection■ Ahead-of-time (AOT) compilation (optional)■ In-place execution (optional)■ Multitasking support (optional)■ Fast synchronization■ No restriction on number of loaded classes■ ROMizer, which stores system classes in a compact format that allows faster

execution■ Multiple profile support with API isolation

2-1

Page 22: Cldc Hotspot Architecture

■ Dynamic native method support to allow adding optional packages aftermanufacture

■ Support for both CLDC 1.0 or CLDC 1.1 with full TCK compliance■ Support for hardware acceleration technology, with battery savings and fast

startup■ Support for 32-bit addressing, useful for large-memory, next-generation phones■ Ability to be built as a main program or as a subroutine in an event loop

2.0.1 Portable ArchitectureThe CLDC HotSpot Implementation system is written in a portable subset of theC++ programming language, enabling it to be ported fairly easily to all platforms forwhich a C++ compiler is available. The system provides CPU-specific assembly codefor the ARM and x86 processors to implement the optimized interpreter and thecompiler. Information on porting these CPU-specific parts of the system is providedin Chapter 8 of the CLDC HotSpot Implementation Porting Guide.

2.0.2 Dynamic CompilerIn general, Java virtual machines with a compiler are an order of magnitude fasterthan those that provide only an interpreter. For that reason, CLDC HotSpotImplementation includes a dynamic compiler to provide fast bytecode execution. Awell-known problem with compiling bytecodes into native instructions is that thegenerated code takes up four to eight times as much space as the original bytecodes.An adaptive compilation technique in CLDC HotSpot Implementation alleviates thisproblem by compiling only methods recognized as “hot spots” (the most frequentlyused parts of the application). The CLDC HotSpot Implementation dynamiccompiler finds the hot spots by running a statistical profiler.

To minimize the amount of compiled code, CLDC HotSpot Implementation virtualmachine includes an optimized interpreter used for infrequently executed methods.

For more information on CLDC HotSpot Implementation’s dynamic compiler, referto Chapter 4.

The CLDC HotSpot Implementation compiler is a simple one-pass compiler thatprovides a number of basic optimizations. It is an adaptive compiler, because it usesdata gathered at runtime to decide which methods to compile. Only the methodsthat execute most frequently are compiled.

2-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 23: Cldc Hotspot Architecture

Incremental and Scheduled Compilation

The maximum duration of any single compilation and the minimum time intervalbetween compilation attempts can be set and dynamically adjusted. If the durationof a compilation exceeds the maximum, the compilation is suspended and theexecution of the user program continues, with the current method being interpreted.The suspended compilation may resume after the specified minimum time interval.

Tunability

Because the performance characteristics of small devices can vary considerably fromone platform to another, even when using the same CPU architecture, the CLDCHotSpot Implementation system provides a large number of compilation optionsand parameters that allow the performance of the compiler to be tuned. Some ofthese options and parameters are summarized in Chapter 4 of the CLDC HotSpotImplementation Porting Guide.

2.0.3 Optimized InterpreterCLDC HotSpot Implementation has an optimized interpreter written in assemblycode and customized for a particular CPU architecture. Optimized interpreter loopsare currently available for two CPU architectures: x86 (using 386 as the lowestcommon denominator) and ARM. Rather than writing the assembly loops by hand,they are generated statically from the debug version of the CLDC HotSpotImplementation system itself. This can be accomplished by invoking the debugversion of the virtual machine from the command line by using the-generate or -generateoptimized option. The former option generates anassembly interpreter for debugging the virtual machine, while the latter optiongenerates an interpreter that can be linked in product builds.

2.0.4 Lightweight Threading SystemCLDC HotSpot Implementation supports a lightweight threading system in additionto supporting native threads (OS threads). In contrast to native threads, lightweightthreads are implemented within the Java runtime environment. In the CLDCHotSpot Implementation, separate execution stacks are maintained for lightweightthreads and native threads.

For the remainder of this manual, a lightweight thread is referred to as a LWT.

In CLDC HotSpot Implementation, LWTs are implemented on a single native OSthread. Using this simple model, CLDC HotSpot Implementation can be ported toenvironments that do not offer any multi-threading capability. Even more

Chapter 2 Technical Overview 2-3

Page 24: Cldc Hotspot Architecture

importantly, the virtual machine has complete control over all memory allocationaspects of thread stacks for Java objects. It can dynamically “right size” these threadstacks. The lightweight threading system is detailed in Chapter 5.”

Support is also available for managing multiple native OS threads using the aniliblibrary. This is called the hybrid threading model, as detailed in Section 5.4, “HybridThreading Coding Style” on page 5-5.

2.0.5 Compact Object LayoutCLDC HotSpot Implementation supports a compact object layout to reduce generalmemory consumption. A Java object has two parts: an object header and an objectbody that are stored contiguously. The object header provides reflective informationsuch as the class pointer and contains a possible hash code or locking status or both.The object body contains the instance fields of the object.

Conventional Java virtual machine implementations use at least two words for theobject header, even though in most cases the hash code information and lockingstatus is needed only for a small number of the objects. Consequently, object headerstake up a big fraction of the total object space.

Very Compact Object Headers

CLDC HotSpot Implementation introduces a new design in which only one word isneeded for the object header. This object header contains a pointer to a near class inwhich the other information (such as hash code and locking status) is stored asnecessary. New instances are created with a prototypical near class that is sharedamong instances. When the instance is assigned a hash code or it is about to belocked, the object header is changed to point to a newly created individual near,instead of the prototypical one. This approach greatly reduces memory consumptionfor object instances. Because most Java object instances contain only a small numberof instance fields, the ability to cut the object header size in half or by one thirdresults in significant space savings.

The CLDC HotSpot Implementation object structure is illustrated in FIGURE 2-1.

2-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 25: Cldc Hotspot Architecture

FIGURE 2-1 Relationship Between Instance, Near Class, and Class

Field Packing

In addition to the compact object headers, CLDC HotSpot Implementation uses afield packing technique borrowed from the HotSpot performance engine. When aJava object contains instance fields of type boolean, byte, short or char, thesystem stores them using a more space-efficient 8-bit or 16-bit representation, ratherthan allocating full 32-bits for each of these fields. This technique can also result insignificant space savings when a large number of object instances are allocated. Thisaffects the internal object layout, because instance fields of the same type aregrouped together.

2.0.6 Unified Resource ManagementA major benefit of CLDC HotSpot Implementation is unified resource management.Unified resource management means that all allocated data in the virtual machineresides inside the object heap. Allocated data include the following:

■ Java objects■ Reflective objects, such as methods and classes■ LWT execution stacks■ Compiler generated code■ Virtual machine internal data structures

An important advantage of unified resource management is that the same garbagecollector takes care of cleaning up all allocated resources, even compiled code.Almost all other virtual machines have designated areas for user objects, reflectivedata, temporary data, and generated code. Such schemes result in memoryfragmentation, multiple cleanup strategies, and other complexities. CLDC HotSpotImplementation solves these issues by using the mark-sweep-compact garbagecollector for most regions of the heap. This implementation does maintain a fewregions in the heap dedicated for special kinds of objects. Different algorithms areused to manage memory in different regions and to adjust region sizes adaptively.However this multi-region management is transparent to applications.

Chapter 2 Technical Overview 2-5

Page 26: Cldc Hotspot Architecture

Another benefit of unified resource management is that compiled code can beremoved dynamically to free space for user-level objects.

Coding of native methods is implemented consistently with the lightweightthreading model (see Chapter 5”), which exemplifies unified resource managementand makes garbage collection even more efficient.

In general, uniform resource management has significant benefits in resource-constrained environments in which programmers are strongly discouraged fromallocating additional memory from the operating system or the device while thesystem is running.

2.0.7 Generational Garbage CollectionA garbage collector automatically reclaims unused object memory and makes thefreed memory available for new allocations. CLDC HotSpot Implementation uses anaccurate generational mark-and-compact garbage collector, which results in thefollowing advantages:

■ Fast object allocation■ Small garbage collection pauses■ No memory fragmentation■ Accuracy

For more technical details on garbage collection in CLDC HotSpot Implementation,see Chapter 3.”

2.0.8 Dedicated Heap Area for Compiled CodeCLDC HotSpot Implementation maintains a dedicated region within the object heapfor compiled code. This facilitates incremental compilation and eliminates the needfor garbage collections to dispose temporary data of the compiler and compiled codeevicted from the cache. This helps minimize compiler-related pauses, and garbagecollection is simplified so that the maximum time for a particular garbage collectionis reduced.

For more technical details about the heap architecture in CLDC HotSpotImplementation, see Chapter 3.”

2-6 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 27: Cldc Hotspot Architecture

2.0.9 Multitasking SupportThe Java programming language provides convenient language-level multithreadingand monitor mechanisms. These mechanisms make it easy to write multithreadedprograms that use fine-grained locking. The CLDC HotSpot Implementation systemuses a variant of the block-structure locking and synchronization approach that wasdeveloped originally for the HotSpot performance engine. Refer to the The JavaHotSpot Performance Engine Architecture, A White Paper listed in the Preface of thisguide under “Related Documentation” on page xv”.

If it is desired for the user to be able to run multiple applications concurrently, CLDCHotSpot Implementation can be compiled with a switch to support running inmultitasking mode.

An important feature of multitasking support in CLDC HotSpot Implementation isthe isolation of the tasks so that they can execute correctly (in a way that iscompliant to the Java Language Specification) as if they were executed in a single taskenvironment.

Although only one thread of execution exists at any given time, for practicalpurposes the MIDP application layer of the Java thread stack can avail itself ofmultiple virtual machines. Any of the multiple virtual machines can be paused whena switch to a different application in a different context is desired and resumed in thesame state at a later point in time.

For more technical details about multitasking support in CLDC HotSpotImplementation, see Chapter 6.”

2.0.10 Faster Virtual Machine Startup WithAhead-of-Time CompilationAhead-of-time compilation or AOT improves startup time by immediately executingfrequently used methods in compiled mode without spending time to compile themduring runtime.

Consider the tradeoff that must be made between faster startup times and increasedROM footprint from methods selected for AOT. To gain the optimal benefit from thisfeature, an implementation must be analyzed for candidates for ahead-of-timecompilation. To begin with, only Java methods in ROMized system classes can beAOT compiled. Of those methods, careful select frequently executed methods or hotspots.

For more technical details about AOT support in CLDC HotSpot Implementation,see Chapter 7.”

Chapter 2 Technical Overview 2-7

Page 28: Cldc Hotspot Architecture

2.0.11 Faster Application Startup With In-PlaceExecutionIf it is desired for the handset maker to preverify certain trusted applications toallow faster application startup, CLDC HotSpot Implementation can be compiledwith a build-time option to support in-place execution. Becvause it bypasses the Javaclass loader for selected applications, this option significantly reduces applicationstartup time.

For more technical details about in-place execution support in CLDC HotSpotImplementation, see Chapter 8.

2.0.12 Fast SynchronizationThe Java programming language provides convenient language-level multithreadingand monitor mechanisms. These mechanisms make it easy to write multithreadedprograms that use fine-grained locking. The CLDC HotSpot Implementation systemuses a variant of the block-structure locking/synchronization approach that wasdeveloped originally for the HotSpot performance engine. Refer to the The JavaHotSpot Performance Engine Architecture, A White Paper listed in the Preface of thisguide under “Related Documentation” on page xv”.

Rather than creating explicit monitor objects on the heap, the system places themonitor information on the execution stack. This approach avoids the memoryallocation and garbage collection costs typically associated with synchronization inJava virtual machines. As a result, synchronization performance becomes so fast thatit is no longer a performance bottleneck for Java applications.

For more information on the threading system of CLDC HotSpot Implementation,refer to Chapter 5.”

2.0.13 Integrated Class PrelinkerThe CLDC HotSpot Implementation system features an integrated prelinker called aROMizer for Java class libraries. This component pre-loads all class libraries thatmight be required at runtime, storing them in a compact format known as aROMized image. This image is embedded in the CLDC HotSpot Implementationvirtual machine when it is built. The image becomes part of the executable, which isburned into the ROM of a device at the time of manufacture.

2-8 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 29: Cldc Hotspot Architecture

To generate the ROMized image, the GenerateROMImage option must be set whenrunning a virtual machine built in debug mode. (efer to Chapter 4 of the CLDCHotSpot Implementation Porting Guide. The ROMizer outputs the image in the fileROMImage.cpp, which is portable between platforms.

In the development environment, the integrated class prelinker runs during theCLDC HotSpot Implementation system startup phase. It pre-loads all system classes,including those required by the configuration (CLDC) and the profile (MIDP). Thus,all these classes are available pre-linked as a ROMized image.

When the ROMized image embedded in the CLDC HotSpot Implementation virtualmachine, and a Java application is run in the development environment or in adevice, any system class required by the application is already pre-loaded and pre-linked.

For more information on using the ROMizer in CLDC HotSpot Implementation,refer to Chapter 10.”

2.0.14 Fully Object-Oriented Internal Design andUpwards ScalabilityThe CLDC HotSpot Implementation system is written in a portable subset of C++and the internal design of the system is fully object oriented. The internal objectlayout inside the system follows the same conventions as the system uses for Javaobjects. This makes the system scalable and lends itself to future enhancement. Inprinciple, the CLDC HotSpot Implementation system could be easily extended tosupport the semantics of the full JavaSE platform, including features such asreflection, serialization, remote method invocation, and so on.

2.1 Additional ComponentsThe system includes a number of additional components that are specific to Java MEreleases:

■ CLDC libraries. The CLDC HotSpot Implementation release comes with animplementation of the CLDC libraries. At this point, since the CLDC 1.1Specification is not yet finalized, only CLDC 1.0 libraries are supported.

■ Runtime verifier. The CLDC HotSpot Implementation system includes a KVM-style runtime verifier. This means that application class files given to the systemmust be preverified (as explained in the CLDC 1.0 Specification) before they can beexecuted.

Chapter 2 Technical Overview 2-9

Page 30: Cldc Hotspot Architecture

■ Dynamic memory profiler. This tool allows the virtual machine to be paused anda profile to be taken of the amount of heap memory in use at that time.

■ Incremental Java Archive (JAR) file reader. Beginning with version 1.1.3 ofCLDC HotSpot Implementation, the JAR file reader does not cache the wholedecoded JAR file entry in the Java heap. Instead, a new method is provided todecode small portions of the entry. This is especially beneficial for the decoding ofaudio and video streams, which typically have sizes up to several hundredkilobytes or a few megabytes.

■ K Native Interface (KNI). The CLDC HotSpot Implementation system includesan implementation of the KNI API that is intended to provide source-levelcompatibility for the native functions that are written for virtual machines thatconform to the CLDC standard. Also, extensions to KNI are provided to supportthe threading models detailed in Chapter 5. More information on the KNI isavailable in a separate publication, K Native Interface (KNI) Specification, (SunMicrosystems, Inc., 2002).

■ Debugging support. This support uses the KVM Debug Wire Protocol (KDWP). Italso provides support for debugging in commercial IDEs. Refer to Chapter 11 fordetails of debugging support.

2.2 New Technical Features in This ReleaseCLDC HotSpot Implementation 1.1.3 includes the following powerful new features:

■ Support for in-place execution in multitasking mode■ Multiple profile support with API isolation■ Dynamic native method support to allow adding optional packages after

manufacture■ Vector floating point support■ Incremental JAR file reader■ Support for interpreter-only mode■ Improved debugger support with commercial IDEs

The following sections describe these new features in more depth.

2.2.1 In-Place Execution in Multitasking ModeThe 1.1.2 release of CLDC HotSpot Implementation did not allow in-place executionin multitasking mode. This release removes that restriction.

2-10 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 31: Cldc Hotspot Architecture

2.2.2 Multiple Profile SupportThis feature allows building a system ROM image containing multiple profiles. Themeaning of profile for this feature is different than a Java ME platform profile (suchas MIDP). Multitasking support in CLDC HotSpot Implementation now defines newAPIs, allowing a new task to be assigned a profile. The profile defines what APIsmust be hidden or restricted for a MIDlet running in that task.

2.2.3 Dynamic Native Method SupportCLDC HotSpot Implementation now supports the downloading and linking ofnative methods as part of JAR files downloaded to the device after manufacture anddeployment. With this mechanism, support for additional optional packages can beadded to the device after manufacture.

2.2.4 Vector Floating Point SupportVector floating point (VFP) is a generic hardware coprocessor that can be used withany ARM processor core. VFP can be run either in IEEE-compliant slow mode or in anon-compliant fast mode. This release of CLDC HotSpot Implementation fullysupports both modes.

CLDC HotSpot Implementation can be built to invoke this hardware when a floatingpoint instruction is encountered. Since the implementation uses the VFP coprocessorfor other purposes, building in this mode is beneficial for the performance of allprograms.

2.2.5 Incremental JAR File ReaderIn past releases of CLDC HotSpot Implementation, the JAR file reader cached thewhole decoded JAR file entry in the Java heap. This is undesirable with JARfilescontaining large data files such as audio or video streams. The new incrementalJAR file reader supports incremental reading, which provides a new method todecode small portions of a JAR file entry.

Chapter 2 Technical Overview 2-11

Page 32: Cldc Hotspot Architecture

2.2.6 Interpreter-Only ModeThe availability of this build option helps a device manufacturer support a widerange of ARM processors while standardizing on one virtual machine. Simply bybuilding with different options, CLDC HotSpot Implementation can scale up as wellas down and fit in all devices with a wide variety of resources. This mode also is ofinterest when building with Jazelle integration.

2.2.7 Improved Debugger Support With CommercialIDEsAbove, corrected init capping per SESG.

The CLDC HotSpot Implementation debug module (KDWP) can communicate withcommercial IDEs such as NetBeans, WebSphere, JBuilder X Developer and JBuilder2005 Developer. This allows on-device debugging using these IDEs.

2-12 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 33: Cldc Hotspot Architecture

CHAPTER 3

Heap Architecture andGarbage Collection

CLDC HotSpot Implementation supports a“segregated” heap architecture, whichfeatures a separate heap area for compiled methods. This greatly reduces thelikelihood of noticeable pauses.

Although it is possible to build the CLDC HotSpot Implementation virtual machinewithout this segregated heap, this is not recommended.

3.1 Garbage CollectionWithin each heap area, the CLDC HotSpot Implementation virtual machine employsa two-generational mark-and-compact garbage collector, as illustrated in FIGURE 3-1.

FIGURE 3-1 The CLDC HotSpot Implementation Two-Generational Garbage Collector

Object Heap

Old Generation New Generation

3-1

Page 34: Cldc Hotspot Architecture

3.1.1 Structure of the HeapThe object heap is divided into old generation, new generation, and as-yet-unusedportions of memory. The old generation region contains objects that were previouslygarbage collected and compacted. New objects are allocated in the new generationregion, which is generally much smaller. When the new generation region is full, thegarbage collector runs briefly and reclaims the unused memory for that generation.In this case, the former new generation becomes part of the “new” old generation. Apart of the unused portion of the heap is allocated to become the “new” newgeneration.

When all memory in the object heap is consumed, the garbage collector runs acrossthe entire heap and compacts all live objects into a single “new” old generation.Only during this large garbage collection does a longer pause occur, but it occursinfrequently.

This scheme takes advantage of the fact that the vast majority of objects are shortlived. Because most objects are short lived, only a small portion of allocated objectsare promoted to the old generation. Most garbage collection operations focus onlyon the new generation, resulting in only very small garbage collection pauses.

3.1.2 Tracking Pointers Across GenerationsOne requirement of a generational system is the ability to track pointers from oldgeneration to new generation. For this, CLDC HotSpot Implementation uses a writebarrier. Whenever a pointer store takes place, the field is marked as a possible futurepointer from the old to the new generation.

3.1.3 Fast AllocationA side benefit of a compacting garbage collecting is that new objects are allocatedcontiguously in stack-like fashion in the young generation. Object allocation is thensimply a matter of increasing a pointer value.

3-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 35: Cldc Hotspot Architecture

CHAPTER 4

Dynamic Compiler

Two different compilers are appropriate in the CLDC HotSpot Implementationvirtual machine: a dynamic compiler and an ahead-of-time compiler. The dynamiccompiler is an adaptive compiler, because it uses data gathered at runtime to decidewhich methods to compile. Only the methods that execute most frequently arecompiled. The other methods are interpreted by the virtual machine.

The ahead-of-time compiler is available to compile classes and methods that are tobe ROMized.

The dynamic compiler is essentially a one-pass compiler that provides a number ofbasic optimizations. The compiler makes a preliminary scan of a method todetermine entry points. Then a target-dependent optimizer makes a final passthrough the generated code.

The dynamic compiler works as a co-routine in a single Java thread. Parameters canbe set so that the compiler can suspend itself after a given time interval.

4.1 Code Set ManagementThe set of methods that are interpreted and compiled must be managed in real timeby the dynamic compiler. This is done as follows:

■ The profiler detects hot interpreted and compiled methods.■ The compiled code cache uses cost-benefit analysis to limit space occupied by

compiled code.■ The compiled code cache size is dynamically adjustable.■ Program startup and phase transitions are handled in a special way.■ Compiled code is stored a dedicated region within the object heap.

4-1

Page 36: Cldc Hotspot Architecture

4.2 Tuning the Dynamic CompilerBecause the performance characteristics of small devices can vary considerably fromone platform to another, even when using the same CPU architecture, the CLDCHotSpot Implementation system provides a large number of compilation optionsand parameters that allow the performance of the dynamic compiler to be tuned.

For more information on tuning the dynamic compiler, refer to the CLDC HotSpotImplementation Porting Guide.

4-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 37: Cldc Hotspot Architecture

CHAPTER 5

Threading System

This chapter provides an overview of the threading system in CLDC HotSpotImplementation 1.1.3. More implementation details are given in Chapter 3 of theCLDC HotSpot Implementation Porting Guide.

The system has two distinct threading models. The simplest and preferred modelsupports LWTs (light weight threads). In this model, CLDC HotSpot Implementationimplements all LWTs on a single native OS thread. LWTs are essentially co-routinescreated and scheduled by the virtual machine. This is transparent at the Java runtimeenvironment level.

Using this simple model, CLDC HotSpot Implementation can be ported toenvironments that do not offer any threading capability. Even more importantly, thevirtual machine has complete control over all memory allocation aspects for LWTstacks. It can dynamically “right size” LWT stacks. Thus the implementation avoidsotherwise unavoidable pathological program failures due to lack of either stackspace or heap space.

As a consequence of only having a single active execution context for LWTs, it is astrict requirement that all native methods return virtually immediately. Otherwisethe whole virtual machine stalls and the user perception of preemptive multi-threading at the Java level is foiled.

A special style of handling threading might be preferable in some ports. This stylerelies on the availability of native thread support in the target platform OS. It iscalled hybrid threading, and is further described in Chapter 3 of the CLDC HotSpotImplementation Porting Guide.

5-1

Page 38: Cldc Hotspot Architecture

5.1 Long-Running Compared With BlockingNative MethodsIt is useful to distinguish between ordinary long-running and blocking nativemethods. For native methods that are long-running simply because they execute alot of free-flowing application code, one can often maintain the appearance of“smooth” thread scheduling by breaking the code up into repeated native calls thatreturn to Java after “reasonably short” execution intervals. This gives the virtualmachine the opportunity to perform sufficient thread context switching.

Blocking calls pose a greater challenge in that they carry the program execution into asystem that is not under virtual machine control. A typical example is a socketread() call into the underlying OS. As long as such a call does not return, thevirtual machine is trapped in inaction and the user is waiting and other LWTs aresuspended even though they are ready to execute.

Chapter 3 of the CLDC HotSpot Implementation Porting Guide describes the APIs andthe SPI in CLDC HotSpot Implementation for efficient implementation of nativemethods that make calls to potentially blocking routines.

5-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 39: Cldc Hotspot Architecture

CHAPTER 6

Multitasking

This document describes the multitasking feature of the CLDC HotSpotImplementation virtual machine.

The multitasking feature allows multiple user MIDlets to run in addition to a systemMIDlet, which can be used by an application management service (AMS) tocoordinate the creation and termination of user MIDlets.

The CLDC HotSpot Implementation virtual machine can be built with or without theoption to support multitasking. If it is built not to support multitasking, the virtualmachine is said to be running in SVM mode.

6.1 IntroductionMultitasking is the ability to handle multiple tasks or applications simultaneously.Of course, they aren't actually running at the same time on a single CPU, but theuser perceives concurrency. In earlier CLDC HotSpot Implementation virtualmachines, each application had to run in its own virtual machine to run multipleJava applications. The amount of wasted memory space due to separate copies of thevirtual machine usually outweighs the usefulness of running multiple applications.Running multiple Java applications in a single virtual machine in such a way thateach application is unaware of other applications running at the same time is a bettersolution. All the code of the virtual machine and much of the data is shared amongall applications. In particular, applications can share common immutable data suchas method bytecodes, final data types, and compiled method code.

Sharing of free memory is also very important. The frequency of garbage collectiondepends on the amount of free memory. Free memory sharing reduces the frequencyof garbage collection and the overall time spent in garbage collection.

6-1

Page 40: Cldc Hotspot Architecture

6.1.1 IsolatesAt the Java level, each separate running Java application within one virtual machineis called an isolate. The API used to instantiate each isolate is a stripped-downversion of the Isolate API defined in JSR 121. Refer to Section 6.1.3, “Reduced IsolateAPI” on page 6-5. At the virtual machine level, each isolate is represented as a Task.A task consists of one or more threads of execution. The CLDC HotSpotImplementation Isolate API is in the source tree atsrc/javaapi/share/com/sun/cldc/isolate.

The isolate mechanism comes close to combining the isolation guaranteed byUNIX system style processes and the lightweight resource consumption of threads.To the user, isolates very much resemble processes, but internally they arerepresented by tasks consisting in groups of threads operating on logically disjointobject graphs.

Physical sharing between those object graphs can occur if it only applies to constantobjects. Sharing opportunities typically arise from metadata, such as internalsymbols and field descriptors. Dynamically compiled code is also shared (by notmaking use of certain optimizations).

Conceptually, the main architectural change in the multitasking from the non-multitasking (SVM) virtual machine is that each isolate or task has a separate,private copy of the static variables of all the loaded Java classes. Normally, in theSVM case, if an application loads a Java class, the static variables of that class areglobal to all threads running in that virtual machine. In the multitasking case, staticvariables are only global to all threads within a particular isolate.

6.1.1.1 Example Program

The CLDC HotSpot Implementation Isolate API is quite simple to use. A new isolatestarts executing at the main method just like a “normal” Java application. To create anew isolate, set up a String array of arguments to the new isolate, set up theclasspath for the new Isolate object, and call the constructor.

Think of calling the Isolate constructor the same way as calling the Threadconstructor. In the case of the Thread constructor, when you subsequently call thestart method, a new thread starts executing at the run method of the class you justinstantiated. In case of the Isolate constructor, when you subsequently call start,the main method of the class you pass into the constructor is run in a new task (anda new thread).

To enable this, you must build the CLDC HotSpot Implementation virtual machinewith Isolate support compiled in. Use the ENABLE_ISOLATES=true compilationflag in the gnumake command. This provides for Isolate support in the virtualmachine and compiles the Java level Isolate API classes.

6-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 41: Cldc Hotspot Architecture

CODE EXAMPLE 6-1 is an example of programming a new isolate. To run this example,put HelloMVM.class in HelloMVM.jar, and MyIsolate.class inMyIsolate.jar. Then run the following command:

cldc_hi -cp HelloMVM.jar HelloMVM

CODE EXAMPLE 6-1 isolate Constructor

import com.sun.cldc.isolate.Isolate;

public class HelloMVM {

public static void main(String args[]) {

String[] isoArgs = {"hello"};

String[] classpath = {"MyIsolate.jar"};

System.out.println("Starting child");

try {

Isolate iso = new Isolate("MyIsolate", isoArgs,

classpath);

iso.start();

iso.waitForExit();

} catch (Throwable t) {

t.printStackTrace();

}

System.out.println("Child exited");

}

}

class MyIsolate {

public static void main(String args[]) {

System.out.println("You're saying " + args[0]);

}

}

6.1.2 Multitasking in MIDP 2.0Sun’s reference implementation of MIDP 2.0 does not support multitasking. TheMIDP 2.0 specification, while not requiring multitasking, does allow it provided thefollowing distinctions are made:

■ MIDlets in the same MIDlet suite share resources and must not be isolated.■ MIDlets from different MIDlet suites must be isolated.

Chapter 6 Multitasking 6-3

Page 42: Cldc Hotspot Architecture

As part of Sun Java Wireless Client, Sun Microsystems developed a MIDPimplementation that supports multitasking. The main architectural changes fromnon-multitasking MIDP to multitasking MIDP are in MIDlet management and in thehandling of events.

MIDlet management is conducted by a singleton “task manger” object, which can beaccessed both from Java programs and at the native virtual machine level. Nativecode can access the task manger object with the API functionSNI_AddStrongReference. A native method must be implemented to make thetask manger object reference reachable by every isolate in Java programs. Thus,every isolate can invoke methods on the shared singleton task manager. Thismechanism is used, for example, to communicate isolate state changes to the AMS.

The AMS runs in the system MIDlet and never terminates unless the entire virtualmachine is shut down. By using the task manager object as a repository for all itsbookkeeping about other isolates, the AMS can quickly access all relevant systemstate information in one central place.

FIGURE 6-1 Multiple Java Program Event Queues

A new requirement implied by a multitasking environment is that native events suchas button presses and keyboard presses need to be routed to an appropriate runningMIDlet. Thus, simple mapping of one native event queue to one MIDlet event queueno longer applies. Instead, now one native event queue caters to multiple Javaprogram event queues. One queue is created for each MIDlet. See FIGURE 6-1. Anevent multiplexer determines which event needs to be routed to which MIDlet. Theimplementation code for this can be found in the midpEvents.c file in the MIDPcode base.

6-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 43: Cldc Hotspot Architecture

6.1.3 Reduced Isolate APIAs mentioned earlier, the CLDC HotSpot Implementation Isolate API is a stripped-down version of the JSR 121 implementation for the Java SE and Java EE platforms.This API is hidden from developers of user MIDlets. It is available only to thedevelopers of AMS software.

See the source code at src/javaapi/share/com/sun/cldc/isolate.

6.2 Isolate ImplementationThis section presents implementation details about isolate support in the CLDCHotSpot Implementation virtual machine.

6.2.1 Virtualization of Static VariablesThe key concept in the multitasking implementation is that static variables are notpart of the JavaClassDesc memory object (as they are in the SVM case). Instead, ithas a table of pointers to TaskMirrorDesc for each active task. An entry in thistable points to a TaskMirrorDesc object for a given class. The table is indexed byclass ID. The TaskMirrorDesc object contains the actual storage for the staticvariables. During execution, a global variable, _current_task_mirror_list,contains the pointer to the TaskMirrorDesc table for the current running task.

6.2.2 Static Class InitializationWhen the Java bytecode attempts to access a static variable, it must first load theTaskMirrorDesc for the particular InstanceClass in which the static variable isinstantiated. If the TaskMirrorDesc is NULL, it means that this class has not beeninitialized for this task. Initialization involves running the methodClass.initialize for that class, and initializing any static variables. The sameprocess is involved to invoke a static method. The virtual machine must firstdetermine if the class that contains the method has been initialized, and if not, itmust go through the initialization process.

Following are examples of how to load a static variable for different classes:

■ Non-multitasking case

JavaClassDesc = _class_list_base[class ID]

value = *JavaClassDesc[static_var_offset]

Chapter 6 Multitasking 6-5

Page 44: Cldc Hotspot Architecture

//where static_var_offset is calculated at class load time.

■ Multitasking case

TaskMirrorDesc = *_current_task_mirror_list[class ID]

value = *TaskMirrorDesc[static_var_offset]

In the multitasking case, an extra load is required to get the pointer to theappropriate TaskMirrorDesc to obtain the static variable value.

6-6 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 45: Cldc Hotspot Architecture

6.2.3 Isolate CreationFIGURE 6-2 illustrates the overall process of creating a new isolate.

FIGURE 6-2 Isolate Creation

Chapter 6 Multitasking 6-7

Page 46: Cldc Hotspot Architecture

6.2.4 SynchronizationThis section discusses two kinds of synchronization that are handled by CLDCHotSpot Implementation: synchronization of instances of Java classes andsynchronization of interned string objects.

6.2.4.1 Synchronization of Java Classes

In the SVM case, each InstanceClass created in the virtual machine has a pointerto a Mirror object. This Mirror object is an instance of Class.java and is usedduring initialization as well as for synchronizing on the InstanceClass. In themultitasking case, in order for synchronization to be task-private, eachInstanceClass loaded into the system must have one private copy of this Mirrorobject per task. The TaskMirrorDesc object that contains the static variables alsocontains a pointer to a Mirror object. Because each InstanceClass has a separateTaskMirrorDesc for each running task, threads in one task cannot block threads inanother task.

6.2.4.2 Synchronization of Interned String Objects

Because String objects are interned when a class is loaded, they are global across alltasks. In order to synchronize on String objects (which is done rarely in practice)the virtual machine maintains a table of proxy objects that are used to do the actualsynchronization. These objects are task private, so that synchronization is taskprivate. This code is used in the SVM case as well, because it allows String objectsin ROMized classes to be in the TEXT section. Thus, the implementation doesn’tneed to modify the Near pointer in the String to lock it. The String object itself isnever locked, but is used as a key to find or allocate a proxy object that is actuallylocked.

6.2.5 Resource ManagementWhen multiple isolates are running in the same virtual machine, they sharecomputational resources such as CPU time and memory. The virtual machine is incharge of administering CPU time and memory resources to ensure that all isolatesget an appropriate share. Other resources, such as network bandwidth andcommunication ports, are managed by the MIDP layer or by optional packages suchas MMAPI.

6-8 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 47: Cldc Hotspot Architecture

6.2.5.1 Scheduling and Priorities

To prevent one task from taking a disproportionate amount of CPU time, CLDCHotSpot Implementation uses a simple fair scheduling algorithm. Each time a threadfrom a particular task is run, a counter for that task is incremented. If the countexceeds a value determined by the priority of that task, an attempt is made to run athread from another task. If all tasks exceed their quota, all the counts are reset andthe algorithm starts over. A task can have one of three priority levels: low, normal,and high. You can set the priority with the method Isolate.setPriority.

6.2.5.2 Object Heap Sharing

The virtual machine allows all isolates to allocate from the same global heap region.This provides more flexible control and sharing. The object graphs of differentisolates are intertwined without intersecting, except when sharing constant objects.The virtual machine has a bookkeeping mechanism that accounts for each isolate’sobject graph’s total heap memory consumption and it injects OutOfMemoryError asneeded to inform isolates that heap space has become scarce.

The CLDC HotSpot Implementation virtual machine implements an exactsynchronous memory quota mechanism. Memory quota violations are detected andsignalled to the isolate if they are encountered upon an attempt to allocate memory.

The memory quota for an isolate is defined by two fields: reservation and limit. Thereservation is the minimum amount of memory to needed to run the isolate. Thelimit is the maximum amount of memory the isolate is allowed to use.

You can set the memory quota for an Isolate using the methodIsolate.setMemoryQuota.

6.2.6 JSR 121JSR 121 defines a Java API for multitasking that is oriented towards larger (Java SEand Java EE platforms) systems. Recently the CLDC space is being taken intoconsideration. But at the time of this writing, this JSR is still ongoing and, for now, itis not formally integrated by CLDC, MIDP, or Java Technology for the WirelessIndustry.

To provide services similar to those defined in JSR 121, CLDC HotSpotImplementation offers a much reduced subset of the JSR 121 API and adds features.One noteworthy example is that the original Links API, which controls inter-isolatecommunication, is by a more lightweight mechanism. This significantly reducescomplexity and footprint.

Chapter 6 Multitasking 6-9

Page 48: Cldc Hotspot Architecture

The CLDC HotSpot Implementation extensions for multitasking are located in thepackage com.sun.cldc.isolate. Use of these extensions is described inSection 6.1.2, “Multitasking in MIDP 2.0” on page 6-3.”

Note – These extensions are available only to system programmers and are notpresented to user applications.

6-10 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 49: Cldc Hotspot Architecture

CHAPTER 7

Ahead-of-Time CompilationSupport

This chapter describes the ahead-of-time (AOT) compilation support in CLDCHotSpot Implementation. Selected methods can be compiled ahead of time, and theresult can be burned into ROM when the device is manufactured.

The AOT feature offers two key advantages.

■ Reduced startup time, because AOT-compiled methods do not need to becompiled again at run time.

■ More efficient usage of RAM, because AOT-compiled methods live in ROM.

7.1 Methods Eligible for AOT CompilationOnly Java methods in ROMized system classes can be AOT compiled. Thecompilation happens during the build process on the development host. The resultof the compilation is saved as a part of the constant data of the system class image.

AOT-compilation of Java methods in downloaded Midlets is not supported in thisrelease.

7.2 Choosing Methods to AOT CompileA new syntax in the ROM configuration file is available to specify the methods to beAOT compiled. If ROM footprint is not an issue, you can specify that all ROMizedmethods be AOT compiled. AOT-compiled methods are typically four to eight times

7-1

Page 50: Cldc Hotspot Architecture

larger than the original Java bytecodes. To save footprint, you can specify only asubset of methods to be AOT compiled. This subset can be determined by runningbenchmark programs and determining the hot ROMized methods.

7.3 AOT Compilation of DownloadedClassesThe possibility of combining AOT compilation with the application image converterfrom in-place execution (see Chapter 8, so that methods in downloaded classes canbe compiled and saved in the execute-in-place format is under invenstigation. Thisfeature might be included in a future release.

7-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 51: Cldc Hotspot Architecture

CHAPTER 8

In-Place Execution

This chapter describes in-place execution support in CLDC HotSpot Implementation.It presents an overview of the design, its advantages, and platform requirements.

8.1 Design OverviewThe goal of the in-place execution feature is to reduce RAM usage of the Java classloader and improve start-up time. The core of this feature consists of two modules:

■ The Application Image Converter converts an application’s JAR file into anapplication image, a format that requires much less memory and executes muchfaster.

■ The Fast Class Loader loads the application image into the Java heap of the virtualmachine for execution.

An application image is the memory content of an application after being loaded bythe virtual machine. It contains Java class data structures such as JavaClass,ArrayClass, Method and ConstantPool, as well the static variables of aapplication. It is equivalent to the results produced by the ClassFileParsermodule in CLDC HotSpot Implementation versions prior to 1.1.2.

8.2 Security ConsiderationsSpecial security considerations exist when using the in-place execution feature.Because the verifications normally performed by the Java class loader are bypassedin the fast class loader, application image files must be maintained on a secured file

8-1

Page 52: Cldc Hotspot Architecture

system that cannot be modified by users or by untrusted applications. Themanufacturing processes by which these image files are transferred to product ROMor flash memory must also be securely controlled.

8.2.1 Storing Application Image FilesThe verifier is an important part of the Java virtual machine that ensures theintegrity and safety of MIDlets. The verifier must be run before a MIDlet is runthrough the application image converter. After conversion, the application imagefiles must be stored in a secured storage device, inaccessible by untrustedapplications and by the phone’s user. This must be done with extreme care.

Because the verifications normally performed by the Java class loader are bypassedby the Java class loading enhancement feature, if an application image file is alteredby malicious parties, the security safeguards of the verifier are circumvented. In suchcases, invalid Java programs might be allowed to execute on the phone and gainaccess to arbitrary memory locations. The results can include, but are not limited to,the following:

■ The phone might crash.

■ Sensitive information might be stolen from the phone.

■ The phone might be used in a coordinated denial-of-service attack of the cellularnetwork.

Different phones may have different ways of storing secured information, so we arenot able to recommend how to store the verification results without specificinformation about your devices. However, following are examples where verificationmust not be stored because the storage device is not secured:

■ The results are stored in a removable storage device (such as an SD card) that theuser can modify using a Personal Computer.

■ The results are stored in a file in the phone’s internal file system, but the user canmodify the file (for example, by connecting the phone to a personal computer orby using a built-in application on the phone).

■ The phone allows the user to download arbitrary native applications that are ableto modify the verification results.

8-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 53: Cldc Hotspot Architecture

8.2.2 Warning MessageThe code provided in this implementation contains a special mechanism that isinvoked when you create an application image file: the following warning messageis printed. This message is to remind you of the security requirements. Remove thecode that prints this warning message after you implement the required securitymechanisms.

****warning***

****Binary ROM Images must be created in secured file system.

****Please refer to CLDC-HotSpot(TM) Porting Guide for moreinformation***

****warning***

Refer to Appendix E of the CLDC HotSpot Implementation Porting Guide for additionalsecurity considerations for the in-place execution feature.

8.3 Integrating the In-Place ExecutionFeatureCLDC HotSpot Implementation provides APIs for integrating the in-place executionfeature into a Java ME MIDP platform.

8.3.1 Running the ConverterThe Converter transforms an application JAR file (.jar) into an application imagebinary file (.bin). The Converter is a part of the virtual machine that uses thevirtual machine to load the Java classes from JAR file into the heap, verify the classcontents, and write the classes to a .bin file. Typically, the Converter is executed bythe Application Management Software (AMS) immediately after a JAR file isdownloaded to the device, with the following method call:

JVM_CreateAppImage(char *jarFile, char *binFile, int flags);

The flags argument to the JVM_CreateAppImage function specifies whether classfiles are to be removed from the JAR file after the conversion process.

If your device is configured to use CLDC HotSpot Implementation in the singlevirtual machine (SVM) mode, you must run the Converter in a clean virtual machinestate. That is, if a Java application is executing, you must exit the Java applicationbefore running the Converter.

Chapter 8 In-Place Execution 8-3

Page 54: Cldc Hotspot Architecture

8.3.2 Executing an Application ImageNo new API exists for executing an application image (.bin) file. Instead, thevirtual machine recognizes a .bin file from its classpath by reading a magic numberfrom the first four bytes of the .bin file.

A .bin file contains only the classes of an application. The resources and JARmanifest files are untouched in the JAR file. Therefore, when executing anapplication image, the AMS must specify both the .bin and JAR files in theclasspath.

8.3.3 In-Place Execution ExampleHere is an example for using in-place execution inside MIDP. This assumes that theclasspath contains MyMidlet.jar, which the AMS is about to launch. The functionJVM_CreateAppImage creates a in-place execution bundle for the JAR file ifnecessary and launches the virtual machine to execute from the bundle (instead offrom the JAR file).

void startMidlet(char *classpath) {

char * bundleName = "MyMidlet.bun";

if (!file_exists(bundleName)) {

JVM_CreateAppImage(classpath, bundleFile,

JVM_REMOVE_CLASSES_FROM_JAR);

}

// Was: JVM_StartVM(classpath, main_class, argc, argv);

JVM_StartVM(bundleName, main_class, argc, argv);

}

8.4 In-Place Execution from FlashWith this technology, the majority of the application image is run directly from theflash file system without first loading it into RAM. This might be achieved withcareful modifications of the virtual machine on your platform. Contact your SunJava Licensee Engineering representative for more information.

8-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 55: Cldc Hotspot Architecture

8.5 Experimenting With In-Place ExecutionThis section describes how to try the in-place execution features in CLDC HotSpotImplementation 1.1.3. Note that much of this is subject to change in future releases:

■ Build when setting the build-time option ENABLE_MONET=true, as follows:cd build/linux_i386make ENABLE_MONET=true

■ Run the virtual machine to create an application image file, as follows:target/bin/cldc_hi -cp HelloWorld.jar -convert.

■ Load the application image file into the virtual machine and execute the programthat it contains, as follows:target/bin/cldc_hi -cp ROM_binary.bun HelloWorld

Chapter 8 In-Place Execution 8-5

Page 56: Cldc Hotspot Architecture

8-6 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 57: Cldc Hotspot Architecture

CHAPTER 9

Jazelle Option for ARMImplementations

This chapter describes Jazelle support in CLDC HotSpot Implementation. Thisoption is especially interesting for ARM-based implementations that lack sufficientmemory resources to support the full dynamic compiler of CLDC HotSpotImplementation.

However, on any implementation, Jazelle can improve performance during startup.It also can provide an improvement during transition phases: When the virtualmachine is moving from one hotspot to another, the next method might not yet becompiled. Thus, while the virtual machine is running in interpreted mode, Jazelle-enabled fast hardware improves performance and provides a better user experience.

Although Jazelle support can be enabled on a platform in which memory isabundant, it is always preferable from a performance standpoint to use the dynamiccompiler if it is available. Jazelle provides essentially no performance improvementwhile Java code is executing in compiled mode.

9.1 Flags to Enable JazelleIt is necessary to set seven flags to enable Jazelle. For convenience, these settings arecontained in the file .../build/ads_jazelle/ads_jazelle.cfg.

As usual, you must create a copy of the build directory that pertains to yourplatform and tool chain to make customized build settings.

9-1

Page 58: Cldc Hotspot Architecture

Notice to Sun’s Licensees – This confidential and proprietary software may beused for evaluation or testing purposes for internal use only. Any commercial userequires execution of a separate JTEK licensing agreement from ARM Limited.

This is in addition to any license agreement the licensor may have entered into withSun. For the avoidance of doubt, distribution of products containing software codeto exercise the BXJ instruction and enable the use of the ARM Jazelle architectureextension without a JTEK licensing agreement from ARM is expressly forbidden.

© COPYRIGHT 1999 to 2004 ARM Limited© COPYRIGHT 2004 Sun Microsystems, Inc.

ALL RIGHTS RESERVED

9-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 59: Cldc Hotspot Architecture

CHAPTER 10

ROMizer

CLDC HotSpot Implementation supports a ROMizer utility. This is also known asthe class prelinker or the class preloader. The ROMizer enables classes compiled fromthe Java programming language to be linked directly in the virtual machine,reducing virtual machine startup time considerably.

At the implementation level, the ROMizer utility combines Java class files andproduces a C++ file that can be compiled and linked with the CLDC HotSpotImplementation virtual machine.

In conventional class loading, you use javac to compile Java source files into Javaclass files. These class files are loaded into a Java technology system, eitherindividually or as part of a JAR file. Upon demand, the class loading mechanismresolves references to other class definitions.

The ROMizer provides an alternative means of program linking and symbolresolution, one that provides a less-flexible model of program building, but whichhelps reduce the virtual machine’s bandwidth and memory requirements.

The ROMizer can accomplish the following tasks:

■ Combine multiple input files■ Determine an object instance’s layout and size■ Load only designated class members, discarding others

10.1 Running the ROMizerThe standard CLDC HotSpot Implementation build process for Linux on i386 andWin32 on i386 creates the following ROMizer executables:

■ $(JVMBuildSpace)/build/linux_i386/dist/bin/romgen■ $(JVMBuildSpace)/build/win32_i386/dist/bin/romgen.exe

10-1

Page 60: Cldc Hotspot Architecture

You can use these executables to generate the ROM image of your system classes byissuing a command such as:

romgen.exe -cp classes.jar -romize romizer-options ...

This command converts all class files in classes.jar into a ROM image, which isstored in the output file ROMImage.cpp. You can then compile and linkROMImage.cpp into your virtual machine executable.

10.2 Requirement for System ClassesThe system classes that you wish to ROMize must satisfy the followingrequirements:

■ All classes must be packaged into a single JAR file, such as in the fileclasses.jar in the previous example.

■ The standard CLDC HotSpot Implementation process creates the file$(JVMBuildSpace)/classes.zip.

This file includes important classes that the ROMizer requires for correctoperation. Your classes.jar file must include all the classes stored at thefollowing subdirectories in this file, without alteration or omission, for theROMizer to function properly:

■ classes/com/sun/cldchi■ classes/java/lang

Note – Your CLDC HotSpot Implementation license might require that you mustalso include other CLDC HotSpot Implementation classes in as-is form.

10.3 ROMizer OptionsThe ROMizer supports the following options.

■ GenerateROMComments, VerboseROMComments

These two options tell the ROMizer to generate comments inside theROMImage.cpp output file. The comments may be useful for understanding thestructure of ROMImage.cpp and for debugging.

Example:

+GenerateROMComments -VerboseROMComments

10-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 61: Cldc Hotspot Architecture

■ GenerateRelaunchableROM

If this option is enabled, the ROMizer generates a “relaunchable image,” whichmeans the virtual machine can be restarted in the same process. This is useful ifyour virtual machine process never terminates, but the virtual machine isrestarted inside the same process to execute different Java applications.

This option is enabled by default. If your virtual machine process alwaysterminates after running one Java program, you can turn off this option to savefootprint.

Example:

-GenerateRelaunchableROM

The syntax of these options is the same as other command-line options for the CLDCHotSpot Implementation virtual machine.

Note – Whether -GenerateRelaunchableROM saves footprint depends on yoursystem’s handling of the .data, .text, and .bss segments. Experiment withGenerateRelaunchableROM turned on and off to see which yields the best result.

10.3.1 ROMizer Optimization OptionsThe CLDC HotSpot Implementation ROMizer can perform a large number ofoptimizations to reduce the ROM footprint and increase performance. None of theseoptimizations change the semantics of your Java code. When used correctly, theseoptions can help you save as much as 30% of the ROM image footprint. For example,the RenameNonPublicROMSymbols option only affects methods and fields that arenot accessible by user applications. Also, the SimpleROMInliner option does notinline methods that may potentially be overridden by user applications. Certainoptions must be used in conjunction of a ROM configure file (see the -romconfigoption in the following list) to produce the correct results. Please read this sectioncarefully so that you can use these ROM optimization options effectively and safely.

The CLDC HotSpot Implementation ROMizer has the following optimizationoptions:

■ EnableAllROMOptimizations

This option enables all available ROM optimization options, including thefollowing:

■ AggressiveROMSymbolRenaming■ CompactROMFieldTables■ RenameNonPublicROMClasses■ RenameNonPublicROMSymbols■ SimpleROMInliner

Chapter 10 ROMizer 10-3

Page 62: Cldc Hotspot Architecture

Some of these optimizations require special care with KNI methods. Please readthe description of each individually optimization option before enablingEnableAllROMOptimizations.

Example

+EnableAllROMOptimizations

■ CompactROMFieldTables

If this option is enabled, the field tables of the ROMized classes are compacted.That is, fields that are not accessible by user applications are removed from thefield tables to save footprint. This option is disabled by default.

■ RenameNonPublicROMClasses

Many non-public ROMized system classes are not accessible by user applications.If this option is enabled, all such non-public classes are renamed to save footprint.This option is disabled by default.

Example:

+RenameNonPublicROMClasses

If you use this option, be sure to use the DontRenameClass command in yourROM configuration file to exclude any classes that cannot be renamed. Forexample, do not rename any classes that are accessed using the Class.forNameJava method or the KNI_FindClass C function.

■ RenameNonPublicROMSymbols

ROMized system classes must contain many non-public symbols (such as thenames of private and package-private fields and methods). User applicationcannot refer to these symbols because of Java programming language security.Hence, you can use this option to rename these symbols such that they take upless space.

However, this option might interfere with your KNI code if you useKNI_GetFieldID() to access non-public fields. Thus, theRenameNonPublicROMSymbols option is disabled by default and must be usedwith caution. It is best to enable this option, but to use theDontRenameNonPublicFields command in your ROM configuration file (seebelow) to exclude any classes that might be accessed by KNI_GetFieldID().

■ AggressiveROMSymbolRenaming

This option takes effect only if you enable the RenameNonPublicROMSymbolsoption. If you enable this option, all fields and methods (even the ones declaredwith the public keyword) in your non-public ROMized classes are renamed tosave space.

Note that when this option is enabled, a user application can still access publicfields and methods in a non-public class as long as these fields and methods areinherited from a public super class. For example, if you have the following code,application classes can still access f() in B:

10-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 63: Cldc Hotspot Architecture

public class A {

public void f() {...}

}

class B extends A {

public void f() {...}

public void g() {...}

}

However, they cannot access g(), because it is not declared in a public class.

■ MakeRestrictedPackagesFinal

This option applies to non-public classes in restricted Java packages (see the-romconfig option ). When this option is enabled, the ROMizer adds the finalattribute to the class’s declaration, provided it is not a public class and one of thefollowing is also true:

■ It is not a public class and it belongs to a restricted package■ It belongs to a hidden package

This makes it possible for the CLDC HotSpot Implementation virtual machine touse the faster invokevirtual_final bytecode to execute methods in this class.

This option is enabled by default.

■ RewriteROMConstantPool

Conventionally, each Java class owns an individual constant pool. Usually,constant pools of ROMIZED system classes have many duplicate entries. Thisoption (enabled by default) enables you to share a single constant pool among allthe ROMized system classes to reduce space.

■ MergedConstantPoolLimit

This option controls the maximum number of entries allowed in a mergedconstant pool. The default value is 65535, which is the maximum number allowedby the Java Programming Language Specification.

The main purpose for this option is for debugging the ROMizer. Use the defaultvalue in most cases.

■ EmbeddedROMHashTables

This option takes effect only if RewriteROMConstantPool is enabled. When thisoption is enabled, the ROMized String and Symbol hashtables are embeddedinto the merged constant pool.

■ ROMHashTableDepth

This option controls the average size of hashtable buckets for the ROMizedString and Symbol tables. The default value is 8. Larger values save space, atthe cost of longer search time. Shorter search times require more space.

Chapter 10 ROMizer 10-5

Page 64: Cldc Hotspot Architecture

Example:

=ROMHashTableDepth12

■ SimpleROMInliner

If this options is enabled, certain methods in the ROM image are inlined.

Example:

class Foo {

int bar;

private void setBar(int value) { bar = value;

}

static void doSomething(Foo foo) { foo.setBar(1234);

}

}

The setter method like the setBar() method in the previous example is inlinedto produce the following code, which is both smaller and faster:

class Foo {

int bar;

/* eliminated from ROM image

private void setBar(int value) { bar = value;

} */

static void doSomething(Foo foo) { foo.bar = 1234;

}

}

■ GenerateROMStructs

If this option is enabled, the ROMizer outputs a file called ROMStructs.h, whichdeclares C structures that represent the layout of all ROMized Java classes. Youcan use these structures to write native code that directly accesses non-static fieldsin the romized classes. This approach is much faster than theKNI_GetFieldID() API.

Note – If you write native code using ROMStructs.h, the code is not portable toother CLDC virtual machines that do not support this functionality.

■ HeapCapacity, HeapMin

10-6 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 65: Cldc Hotspot Architecture

Currently the ROMizer requires quite a bit of memory. The ROMizer allocates an8-megabyte heap by default (that is, the =HeapCapacity8M flag is on). However,if you have many classes in your classes.jar file, the ROMizer might fail witha cryptic message. If this happens, try adjusting HeapCapacity to 16M or higher.

The HeapMin option must never be set during ROMization.

■ -romconfig filename

All the options describes so far apply to the entire ROM image. The -romconfigoption, on the other hand, enables you to configure individual classes in the ROMimage.

The filename parameter specifies a ROM configuration file. The file can contain thefollowing entries:

■ InitAtBuild = class-name

The InitAtBuild entry tells the ROMizer to initialize the given class at buildtime. This feature is useful if you have classes with large class initializermethods, especially those that initialize large arrays. You can reduce virtualmachine startup time and shrink footprint by initializing such classes at buildtim. That is, during the generation of ROMImage.cpp.

Note – This option must be used with great caution. Initialize a class at buildtime only if its class initializer always produces the same result. For example, ifyour class initializer produces different output depending on the return value ofSystem.currentTimeMillis(), then it is obviously not a candidate forinitialization at build time.

Also, the ROMizer prints a warning if any class initializer callsSystem.getProperty().

In most cases you perform cross-ROMization. For example, you run the ROMizeron a PC and use its output, ROMImage.cpp, to build a MIDP stack for a targetdevice. The System.getProperty() method in the ROMizer returns anincorrect value, because it does not know anything about the properties definedin MIDP. The ROMizer’s warning message includes a stack trace to tell you theoffending class that calls System.getProperty().

■ DontRenameClass = class-name

If you use KNI_GetClass() or Class.forName() to access a class, use theDontRenameClass entry to tell the ROMizer not to rename the given class.

■ DontRenameNonPublicFields = class_name

If you use KNI_GetFieldID() to access fields of a class, use theDontRenameNonPublicFields entry to tell the ROMizer not to rename thenon-public fields in this class.

■ RestrictedPackage = package-name

Chapter 10 ROMizer 10-7

Page 66: Cldc Hotspot Architecture

For security reasons, you might need to disallow applications from definingclasses in certain Java packages. This prevents malicious applications fromaccessing the package-private members of these packages. This is an examplethat makes java.lang into a restricted package:

RestrictedPackage = java.lang

■ HiddenPackage = package-name

This entry makes the given package completely hidden from a userapplication. The application cannot access any of the classes of the givepackage, even those explicitly declared public. HiddenPackage impliesRestrictedPackage.

The main reason for using HiddenPackage is to hide the API implementationclasses (for example, a com.sun.* implementation for ajavax.microedition.io.* API). It can prevent malicious applications fromusing even the public interfaces of such packages. It can also prevent naiveapplications from accidentally using some implementation packages that mightnot be available in future versions of your software.

HiddenPackage also makes it possible for the ROMizer to perform moreoptimizations to further reduce footprint.

■ DontCompile = pattern

On slow platforms, dynamic compilation of Java methods into native code cantake significant amount of virtual machine startup time. Many methods in atypical MIDP implementation are executed only once during startup. To helpminimize star-up time, you can use the DontCompile entry to disablecompilation for such methods.

pattern is a match pattern for the fully qualified name of a method. Forexample, any of the following patterns matches the Object.toStringmethod:

java.lang.Object.toString

java.*.Object.toString

*.Object.toString

The ROMizer output file, ROMLog.txt (see Section 10.5, “ROMizer Log File”on page 10-10), contains a listing of all the methods that are marked as do-not-compile. Use this listing as an aid to check if your patterns match the desiredmethods.

10.3.2 ExampleAn example configuration file is included in the CLDC HotSpot Implementationsource distribution at $(JVMBuildSpace)/src/vm/cldc_rom.cfg:

10-8 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 67: Cldc Hotspot Architecture

InitAtBuild = java.lang.Integer

InitAtBuild = java.util.Calendar

InitAtBuild = com.sun.cldc.util.j2me.CalendarImpl

InitAtBuild = java.lang.Runtime

InitAtBuild = com.sun.cldc.util.j2me.TimeZoneImpl

InitAtBuild = com.sun.cldc.io.j2me.socket.Protocol

InitAtBuild = java.util.TimeZone

InitAtBuild = com.sun.cldc.i18n.j2me.ISO8859_1_Reader

DontRenameNonPublicFields = com.sun.cldc.io.ResourceInputStream

RestrictedPackage = java.io

RestrictedPackage = java.lang

10.4 Ahead-of-Time (AOT) CompilationThe ROMizer supports the ahead-of-time compilation of Java methods in ROMizedsystem classes. Java methods in ROMized system classes can be AOT compiled. Thecompilation happens during the build process on the development host. The resultof the compilation is saved as a part of the constant data of the system class image.

A new syntax is included in the ROM configuration file to specify the methods to beAOT-compiled:

Precompile = pattern

Note – If a method matches patterns for both Precompile and DontCompile, thatmethod is not AOT-compiled.

If ROM footprint is not an issue, you can specify that all romized methods be AOT-compiled. AOT compiled methods are typically four to eight times larger than theoriginal Java bytecodes. To save footprint, you can specify only a subset of methodsto be AOT compiled. This subset can be determined by running benchmarkprograms and determining the hottest candidate ROMized methods.

Following are the advantages of AOT compilation:

■ Reduced startup time - AOT-compiled methods do not need to be compiled againat runtime.

■ More efficient usage of RAM - AOT-compiled methods reside in ROM.

Chapter 10 ROMizer 10-9

Page 68: Cldc Hotspot Architecture

10.5 ROMizer Log FileBesides the ROMImage.cpp output file, the ROMizer also creates a log file,ROMLog.txt, which contains various statistics about the ROM image. Oneimportant purpose of the ROMLog.txt file is to list the unintialized classes at buildtime, and why they are uninitialized. Here’s an example:

[Uninitialized Classes]

javax.microedition.lcdui.TextEditor

-> <clinit> not executed (435 bytes)

-> uninitialized super class javax.microedition.lcdui.TextBox

-> uninitialized super class javax.microedition.lcdui.Screen

This log entry shows that the TextEditor class was not initialized at build time forthe following reasons:

■ Its static initializer method (<clinit>) was not executed because this class wasnot specified by an InitAtBuild entry in the ROM configuration file.

■ Two of its superclasses were not initialized.

In this example, because the <clinit> method of TextEditor is relatively large,consider rearranging the code so that TextEditor can be initialized and its<clinit> method remove, at build time.

Also check in ROMLog.txt the list of non-restricted packages (see the [classes innon-restricted packages] section of ROMLog.txt). Typically this list is emptyso that malicious applications cannot be able to access package-private members ofthe system classes.

10-10 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 69: Cldc Hotspot Architecture

CHAPTER 11

Java Programming LanguageDebugging (KDWP)

CLDC HotSpot Implementation can plug its virtual machine into third-party Javaplatform development and debugging environments, provided they are compliantwith the Java Platform Debug Architecture (JPDA) specification supported by the JavaSE platform. Further information on the JPDA architecture is available athttp://java.sun.com/products/jpda/.

Due to strict memory constraints, CLDC HotSpot Implementation does notimplement support for the Java Virtual Machine Debug Interface (JVMDI) and fullJava Debug Wire Protocol (JDWP) specifications required by JPDA.

Instead, CLDC HotSpot Implementation implements a subset of the JDWP known asKVM Debug Wire Protocol (KDWP). A specification of the KDWP protocol is availablein a separate document, KVM Debug Wire Protocol (KDWP) Specification, (SunMicrosystems, Inc., 2001).

11.1 KDWP ArchitectureThe KDWP is a strict subset of the JDWP, primarily based on the resource constraintsimposed on the CLDC HotSpot Implementation virtual machine. To make CLDCHotSpot Implementation run with a JPDA-compatible debugger IDEs, a debug agent(debug proxy) program is interposed between the virtual machine and the JPDA-compatible debugger. The debug agent enables many of the memory-consumingcomponents of a JPDA-compliant debugging environment to be located on thedevelopment workstation instead of in the virtual machine, therefore reducing thememory overhead on the virtual machine and target devices due to the debugginginterfaces. Of course, the debugging interfaces can be turned off completely (atcompile time) on those platforms and ports that do not need debugging support atthe level of the Java programming language.

11-1

Page 70: Cldc Hotspot Architecture

At the high level, KDWP debugging support implementation consists of two parts:

■ The actual code in the virtual machine to support a subset of the JDWP■ The debug agent that performs some of the debug commands on behalf of the

virtual machine

The overall architecture for the Java-level debugging interface is illustrated inFIGURE 11-1. In that figure, the top-most box represents the JPDA-compliantdebugging environment (“JPDA Debugger”) running on a developmentworkstation. The debugger is connected to a debug agent, which communicates withthe virtual machine.

FIGURE 11-1 Java Programming Language Debugging Interface Architecture

The debug agent connects to the virtual machine via a socket connection. Similarly,the debugger connects to the debug agent over a socket. The debugger is unawarethat it is connected to the debug agent. The debugger appears to be communicatingdirectly with a JDWP-compliant Java virtual machine. In fact, the debug agent can beconfigured in pass through mode so that all packets are passed from input to outputusing the debug agent with a Java virtual machine. In normal CLDC HotSpotImplementation debug mode, the debug agent examines packets from the debuggerand determines which packets are to be handled by the virtual machine and whichare to be handled within the debug agent.

The main processing done in the debug agent is the parsing of class files to extractdebugging information. This includes line number and code offset information andvariable information. The KDWP implementation within the virtual machineincludes some vendor-specific commands that the debug agent uses to communicatewith the virtual machine.

JPDA Debugger

Debug Agent

CLDC HotSpot

Socket Connection

Socket Connection

Virtual MachineImplementation

11-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 71: Cldc Hotspot Architecture

11.2 Debug AgentAn executable for the debug agent (also known as debug proxy) is included with theCLDC 1.1 release.

The debug agent is written in the Java programming language. The source code canbe downloaded from http://java.sun.com/products/cldc/. The code hastwo main portions: the portion that handles connections to the debugger and to thevirtual machine, and the portion that handles the parsing of the class files. The lattercode is located in subdirectory classparser.

11.2.1 Connections Between a Debuggerand CLDC HotSpot ImplementationThe portion of the code that handles connections to the debugger and to the virtualmachine resides in file KVMDebugProxy.java. This code creates two objects:DebuggerListener and KVMListener. The DebuggerListener class handles theretrieval of packets from the debugger and the KVMListener class handles theretrieval of packets from the virtual machine. DebuggerListener andKVMListener are both subclasses of class Thread. Therefore, when they areinvoked, they start a new thread of execution (on the development workstation.)Each object also is passed a handle to the other object (that is, the KVMListenerobject is passed a handle to the DebuggerListener object, and vice versa). Thisenables cross-communication of packets between the debugger and the virtualmachine. The following diagram (FIGURE 11-2) clarifies this further.

Chapter 11 Java Programming Language Debugging (KDWP) 11-3

Page 72: Cldc Hotspot Architecture

FIGURE 11-2 Debugger and CLDC HotSpot Implementation Connections

In a typical scenario, the CLDC HotSpot Implementation virtual machine is startedwith the -debugger flag, which puts it into a debugger-enabled mode. In this mode,the virtual machine listens on a socket for a connection from the debug agent. Whenthe debug agent is started, it connects to this socket, and then listens on anothersocket for a connection from the debugger. When the debugger connects, it issues theJDWP handshake command, which consists of the string JDWP-Handshake. Thedebug agent acknowledges by reflecting this string back to the debugger.Meanwhile, the debug agent has sent the handshake command to the virtualmachine, which has responded back with information about which optional events itsupports. The KVMListener then queries the virtual machine for a list of all theclasses that are currently loaded into it. This information is used to build a hashtable of ClassFile objects that is used later when the debugger requestsinformation about a specific class (such as line number information, methodinformation, and so forth.) At this point, each thread is listening for packets. Thevirtual machine sends a VMInit event to the debugger using the debug agent, whichindicates to the debugger that the virtual machine is starting its execution of the Javatechnology application. The debugger might also send packets that indicate to thevirtual machine to start other events such as ClassPrepare or ClassLoad.

JPDA Debugger

Debugger Listener

CLDC HotSpot

Class Manager

Debug Agent

CLDC HotSpot

Virtual Machine

ListenerImplementation

Implementation

11-4 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 73: Cldc Hotspot Architecture

The communication code for the debug agent is in source fileSocketConnection.java. In this file, each object (KVMListener andDebuggerListener) creates a thread of execution that waits for packets to arrivefrom its respective socket. If the packet is a command packet (the Packet.Reply bitis not set), it puts that packet on a packetQueue list (see fileProxyListener.java) and a notification is sent to any object waiting on thatqueue. The packet is then extracted from the queue by whatever listener is waitingfor that packet on that queue. In the run method for the KVMListener andDebuggerListener, each packet is analyzed to determine if the debug agent needsto process the packet or whether it is to be transmitted to the other object for furtherprocessing.

11.2.2 Packet ProcessingThe DebuggerListener object intercepts a number of packets as is evident byexamining the code for the large switch statement located after the call towaitForPacket. When waitForPacket returns with a packet, the debug agentfirst creates a new PacketStream object, then checks to see if the debug agentneeds to process that packet. For example, the SENDVERSION_CMD packet isprocessed by the debug agent directly and a response is created and sent to thedebugger without any interaction with the virtual machine. A more complexcommandis the FIELDS_CMD of the REFERENCE_TYPE_CMDSET. For this command,the debugger passes in a class id, which is used by the debug agent to find aClassFile object via the ClassManager.classMap object. The classMap objectis filled by the KVMListener object when it receives the ClassPrepare eventsfrom the virtual machine. Once the debug agent obtains the ClassFile object, ituses the getAllFieldInfo method to obtain a list of fields and iterates throughthis list passing the information back to the debugger. Once again, no interactionwith the virtual machine occurs.

Similarly, within the source file for the KVMListener.java, the KVMListenerobject intercepts the CLASS_PREPARE events that are passed up from the virtualmachine. KVMListener creates a new ClassFile object using the call tomanager.findClass and inserts it into the ClassManager.classMap hashtable.KVMListener then passes the event to the debugger so that it can process the eventas well.

Chapter 11 Java Programming Language Debugging (KDWP) 11-5

Page 74: Cldc Hotspot Architecture

11.3 Debugger SupportThe debugger support within the CLDC HotSpot Implementation virtual machineconsists primarily of the files in the directory src/vm/share/debugger. Alldebugger code is included with the conditional compilation flagENABLE_JAVA_DEBUGGER. If this flag is enabled and the virtual machine is rebuilt,the Java debugger support is included within the virtual machine. If Java debuggersupport is not desired, rebuild with ENABLE_JAVA_DEBUGGER=false.

Note – If your target platform or port does not require Java level debuggingsupport, turn the debugging code off at compile time by rebuilding withENABLE_JAVA_DEBUGGER=false

This makes the virtual machine executable much smaller.

The following files are located in the debugger directory of the source tree:

■ JavaDebugger.* - Main interface to the debug agent. Handles the processing ofcommands and replies.

■ SocketTransport.* - Handles debugger packets to and from a socket.■ VMEvent.* - Handles events to the debugger.■ VMEventModifier.* - Supports various attributes of events.■ DebuggerStream.* - Manages the debugger packets to and from the debugger.■ *Impl.* - Handles specific commands from the debugger to obtain information

about the program being debugged.

11.3.1 EventsEvents are essentially commands generated by the virtual machine. Events arepassed up to the debug agent, which can in turn pass them up to the debugger. Thecode for handling an event is similar to the following example:

#if ENABLE_JAVA_DEBUGGER

{

VMEvent::new_class_prepare_event(&ic);}

#endif /* ENABLE_JAVA_DEBUGGER */

A typical event routine in VMEvent.cpp first determines if the event attempting tobe sent was enabled by a previous Set Event command from the debugger. Then,findSatisfyingEvent is invoked to determine if this particular event matches anevent request sent down from the debugger. The get_event_request functionalso checks the event counter as well as any modifiers that the debugger applied to

11-6 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 75: Cldc Hotspot Architecture

this event. If the event passes, it is sent on the outputStream. After an event issent, handleSuspendPolicy is invoked to process whatever suspend policy thedebugger attached to this event when the debugger issued the Set Event command.Some events, such as breakpoints or single stepping, generally have a suspendpolicy of ALL, which means that all threads are suspended and that the virtualmachine continually polls the debugger for commands. The Resume commandeventually comes from the debugger when the user issues a Continue command orwhen the user explicitly issues a Resume Thread command.

11.3.2 BreakpointsWhen the Java bytecode interpreter hits the Breakpoint opcode (seeTemplateTable_<arch>.cpp), if it is not single stepping, thehandle_breakpoint function is invoked, which sends an event to the debuggervia the debug agent. Eventually, the user presess the Continue button on thedebugger, which causes all threads to resume execution.

11.3.3 Single SteppingWhen the debugger issues a SingleStep event request, the code in VMEvent.cppmust determine which type of step function it is, that is, step by bytecode or step byline. It also must determine which tipe of step it is, as follows:

■ Step Into - Step into a function.

■ Step Over - Step over calls to functions. That is, do not single step into anotherfunction.

■ Step Out - Go back to the function that called this function.

Additionally, if it is a step by line, the virtual machine needs to know what the codeoffset is for the next line number. To obtain this information, the virtual machinecalls a private API within the debug agent to return the target offset and the nextline offset. The debug agent returns this information to the virtual machine, whichstores it into a StepModifier object. Within the interpreter loop, a flag is checkedto determine if this particular thread is in single-step mode. If so, thehandle_single_step function in VMEvent.cpp is invoked to process this singlestep. The handle_single_step function determines if the instruction pointerreached the target offset or if it popped up a frame or if it exceeded the target offset.Depending on the type of stepping being performed, this function determines whento send a SingleStep event to the debugger. In most cases, if the user is singlestepping line by line, and when the code offset is equal to the target offset, it resultsin a SingleStep event to be sent to the debugger. All threads are typically

Chapter 11 Java Programming Language Debugging (KDWP) 11-7

Page 76: Cldc Hotspot Architecture

suspended at this point, and as was the case for the breakpoint scenario describedearlier, the virtual machine waits until the debugger resumes the threads using aContinue command or a subsequent SingleStep event.

11.4 Using the Debug Agent and the JPDADebuggerTo run the debug agent, it is necessary to build the application class or classes beingdebugged to include debug information. It is also necessary to transform theapplication class file(s) using the preverifier. Then, after the virtual machine isinvoked on a specified host and port, the debug agent can be started so that it listensto requests on the virtual machine port, and a local port is specified for connectingwith a JPDA-compatible debugger.

The following section summarizes the steps necessary to start a debug session inmuch more detail.

Note – CLDC HotSpot Implementation debugger functionality is integrated into theJava ME platform wireless toolkit. Therefore, if you are using the wireless toolkit, thedetailed steps in the next section are not necessary.

11.4.1 Starting a Debug Session1. Build the application classes to be debugged with the -g option to include debug

information.

2. Place the output in a separate directory for transforming the resulting class fileusing this command:

javac -g -classpath <path> -d <directory> <class>

Note the following:

■ -g indicates debug information is to be included.

■ In -classpath <path>, <path> indicates the directory that contains the virtualmachine Java library classes and the application classes for the application beingdebugged.

■ In -d <directory>, <directory> indicates the directory in which output classes are tobe written. The default output directory is ./output.

■ <class> is the application class or classes being debugged.

11-8 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 77: Cldc Hotspot Architecture

3. Invoke the preverifier for transforming the class file with this command:

preverify -classpath <path> -d . <directory>

This transforms all classes under <directory> and places the transformed class files inthe current directory (as specified by the -d option).

4. Start the CLDC HotSpot Implementation process with this command:

cldc_hi -debugger -classpath <path> -port<CLDC-HotSpot-Implmentation-port> <class>

Note the following:

■ -debugger indicates that the virtual machine is to be placed in debugger-enabledmode

■ In -classpath <path>, <path> specifies the directory that contains the virtualmachine Java library classes and the application classes for the application beingdebugged.

■ -port <CLDC-HotSpot-Implmentation-port> is the CLDC HotSpot Implementationport. The default port is 2800. This must match the port specified by the debugagent in Step 5.

■ <class> is the application class being debugged.

5. Start the debug agent (debug proxy) with this command:

java -classpath <path> kdp.KVMDebugProxy -l <localport> -p -r<CLDC-HotSpot-Implmentation-host> <CLDC-HotSpot-Implmentation-port> -cp<CLDC-HotSpot-Implmentation-path>

■ -classpath <path>, where <path> specifies the directories in which the debugproxy classes are located.

■ -l <localport>, where <localport> is the port that the debugger connects to.

■ -p indicates to run as a debug proxy.

■ -r <CLDC-HI host>, where <CLDC-HI host> is the remote host name.

■ <CLDC-HI port> is the port that must match the port specified in step 3 above.■ -cp <path>, where <path> is the directory or directories which contain the virtual

machine Java library classes and the application classes for the application beingdebugged.

6. Connect to the debug agent with the debugger.

For Sun ONE Studio debugger, go to the Debug->Attach dialog box and insert thehost where the debug agent is running and the local port number that was specifiedusing the -l <localport> option.

Chapter 11 Java Programming Language Debugging (KDWP) 11-9

Page 78: Cldc Hotspot Architecture

Note – To obtain Sun ONE Studio, go tohttp://wwws.sun.com/software/sundev/jde/buy/index.html. Whenrunning the Sun ONE debugger, JDK version1.3 or later must be installed and be onthe classpath, because only this version (or later) of the JDK includes support for theJPDA. For further information on downloading the latest JDK version, please refer tothe web site at http://java.sun.com/j2se.

For jdb (Java debugger), the command is as follows:

jdb -attach <agent hostname>:<localport>

11.4.2 Debugging ExampleIf the CLDC HotSpot Implementation virtual machine is running on a system calledsiciy, and the debug agent and debugger are running on debughost, then thecommands for starting the debug session appears as follows:

1. On the sicily system, build the application testusing this command:

javac -g -classpath ../api/classes:../samples/classes

-d output test.java

2. Invoke the preverifier for building a preverified class file, using this command:

preverify -classpath ../api/classes:../samples/classes

-d . output

3. On the sicily system, type the following command to invoke CLDC HotSpotImplementation:

cldc_hi -debugger -classpath ../api/classes:../samples/classes

-port 2800 test

4. On the debughost system, assuming the current directory is tools/kdp/classes,the following command invokes the debug agent (debug proxy):

java -classpath . kdp.KVMDebugProxy -l 1234 -p -r sicily

2800 -cp ../../../api/classes:../../../samples/classes

5. Invoke the Sun ONE debugger, followin gthese steps:

a. Select the Debug->Attach dialog and select the socket transport.

b. Enter debughost in the host name box, and enter 1234 in the port number box.

c. Press OK.

11-10 CLDC HotSpot™ Implementation Architecture Guide • July 2006

Page 79: Cldc Hotspot Architecture

Index

Aadaptive compilation, 2-2ahead-of-time compilation (AOT), support for, 7-1ahead-of-time compiler, 4-1AMS (application management service), 6-1, 6-4ANI (asynchronous native interface), 5-5ani.h, 5-5AOT(ahead-of-time compilation), support for, 7-1application management service (AMS), 6-1, 6-4asynchronous native interface (ANI), 5-5

Bblocking calls, 5-2

Cclass prelinker, 2-8class prelinker utility (ROMizer), 10-1classes, ROMized, 4-1CLDC HotSpot Implementation, 1-1CLDC HotSpot Implementation Porting Guide, 4-2CLDC Hotspot Implementation, components, 2-1CLDC Hotspot™ Implementation, key ideas, 2-1CLDC libraries, 2-9coding style, hybrid threading, 5-2coding style, non-blocking scheduling, 5-2Coding Styles for Long-running Native Methods, 5-

2compiler, adaptive, 1-3, 2-2compiler, ahead-of-time, 4-1Compiler, Dynamic, 2-2

compiler, dynamic, 4-1compiler, tunability, 4-2

Ddebugger support with KDWP protocol, 11-1dynamic compiler, 4-1dynamic compiler, tuning, 4-2

GGarbage Collection, 3-1garbage collector, accurate, 2-6garbage collector, mark-sweep, 2-6garbage collector, two generational, 3-1

Hheap, structure of, 3-2HotSpot™ performance engine, 1-2hybrid threading coding style, 5-2

Iin-place execution, 8-1in-place execution, security considerations, 8-1integrated class prelinker, 2-8integrating in-place execution, APIs, 8-3interpreter, optimized, 2-3isolate, 6-2isolate, API, 6-5isolate, compared to JSR 121, 6-2isolate, creating new, 6-7

Index-1

Page 80: Cldc Hotspot Architecture

isolate, support in CLDC HotSpotImplementation, 6-5

JJava classes, synchronization of in multitasking, 6-8Jazelle, flags to enable, 9-1Jazelle, startup performance improvement, 9-1Jazelle™ support, 9-1

KK Native Interface, 2-10K virtual machine, 1-1KDWP support, 2-10KDWP, architecture, 11-1KNI, 2-10KVM, 1-1

Llightweight thread, 2-3long-running methods, compared to blocking native

methods, 5-1LWT, 2-3LWT (lightweight thread), 5-1

Mmultitasking in CLDC HotSpot Implementation, 6-1multitasking in Sun Java Wireless Client, 6-4

Nnative methods, compared to blocking long-running

methods, 5-1near class, 2-4non-blocking scheduling coding style, 5-2

Oobject heap, 3-2object heap, new generation, 3-2object heap, old generation, 3-2object layout, compact, 2-4OS thread, 2-3

PPorting Guide, CLDC HotSpot Implementation, 4-2

Rresource management in multitasking, 6-8ROMizer utility, 10-1ROMizer, optimization options, 10-3ROMizer, options, 10-2ROMizer, running, 10-1ROMizer, supports for ahead-of-time compilation

(AOT), 10-9ROMizer, system class requirements, 10-2runtime verifier, 2-9

Sscheduling algorithm in multitasking, 6-9segregated heap architecture, 3-1sni.h, 5-3Sun Java Wireless Client, multitasking in, 6-4SVM mode, 6-1

Tthread synchronization, 2-8thread, lightweight (LWT), 5-1tunability of compiler, 4-2tuning the dynamic compiler, 4-2

Uunified resource management, 2-5

Vvirtual machine, performance of, 1-3

Index-2 CLDC HotSpot™ Implementation Architecture Guide • July 2006