SlideShare una empresa de Scribd logo
1 de 50
Descargar para leer sin conexión
NativeBoost
tutorial: using an external library from Pharo
#ESUG2013
To follow along…
For support files, tutorial steps, links, workarounds…
http://db.tt/VcuYEo2N
What’s ahead
extending Storm, a Pharo binding to the Chipmunk2D library
basics of FFI with NativeBoost :
function calls, handling values, structures, callbacks…
0 Prerequisites
x86 system with 32-bit libraries
cmake, C/C++ compiler
unix-ish shell environment (MinGW on windows)
Some understanding of C development tools & practices
how to build the C part, how it works, what it expects
A place to work
mkdir nbtutorial && cd nbtutorial each slide starts there
1 Get & build Chipmunk
cd nbtutorial
wget http://chipmunk-physics.net/release/Chipmunk-6.x/Chipmunk-6.1.5.tgz
tar xf Chipmunk-6.1.5.tgz && cd Chipmunk-6.1.5
cmake -DCMAKE_C_FLAGS='-m32 -DCHIPMUNK_FFI' . && make
to check if it works :
./Demo/chipmunk_demos
we will use the library as is,
no need to install it in your system
important !
32-bit & FFI support
2 VM & image
Get a recent VM
cd nbtutorial
curl http://get.pharo.org/vm | bash
Get the tutorial image
(included in the tutorial archive)
Gofer new
	
 smalltalkhubUser: 'estebanlm' project: 'Storm';
	
 configuration; load.
#ConfigurationOfStorm asClass loadBleedingEdge.
scratch install, for cheaters :
(spoilers)
2.1 Make chipmunk visible
NativeBoost needs to find the compiled library
dynamic linking is platform dependent (.dll, .so, .dylib…)
Symlink or copy the binary to where the image expects it :
ln -s Chipmunk-6.1.5/src/libchipmunk.dylib .
2.2 Trying Storm
./pharo-ui nbtutorial.image
StormFallingBallSlopes new start.
What if
I told you…
you’ve been hacking
within an image,
but there’s CODE
outside of it.
// Easy keyword replacement. Too easy to detect I think!
#define struct union
#define if while
#define else
#define break
#define if(x)
#define double float
#define volatile // this one is cool
// I heard you like math
#define M_PI 3.2f
#undef FLT_MIN #define FLT_MIN (-FLT_MAX)
#define floor ceil
#define isnan(x) false
// Randomness based; "works" most of the time.
#define true ((__LINE__&15)!=15)
#define true ((rand()&15)!=15)
#define if(x) if ((x) && (rand() < RAND_MAX * 0.99))
// String/memory handling, probably can live undetected quite long!
#define strcpy(a,b) memmove(a,b,strlen(b)+2)
#define strcpy(a,b) (((a & 0xFF) == (b & 0xFF)) ? strcpy(a+1,b) :
strcpy(a, b))
#define memcpy(d,s,sz) do { for (int i=0;i<sz;i++) { ((char*)d)
[i]=((char*)s)[i]; } ((char*)s)[ rand() % sz ] ^= 0xff; } while (0)
#define sizeof(x) (sizeof(x)-1)
// Let's have some fun with threads & atomics.
#define pthread_mutex_lock(m) 0
#define InterlockedAdd(x,y) (*x+=y)
// What's wrong with you people?!
#define __dcbt __dcbz // for PowerPC platforms
#define __dcbt __dcbf // for PowerPC platforms
#define __builtin_expect(a,b) b // for gcc
#define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false,
rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break
preprocessor_fun.h
https://gist.github.com/aras-p/6224951
NativeBoost…ok, but what’s NativeBoost?
NativeBoost
native code
(highly explosive)
low-level stuff
Boost!
Boost!
Boost!
Boost!
while NativeBoost is fast,
Today is about opening Pharo to new horizons.Photo CC-BY-NC Terry Feuerborn http://www.flickr.com/photos/travfotos/5431916497
hardware
operating system
virtual machine
image
What is NativeBoost?
compiler
primitives
CompiledMethod
NB plugin
NativeBoost
AsmJit
NativeBoost
• API for low-level (VM, C runtime)
• ad-hoc primitive methods (FFI)
• data marshalling
NB plugin: just a few primitives
• loading libraries (dlopen, dlsym)
• invoking native code
AsmJit: image-side assembler (x86)
NativeBoost FFI
Calling a C function from Pharo
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
a new method, bound to
NB’s native call primitive
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
the body describes
what to call & how
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
C signature, as a literal array
(almost copy-pasted)
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
method arguments
get passed to the
native callMyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
type marshalling (originally char *)
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
which library to load this function from
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
Physics simulation for 2D games
rigid bodies, collisions, constraints & joints
Physics only!
needs a game engine (graphics, events, animation loop)
we use Storm + Athens
Chipmunk Physics
http://chipmunk-physics.net
http://chipmunk-physics.net/release/ChipmunkLatest-Docs/
Basic concepts
Four main object types :
rigid bodies
collision shapes
constraints or joints
simulation spaces
Plus some utilities :
vectors, axis-aligned bounding boxes, math functions…
Rigid body
Physical properties of an object :
position of center of gravity
mass M, moment of inertia I
linear velocity V, angular velocity ω
C structure
include/chipmunk/cpBody.h
M,I
V
ω
Collision shapes
Describe the outer surface of a body
composed from circles, line segments, convex polygons
contact properties: friction, elasticity, or arbitrary callback
C structure
include/chipmunk/cpShape.h
cpPolyShape.h
Simulation space
Container for one physical simulation
add bodies, shapes, constraints
global properties: gravity, damping, static bodies…
C structure
include/chipmunk/cpSpace.h
Constraints
Describe how 2 rigid bodies interact
approximate, based on synchronizing velocities
mechanical constraints (pivot, groove, gears, limits, ratchet…)
active joints (motor, servo…)
C structure
include/chipmunk/constraints/*.h
looks like a small object-oriented system…
Looking around
3 Library setup
CmSpace >> addBody: body
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self nbCall: #(
	
 	
 	
 void cpSpaceAddBody ( self, CmBody body ) )
What about the module: part of nbCall: ?
where is the library specified ?
Library setup
CmSpace >> addBody: body
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self nbCall: #(
	
 	
 	
 void cpSpaceAddBody ( self, CmBody body ) )
CmSpace inherits this method :
nbLibraryNameOrHandle
	
 ^ 'libchipmunk.dylib'
4 Type mapping
CmSpace >> step: aNumber
	
 self primStep: aNumber asFloat
CmSpace >> primStep: time
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
^ self nbCall: #( void cpSpaceStep( self, cpFloat time ) )
Native code does NOT expect instances of Number !
What about class Float vs. cpFloat (chipmunk’s typedef) ?
Type mappings
Resolution mechanism, via pool variables (here, CmTypes)
look for implementors of asNBExternalType:
cpBool := #bool.
cpFloat := #float.
…
cpVect := #CmVector.
cpSpace := #CmSpace.
cpBody := #CmBody.
cpShape := #CmShape.
cpBB := #CmBoundingBox
what’s this ?
5 Indirect calls ?
CmSpace >> primGravity: aVector
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self indirectCall: #(
	
 	
 	
 	
 	
 void _cpSpaceSetGravity (self, CmVector aVector)
	
 	
 	
 	
 )
Inline functions are not exported by the library !
…so chipmunk_ffi.h defines this (very obvious indeed) macro :
#define MAKE_REF(name) __typeof__(name) *_##name = name
…then applies it to ~140 function names
Chipmunk FFI hacks
// include/chipmunk/cpVect.h
inline cpVect cpv(cpFloat x, cpFloat y)
{
cpVect v = {x, y};
return v;
}
cpVect (*_cpv)(cpFloat x, cpFloat y)
inline function
(not exported)
MAKE_REF(cpv);
exported alias,
but as a function pointer !
nbCall: does not expect a function pointer !
1. resolve symbol to
function pointer
2. follow pointer
3. invoke function
Indirect calls
CmExternalObject >> indirectCall: fnSpec
	
 | sender |
	
 sender := thisContext sender.
^ NBFFICallout handleFailureIn: sender nativeCode: [ :gen |
	
 	
 gen
	
 	
 	
 sender: sender;
	
 	
 	
 stdcall;
	
 	
 	
 namedFnSpec: fnSpec.
	
 	
 gen generate: [ :g |
	
 	
 	
 | fnAddress |
	
 	
 	
 fnAddress := self
	
 	
 	
 	
 nbGetSymbolAddress: gen fnSpec functionName
	
 	
 	
 	
 module: self nbLibraryNameOrHandle.
fnAddress ifNil: [ self error: 'function unavailable' ].
fnAddress := (fnAddress nbUInt32AtOffset: 0).
	
 	
 	
 gen asm
	
 	
 	
 	
 mov: fnAddress asUImm32 to: gen asm EAX;
	
 	
 	
 	
 call: gen asm EAX.
	
 	
 ]
]
Data structures
Structures vs. Objects
NBExternalStructure = C struct
no encapsulation
field sizes known
often used as a value
NBExternalObject = opaque type
C functions as accessors
handled via pointers
6 Structures
See class CmVector ? FORGET IT EVER EXISTED.
Now what ?
How to describe fields ?
How to access fields ?
from cpVect to CmVector
typedef struct cpVect {
	
 cpFloat x, y;
} cpVect;
CmExternalStructure subclass: #CmVector2
	
 instanceVariableNames: ''
	
 classVariableNames: ''
	
 poolDictionaries: ''
	
 category: 'Esug2013-NativeBoostTutorial'
from cpVect to CmVector
CmVector2 class >> fieldsDesc
	
 "self initializeAccessors"
	
 ^ #(
	
 	
 cpFloat x;
	
 	
 cpFloat y
	
 )
magic !
7 External Objects
See CmShape ? FORGET IT EVER EXISTED.
Now what ?
How to create instances ?
How to define methods ?
from cpShape to CmShape
CmExternalObject subclass: #CmShape2
	
 instanceVariableNames: ''
	
 classVariableNames: ''
	
 poolDictionaries: ''
	
 category: 'Esug2013-NativeBoostTutorial'
from cpShape to CmShape
cpShape *cpCircleShapeNew(
	
 cpBody *body,
	
 cpFloat radius, cpVect offset )
CmShape class >>
newCircleBody: aBody radius: radius offset: offsetPoint
	
 ^ (self
	
 	
 	
 primCpCircleShapeNew: aBody
	
 	
 	
 radius: radius asFloat
	
 	
 	
 offset: offsetPoint asCmVector)
	
 	
 initialize
from cpShape to CmShape
CmShape class >>
primCpCircleShapeNew: aBody radius: radius offset: offsetPoint
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ (self nbCall: #(
	
 	
 	
 CmShape cpCircleShapeNew(
	
 	
 	
 	
 CmBody body, cpFloat radius, CmVector offset ) )
8 Arrays
CmShape class >>
newPolygonBody: aBody vertices: hullVertices offset: aPoint
vertices := CmVector arrayClass new: hullVertices size.
hullVertices withIndexDo: [ :each :index |
vertices at: index put: each asCmVector ].
	
 ^ (self
	
 	
 	
 primCpPolygonNew: aBody
	
 	
 	
 verticesNumber: vertices size
	
 	
 	
 vertices: vertices address
	
 	
 	
 offset: aPoint asCmVector) initialize
Callbacks
Collision handling callbacks
begin
pre-solve
post-solve
separate
contact detected,
proceed with collision ?
shapes just
stopped touching
tweak contact properties
before processing
react to
computed impulse
Callback = block + signature
NBFFICallback subclass: #CmCollisionBegin
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: 'CmTypes'
category: 'Esug2013-NativeBoostTutorial'
CmCollisionBegin class >> fnSpec
^ #(int (void *arbiter, CmSpace space, void *data))
Tracing collisions
beginCallback :=
	
 CmCollisionBegin on: [ :arbiter :space :data |
	
 	
 	
 Transcript show: 'begin'; cr.
	
 	
 	
 1 ].
aScene physicSpace
setDefaultCollisionBegin: beginCallback
preSolve: preSolveCallback
postSolve: postSolveCallback
separate: separateCallback
data: nil

Más contenido relacionado

La actualidad más candente

Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorialnikomatsakis
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnMoriyoshi Koizumi
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objectsjulien pauli
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machinejulien pauli
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)James Titcumb
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 

La actualidad más candente (20)

node ffi
node ffinode ffi
node ffi
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 

Similar a NativeBoost

NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbJuan Maiz
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeKenneth Geisshirt
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)fefe7270
 
GC in Smalltalk - Now What?
GC in Smalltalk - Now What?GC in Smalltalk - Now What?
GC in Smalltalk - Now What?ESUG
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaXKernel TLV
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceJesse Vincent
 

Similar a NativeBoost (20)

NativeBoost
NativeBoostNativeBoost
NativeBoost
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)Surface flingerservice(서피스플링거서비스초기화)
Surface flingerservice(서피스플링거서비스초기화)
 
GC in Smalltalk - Now What?
GC in Smalltalk - Now What?GC in Smalltalk - Now What?
GC in Smalltalk - Now What?
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
 

Más de ESUG

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingESUG
 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in PharoESUG
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapESUG
 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoESUG
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...ESUG
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsESUG
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6ESUG
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationESUG
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingESUG
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesESUG
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportESUG
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsESUG
 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector TuningESUG
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseESUG
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FutureESUG
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the DebuggerESUG
 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing ScoreESUG
 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptESUG
 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocESUG
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsESUG
 

Más de ESUG (20)

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in Pharo
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in Pharo
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector Tuning
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing Score
 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design Mooc
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
 

Último

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Último (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

NativeBoost

  • 1. NativeBoost tutorial: using an external library from Pharo #ESUG2013
  • 2. To follow along… For support files, tutorial steps, links, workarounds… http://db.tt/VcuYEo2N What’s ahead extending Storm, a Pharo binding to the Chipmunk2D library basics of FFI with NativeBoost : function calls, handling values, structures, callbacks…
  • 3. 0 Prerequisites x86 system with 32-bit libraries cmake, C/C++ compiler unix-ish shell environment (MinGW on windows) Some understanding of C development tools & practices how to build the C part, how it works, what it expects A place to work mkdir nbtutorial && cd nbtutorial each slide starts there
  • 4. 1 Get & build Chipmunk cd nbtutorial wget http://chipmunk-physics.net/release/Chipmunk-6.x/Chipmunk-6.1.5.tgz tar xf Chipmunk-6.1.5.tgz && cd Chipmunk-6.1.5 cmake -DCMAKE_C_FLAGS='-m32 -DCHIPMUNK_FFI' . && make to check if it works : ./Demo/chipmunk_demos we will use the library as is, no need to install it in your system important ! 32-bit & FFI support
  • 5. 2 VM & image Get a recent VM cd nbtutorial curl http://get.pharo.org/vm | bash Get the tutorial image (included in the tutorial archive) Gofer new smalltalkhubUser: 'estebanlm' project: 'Storm'; configuration; load. #ConfigurationOfStorm asClass loadBleedingEdge. scratch install, for cheaters : (spoilers)
  • 6. 2.1 Make chipmunk visible NativeBoost needs to find the compiled library dynamic linking is platform dependent (.dll, .so, .dylib…) Symlink or copy the binary to where the image expects it : ln -s Chipmunk-6.1.5/src/libchipmunk.dylib .
  • 7. 2.2 Trying Storm ./pharo-ui nbtutorial.image StormFallingBallSlopes new start.
  • 8.
  • 9. What if I told you…
  • 10. you’ve been hacking within an image, but there’s CODE outside of it. // Easy keyword replacement. Too easy to detect I think! #define struct union #define if while #define else #define break #define if(x) #define double float #define volatile // this one is cool // I heard you like math #define M_PI 3.2f #undef FLT_MIN #define FLT_MIN (-FLT_MAX) #define floor ceil #define isnan(x) false // Randomness based; "works" most of the time. #define true ((__LINE__&15)!=15) #define true ((rand()&15)!=15) #define if(x) if ((x) && (rand() < RAND_MAX * 0.99)) // String/memory handling, probably can live undetected quite long! #define strcpy(a,b) memmove(a,b,strlen(b)+2) #define strcpy(a,b) (((a & 0xFF) == (b & 0xFF)) ? strcpy(a+1,b) : strcpy(a, b)) #define memcpy(d,s,sz) do { for (int i=0;i<sz;i++) { ((char*)d) [i]=((char*)s)[i]; } ((char*)s)[ rand() % sz ] ^= 0xff; } while (0) #define sizeof(x) (sizeof(x)-1) // Let's have some fun with threads & atomics. #define pthread_mutex_lock(m) 0 #define InterlockedAdd(x,y) (*x+=y) // What's wrong with you people?! #define __dcbt __dcbz // for PowerPC platforms #define __dcbt __dcbf // for PowerPC platforms #define __builtin_expect(a,b) b // for gcc #define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false, rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break preprocessor_fun.h https://gist.github.com/aras-p/6224951
  • 12. NativeBoost native code (highly explosive) low-level stuff Boost! Boost! Boost! Boost!
  • 13. while NativeBoost is fast, Today is about opening Pharo to new horizons.Photo CC-BY-NC Terry Feuerborn http://www.flickr.com/photos/travfotos/5431916497
  • 14. hardware operating system virtual machine image What is NativeBoost? compiler primitives CompiledMethod NB plugin NativeBoost AsmJit NativeBoost • API for low-level (VM, C runtime) • ad-hoc primitive methods (FFI) • data marshalling NB plugin: just a few primitives • loading libraries (dlopen, dlsym) • invoking native code AsmJit: image-side assembler (x86)
  • 15. NativeBoost FFI Calling a C function from Pharo MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 16. a new method, bound to NB’s native call primitive MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 17. the body describes what to call & how MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 18. C signature, as a literal array (almost copy-pasted) MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 19. method arguments get passed to the native callMyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 20. type marshalling (originally char *) MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 21. which library to load this function from MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 22.
  • 23. Physics simulation for 2D games rigid bodies, collisions, constraints & joints Physics only! needs a game engine (graphics, events, animation loop) we use Storm + Athens Chipmunk Physics http://chipmunk-physics.net http://chipmunk-physics.net/release/ChipmunkLatest-Docs/
  • 24. Basic concepts Four main object types : rigid bodies collision shapes constraints or joints simulation spaces Plus some utilities : vectors, axis-aligned bounding boxes, math functions…
  • 25. Rigid body Physical properties of an object : position of center of gravity mass M, moment of inertia I linear velocity V, angular velocity ω C structure include/chipmunk/cpBody.h M,I V ω
  • 26. Collision shapes Describe the outer surface of a body composed from circles, line segments, convex polygons contact properties: friction, elasticity, or arbitrary callback C structure include/chipmunk/cpShape.h cpPolyShape.h
  • 27. Simulation space Container for one physical simulation add bodies, shapes, constraints global properties: gravity, damping, static bodies… C structure include/chipmunk/cpSpace.h
  • 28. Constraints Describe how 2 rigid bodies interact approximate, based on synchronizing velocities mechanical constraints (pivot, groove, gears, limits, ratchet…) active joints (motor, servo…) C structure include/chipmunk/constraints/*.h looks like a small object-oriented system…
  • 30. 3 Library setup CmSpace >> addBody: body <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceAddBody ( self, CmBody body ) ) What about the module: part of nbCall: ? where is the library specified ?
  • 31. Library setup CmSpace >> addBody: body <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceAddBody ( self, CmBody body ) ) CmSpace inherits this method : nbLibraryNameOrHandle ^ 'libchipmunk.dylib'
  • 32. 4 Type mapping CmSpace >> step: aNumber self primStep: aNumber asFloat CmSpace >> primStep: time <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceStep( self, cpFloat time ) ) Native code does NOT expect instances of Number ! What about class Float vs. cpFloat (chipmunk’s typedef) ?
  • 33. Type mappings Resolution mechanism, via pool variables (here, CmTypes) look for implementors of asNBExternalType: cpBool := #bool. cpFloat := #float. … cpVect := #CmVector. cpSpace := #CmSpace. cpBody := #CmBody. cpShape := #CmShape. cpBB := #CmBoundingBox
  • 34. what’s this ? 5 Indirect calls ? CmSpace >> primGravity: aVector <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self indirectCall: #( void _cpSpaceSetGravity (self, CmVector aVector) )
  • 35. Inline functions are not exported by the library ! …so chipmunk_ffi.h defines this (very obvious indeed) macro : #define MAKE_REF(name) __typeof__(name) *_##name = name …then applies it to ~140 function names Chipmunk FFI hacks // include/chipmunk/cpVect.h inline cpVect cpv(cpFloat x, cpFloat y) { cpVect v = {x, y}; return v; } cpVect (*_cpv)(cpFloat x, cpFloat y) inline function (not exported) MAKE_REF(cpv); exported alias, but as a function pointer !
  • 36. nbCall: does not expect a function pointer ! 1. resolve symbol to function pointer 2. follow pointer 3. invoke function Indirect calls CmExternalObject >> indirectCall: fnSpec | sender | sender := thisContext sender. ^ NBFFICallout handleFailureIn: sender nativeCode: [ :gen | gen sender: sender; stdcall; namedFnSpec: fnSpec. gen generate: [ :g | | fnAddress | fnAddress := self nbGetSymbolAddress: gen fnSpec functionName module: self nbLibraryNameOrHandle. fnAddress ifNil: [ self error: 'function unavailable' ]. fnAddress := (fnAddress nbUInt32AtOffset: 0). gen asm mov: fnAddress asUImm32 to: gen asm EAX; call: gen asm EAX. ] ]
  • 38. Structures vs. Objects NBExternalStructure = C struct no encapsulation field sizes known often used as a value NBExternalObject = opaque type C functions as accessors handled via pointers
  • 39. 6 Structures See class CmVector ? FORGET IT EVER EXISTED. Now what ? How to describe fields ? How to access fields ?
  • 40. from cpVect to CmVector typedef struct cpVect { cpFloat x, y; } cpVect; CmExternalStructure subclass: #CmVector2 instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Esug2013-NativeBoostTutorial'
  • 41. from cpVect to CmVector CmVector2 class >> fieldsDesc "self initializeAccessors" ^ #( cpFloat x; cpFloat y ) magic !
  • 42. 7 External Objects See CmShape ? FORGET IT EVER EXISTED. Now what ? How to create instances ? How to define methods ?
  • 43. from cpShape to CmShape CmExternalObject subclass: #CmShape2 instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Esug2013-NativeBoostTutorial'
  • 44. from cpShape to CmShape cpShape *cpCircleShapeNew( cpBody *body, cpFloat radius, cpVect offset ) CmShape class >> newCircleBody: aBody radius: radius offset: offsetPoint ^ (self primCpCircleShapeNew: aBody radius: radius asFloat offset: offsetPoint asCmVector) initialize
  • 45. from cpShape to CmShape CmShape class >> primCpCircleShapeNew: aBody radius: radius offset: offsetPoint <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ (self nbCall: #( CmShape cpCircleShapeNew( CmBody body, cpFloat radius, CmVector offset ) )
  • 46. 8 Arrays CmShape class >> newPolygonBody: aBody vertices: hullVertices offset: aPoint vertices := CmVector arrayClass new: hullVertices size. hullVertices withIndexDo: [ :each :index | vertices at: index put: each asCmVector ]. ^ (self primCpPolygonNew: aBody verticesNumber: vertices size vertices: vertices address offset: aPoint asCmVector) initialize
  • 48. Collision handling callbacks begin pre-solve post-solve separate contact detected, proceed with collision ? shapes just stopped touching tweak contact properties before processing react to computed impulse
  • 49. Callback = block + signature NBFFICallback subclass: #CmCollisionBegin instanceVariableNames: '' classVariableNames: '' poolDictionaries: 'CmTypes' category: 'Esug2013-NativeBoostTutorial' CmCollisionBegin class >> fnSpec ^ #(int (void *arbiter, CmSpace space, void *data))
  • 50. Tracing collisions beginCallback := CmCollisionBegin on: [ :arbiter :space :data | Transcript show: 'begin'; cr. 1 ]. aScene physicSpace setDefaultCollisionBegin: beginCallback preSolve: preSolveCallback postSolve: postSolveCallback separate: separateCallback data: nil