SlideShare a Scribd company logo
NativeBoost
   Igor Stasenko
    August, 2011
 ESUG Conference
Before we start


• http://code.google.com/p/nativeboost/
  wiki/Installation
What is NativeBoost?

• A plugin for VM which allows you to run
  machine code generated in image
• A set of utilities at language side which
  helping you to generate machine code
  and interact with VM
• It is more a philosophy than technology
A philosophy



{
    •   ALL interesting stuff should happen at
        language side

    •   No need to recompile VM each time you need
        to change something

    •   You should be able to ship your code in
        smalltalk. And it should work out of the box.
A philosophy...

• A VM plugin is essentially small and
  contain no complex logic:

    fnPtr = (sqInt (*)(void)) retrieveCodeAddress();
    result = fnPtr();
How does it works
• We’re extending a CompiledMethod
  trailer to carry a native code
• All native code is invoked via single
  primitive, provided by NativeBoost
  plugin: #primitiveNativeCall

 someMethod: x y: y z: z
 	

 <primitive: #primitiveNativeCall
        module: #NativeBoostPlugin>
        ...
Project components
• AsmJit - an assembler
• NativeBoost-Core - the core
  implementation
• NativeBoost-Unix/Mac/Win32 - a
  platform-specific support code
• Tests
• Examples
AsmJit - a simple
           assembler
| asm |                       	

   asm
asm := AJx86Assembler new.    	

   	

 mov: EAX ptr - 1 -> EAX;
asm                           	

   	

 mov: EBX ptr + ECX * 2 - 5 -> EAX.
   push: asm EBP;
   mov: asm ESP -> asm EBP;   	

   asm
   mov: 1024 -> asm EAX;      	

   	

 label: #label1;
   mov: asm EBP -> asm ESP;   	

   	

 nop;
   pop: asm EBP;              	

   	

 nop;
   ret;                       	

   	

 nop;
   bytes.                     	

   	

 jz: #label1.


    an x86 assembler as it is (just in smalltalk ;)
NativeBoost-Core
• A top-level interface (NativeBoost class)
• VM interface (NBInterpreterProxy)
• FFI callout interface (NBFFICallout)
• C argument(s)/return type marshaling
  (NativeBoost-Core-Types)
• interface for generating native
  functions: NBNativeFunctionGen
• callbacks *
NativeBoost interface
• contains code for bootstrapping a
  NativeBoost on target platform
• provides a default interface for external
  memory management (#alloc: / #free: )
• provides a default interface for loading
  external libraries and looking up their
  symbols
• subclasses taking care about platform-
  specific nuances
NBInterpreterProxy
•   InterpreterProxy is a table of functions
    pointers - a public API of VM
    (sqVirtualMachine.h/.c)
•   NBInterpreterProxy main purpose is
    interacting with VM: retrieving method’s
    arguments, accessing object’s state etc
•   some VM functions may trigger GC,
    therefore we have a limitation:
    generated native code should be
    relocation agnostic
NBFFICallout

• responsible for generating a machine
  code to make foreign calls
• support for different calling conventions
  (currently - cdecl and stdcall)
• provides a simple default interface for
  making foreign calls
First foreign call
man getenv ...

NAME
  getenv, putenv, setenv, unsetenv -- environment variable functions

LIBRARY
   Standard C Library (libc, -lc)

SYNOPSIS
  #include <stdlib.h>

   char *
   getenv(const char *name);

RETURN VALUES
    The getenv() function returns the value of the environment variable as a NUL-terminated
string. If the variable name is not in the current environment, NULL is returned.
Calling getenv...
getEnv: name

	

   <primitive: #primitiveNativeCall module: #NativeBoostPlugin>
	

	

   ^ NBFFICallout cdecl: #(
	

   	

    String getenv( String name)
	

   	

 ) module: NativeBoost CLibrary
The magic
•   initially, a compiled method is just a method
    with primitive

•   on a first call a primitive fails, leading to
    entering a method body

•   NBFFICallout then generating machine code,
    installs it into caller’s method and retry the
    message send

•   machine code embedded into a method =>
    its life cycle same as method where its
    installed
Forming a foreign call in
                    detail
getEnv: name
	

   	

   <primitive: #primitiveNativeCall module: #NativeBoostPlugin>


	

   ^ NBFFICallout cdecl: #(
	

   	

            String getenv ( String name, ... )
	

   	

          ) module: NativeBoost CLibrary

cdecl - call convention              module - the module name or its handle,
String - return type                 where to look for a function
getenv - function name
String - argument type
name - argument name
Passing arguments
HeapAlloc Function

Allocates a block of memory from a heap. The allocated memory is not movable.
Syntax
                                                     dwFlags [in]

LPVOID WINAPI HeapAlloc(                          HEAP_GENERATE_EXCEPTIONS
   __in  HANDLE hHeap,                            0x00000004
   __in  DWORD dwFlags,                           HEAP_NO_SERIALIZE
   __in  SIZE_T dwBytes                           0x00000001
);                                                HEAP_ZERO_MEMORY
                                                  0x00000008



http://msdn.microsoft.com/en-us/library/aa366597%28v=vs.85%29.aspx
Naive approach
heapAlloc: aHeap flags: aFlags size: numberOfBytes
<primitive: #primitiveNativeCall module: #NativeBoostPlugin>

	

   ^ NBFFICallout stdcall: #(
LPVOID HeapAlloc (HANDLE aHeap , DWORD aFlags ,
SIZE_T numberOfBytes))
      module: #Kernel32


  NBWin32Heap>>allocate: numBytes
  ^ self heapAlloc: heap flags: 0 size: numBytes

  NBWin32Heap>>zalloc: numBytes
  ^ self heapAlloc: heap flags: HEAP_ZERO_MEMORY size: numBytes
Clever approach
NBWin32Heap>>alloc: numberOfBytes
	

   <primitive: #primitiveNativeCall module: #NativeBoostPlugin>

	

   ^ NBFFICallout stdcall: #(

LPVOID HeapAlloc (self , 0 , SIZE_T numberOfBytes)
       ) module: #Kernel32




NBWin32Heap>>zalloc: numberOfBytes
	

   <primitive: #primitiveNativeCall module: #NativeBoostPlugin>

	

   ^ NBFFICallout stdcall: #(

LPVOID HeapAlloc (self , HEAP_ZERO_MEMORY , SIZE_T numberOfBytes)
      )module: #Kernel32
Types

• support for basic C types: int, float etc
• type aliases: map a name to one of the
  basic types
• C structures (see NBExternalStructure
  and subclasses)
Custom types


• subclass NBExternalType
• (demonstrate NBUTF8StringExample)
Getting rid of bloat
heapAlloc: aHeap flags: aFlags size: numberOfBytes

<primitive: #primitiveNativeCall module: #NativeBoostPlugin>

	

   ^ self call: #( .... )


                        It’s just a smalltalk code
Examples & Demo
Future plans

• integrate callback mechanism
• support for non-blocking call mode
• integration with JIT
?
The end

More Related Content

PPTX
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
PDF
Experiments in Sharing Java VM Technology with CRuby
PDF
Blocks & GCD
PDF
Create your own PHP extension, step by step - phpDay 2012 Verona
KEY
Node.js - Best practices
PDF
Handling inline assembly in Clang and LLVM
PDF
JRuby 9000 - Taipei Ruby User's Group 2015
PPTX
HipHop Virtual Machine
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
Experiments in Sharing Java VM Technology with CRuby
Blocks & GCD
Create your own PHP extension, step by step - phpDay 2012 Verona
Node.js - Best practices
Handling inline assembly in Clang and LLVM
JRuby 9000 - Taipei Ruby User's Group 2015
HipHop Virtual Machine

What's hot (20)

PDF
Clojure and the Web
KEY
Know yourengines velocity2011
PDF
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
PDF
Inside the JVM - Follow the white rabbit!
KEY
Dispatch in Clojure
PDF
Objective-C Blocks and Grand Central Dispatch
ODP
Asynchronous I/O in NodeJS - new standard or challenges?
PDF
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
PDF
Skiron - Experiments in CPU Design in D
PDF
Practical Testing of Ruby Core
PDF
clWrap: Nonsense free control of your GPU
PDF
Asynchronous single page applications without a line of HTML or Javascript, o...
PDF
HHVM and Hack: A quick introduction
PPTX
Pune-Cocoa: Blocks and GCD
PPT
Intro2 Cuda Moayad
PDF
Top 10 Perl Performance Tips
PDF
node ffi
PPTX
HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook)
PDF
TensorFlow local Python XLA client
PDF
Arduino C maXbox web of things slide show
Clojure and the Web
Know yourengines velocity2011
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
Inside the JVM - Follow the white rabbit!
Dispatch in Clojure
Objective-C Blocks and Grand Central Dispatch
Asynchronous I/O in NodeJS - new standard or challenges?
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Skiron - Experiments in CPU Design in D
Practical Testing of Ruby Core
clWrap: Nonsense free control of your GPU
Asynchronous single page applications without a line of HTML or Javascript, o...
HHVM and Hack: A quick introduction
Pune-Cocoa: Blocks and GCD
Intro2 Cuda Moayad
Top 10 Perl Performance Tips
node ffi
HHVM: Efficient and Scalable PHP/Hack Execution / Guilherme Ottoni (Facebook)
TensorFlow local Python XLA client
Arduino C maXbox web of things slide show
Ad

Similar to NativeBoost (20)

PDF
NativeBoost
PPTX
Android ndk
PDF
Compromising Linux Virtual Machines with Debugging Mechanisms
PDF
Raffaele Rialdi
PDF
Using the Android Native Development Kit (NDK)
PDF
Tips and tricks for building high performance android apps using native code
PDF
.NET Core, ASP.NET Core Course, Session 5
PDF
Using the Android Native Development Kit (NDK)
PPTX
Using the android ndk - DroidCon Paris 2014
PDF
"Making OpenCV Code Run Fast," a Presentation from Intel
PPTX
NASM Introduction.pptx
KEY
Using Smalltalk for controlling robotics systems
PDF
Efficient Bytecode Analysis: Linespeed Shellcode Detection
PDF
Perl at SkyCon'12
PDF
Automation with Ansible and Containers
PPTX
Intro To Node.js
PDF
NodeJS for Beginner
PPTX
C++ in kernel mode
PPTX
GOTO Night with Charles Nutter Slides
PPTX
introduction to node.js
NativeBoost
Android ndk
Compromising Linux Virtual Machines with Debugging Mechanisms
Raffaele Rialdi
Using the Android Native Development Kit (NDK)
Tips and tricks for building high performance android apps using native code
.NET Core, ASP.NET Core Course, Session 5
Using the Android Native Development Kit (NDK)
Using the android ndk - DroidCon Paris 2014
"Making OpenCV Code Run Fast," a Presentation from Intel
NASM Introduction.pptx
Using Smalltalk for controlling robotics systems
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Perl at SkyCon'12
Automation with Ansible and Containers
Intro To Node.js
NodeJS for Beginner
C++ in kernel mode
GOTO Night with Charles Nutter Slides
introduction to node.js
Ad

More from ESUG (20)

PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
PDF
Directing Generative AI for Pharo Documentation
PDF
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
PDF
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
PDF
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
PDF
Analysing Python Machine Learning Notebooks with Moose
PDF
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
PDF
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
PDF
Package-Aware Approach for Repository-Level Code Completion in Pharo
PDF
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
PDF
An Analysis of Inline Method Refactoring
PDF
Identification of unnecessary object allocations using static escape analysis
PDF
Control flow-sensitive optimizations In the Druid Meta-Compiler
PDF
Clean Blocks (IWST 2025, Gdansk, Poland)
PDF
Encoding for Objects Matters (IWST 2025)
PDF
Challenges of Transpiling Smalltalk to JavaScript
PDF
Immersive experiences: what Pharo users do!
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
PDF
Cavrois - an Organic Window Management (ESUG 2025)
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
Micromaid: A simple Mermaid-like chart generator for Pharo
Directing Generative AI for Pharo Documentation
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
Analysing Python Machine Learning Notebooks with Moose
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
Package-Aware Approach for Repository-Level Code Completion in Pharo
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
An Analysis of Inline Method Refactoring
Identification of unnecessary object allocations using static escape analysis
Control flow-sensitive optimizations In the Druid Meta-Compiler
Clean Blocks (IWST 2025, Gdansk, Poland)
Encoding for Objects Matters (IWST 2025)
Challenges of Transpiling Smalltalk to JavaScript
Immersive experiences: what Pharo users do!
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
Cavrois - an Organic Window Management (ESUG 2025)

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
KodekX | Application Modernization Development
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Empathic Computing: Creating Shared Understanding
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
cuic standard and advanced reporting.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MYSQL Presentation for SQL database connectivity
KodekX | Application Modernization Development
Spectral efficient network and resource selection model in 5G networks
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
sap open course for s4hana steps from ECC to s4
Digital-Transformation-Roadmap-for-Companies.pptx
Programs and apps: productivity, graphics, security and other tools
“AI and Expert System Decision Support & Business Intelligence Systems”
Review of recent advances in non-invasive hemoglobin estimation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The AUB Centre for AI in Media Proposal.docx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)

NativeBoost

  • 1. NativeBoost Igor Stasenko August, 2011 ESUG Conference
  • 2. Before we start • http://code.google.com/p/nativeboost/ wiki/Installation
  • 3. What is NativeBoost? • A plugin for VM which allows you to run machine code generated in image • A set of utilities at language side which helping you to generate machine code and interact with VM • It is more a philosophy than technology
  • 4. A philosophy { • ALL interesting stuff should happen at language side • No need to recompile VM each time you need to change something • You should be able to ship your code in smalltalk. And it should work out of the box.
  • 5. A philosophy... • A VM plugin is essentially small and contain no complex logic: fnPtr = (sqInt (*)(void)) retrieveCodeAddress(); result = fnPtr();
  • 6. How does it works • We’re extending a CompiledMethod trailer to carry a native code • All native code is invoked via single primitive, provided by NativeBoost plugin: #primitiveNativeCall someMethod: x y: y z: z <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ...
  • 7. Project components • AsmJit - an assembler • NativeBoost-Core - the core implementation • NativeBoost-Unix/Mac/Win32 - a platform-specific support code • Tests • Examples
  • 8. AsmJit - a simple assembler | asm | asm asm := AJx86Assembler new. mov: EAX ptr - 1 -> EAX; asm mov: EBX ptr + ECX * 2 - 5 -> EAX. push: asm EBP; mov: asm ESP -> asm EBP; asm mov: 1024 -> asm EAX; label: #label1; mov: asm EBP -> asm ESP; nop; pop: asm EBP; nop; ret; nop; bytes. jz: #label1. an x86 assembler as it is (just in smalltalk ;)
  • 9. NativeBoost-Core • A top-level interface (NativeBoost class) • VM interface (NBInterpreterProxy) • FFI callout interface (NBFFICallout) • C argument(s)/return type marshaling (NativeBoost-Core-Types) • interface for generating native functions: NBNativeFunctionGen • callbacks *
  • 10. NativeBoost interface • contains code for bootstrapping a NativeBoost on target platform • provides a default interface for external memory management (#alloc: / #free: ) • provides a default interface for loading external libraries and looking up their symbols • subclasses taking care about platform- specific nuances
  • 11. NBInterpreterProxy • InterpreterProxy is a table of functions pointers - a public API of VM (sqVirtualMachine.h/.c) • NBInterpreterProxy main purpose is interacting with VM: retrieving method’s arguments, accessing object’s state etc • some VM functions may trigger GC, therefore we have a limitation: generated native code should be relocation agnostic
  • 12. NBFFICallout • responsible for generating a machine code to make foreign calls • support for different calling conventions (currently - cdecl and stdcall) • provides a simple default interface for making foreign calls
  • 13. First foreign call man getenv ... NAME getenv, putenv, setenv, unsetenv -- environment variable functions LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> char * getenv(const char *name); RETURN VALUES The getenv() function returns the value of the environment variable as a NUL-terminated string. If the variable name is not in the current environment, NULL is returned.
  • 14. Calling getenv... getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ NBFFICallout cdecl: #( String getenv( String name) ) module: NativeBoost CLibrary
  • 15. The magic • initially, a compiled method is just a method with primitive • on a first call a primitive fails, leading to entering a method body • NBFFICallout then generating machine code, installs it into caller’s method and retry the message send • machine code embedded into a method => its life cycle same as method where its installed
  • 16. Forming a foreign call in detail getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ NBFFICallout cdecl: #( String getenv ( String name, ... ) ) module: NativeBoost CLibrary cdecl - call convention module - the module name or its handle, String - return type where to look for a function getenv - function name String - argument type name - argument name
  • 17. Passing arguments HeapAlloc Function Allocates a block of memory from a heap. The allocated memory is not movable. Syntax dwFlags [in] LPVOID WINAPI HeapAlloc( HEAP_GENERATE_EXCEPTIONS __in  HANDLE hHeap, 0x00000004 __in  DWORD dwFlags, HEAP_NO_SERIALIZE __in  SIZE_T dwBytes 0x00000001 ); HEAP_ZERO_MEMORY 0x00000008 http://msdn.microsoft.com/en-us/library/aa366597%28v=vs.85%29.aspx
  • 18. Naive approach heapAlloc: aHeap flags: aFlags size: numberOfBytes <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ NBFFICallout stdcall: #( LPVOID HeapAlloc (HANDLE aHeap , DWORD aFlags , SIZE_T numberOfBytes)) module: #Kernel32 NBWin32Heap>>allocate: numBytes ^ self heapAlloc: heap flags: 0 size: numBytes NBWin32Heap>>zalloc: numBytes ^ self heapAlloc: heap flags: HEAP_ZERO_MEMORY size: numBytes
  • 19. Clever approach NBWin32Heap>>alloc: numberOfBytes <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ NBFFICallout stdcall: #( LPVOID HeapAlloc (self , 0 , SIZE_T numberOfBytes) ) module: #Kernel32 NBWin32Heap>>zalloc: numberOfBytes <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ NBFFICallout stdcall: #( LPVOID HeapAlloc (self , HEAP_ZERO_MEMORY , SIZE_T numberOfBytes) )module: #Kernel32
  • 20. Types • support for basic C types: int, float etc • type aliases: map a name to one of the basic types • C structures (see NBExternalStructure and subclasses)
  • 21. Custom types • subclass NBExternalType • (demonstrate NBUTF8StringExample)
  • 22. Getting rid of bloat heapAlloc: aHeap flags: aFlags size: numberOfBytes <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self call: #( .... ) It’s just a smalltalk code
  • 24. Future plans • integrate callback mechanism • support for non-blocking call mode • integration with JIT
  • 25. ?