SlideShare a Scribd company logo
http://strikr.in/ CC BY NC-SA 4.0
unsafe, cgo and go plugins
saifi@acm.org
http://strikr.in/ CC BY NC-SA 4.0
In the world of 'go'
● Safety guarantees
– Static checks
● Type checks
● Strict rules for type conversions
– Dynamic checks
● Out-of-array bounds
● Nil pointer references
http://strikr.in/ CC BY NC-SA 4.0
In the world of 'go' ...
● Implementation details are not accessible
– Discover layout of struct
– Pointer identifies a variable without revealing
its address.
– Identity of the OS thread on which the current
stackless function (g*) is running
– Go scheduler moves stackless function (g*)
from one thread to another.
– Address changes and pointer updates as
garbage collector moves variables
http://strikr.in/ CC BY NC-SA 4.0
Side stepping the safety
● unsafe
● Expose details of Go
memory layout
● Looks like a regular
package
● Import “unsafe”
● Actually implemented
by the compiler
os
runtime
syscall
net
unsafe
http://strikr.in/ CC BY NC-SA 4.0
unsafe
src/unsafe/unsafe.go
type ArbitraryType int
type Pointer *ArbitraryType
func Sizeof (x ArbitraryType) uintptr
func Offsetof (x ArbitraryType) uintptr
func AlignOf (x ArbitraryType) uintptr
go vet may help but can't depend on it.
http://strikr.in/ CC BY NC-SA 4.0
unsafe pointer manipulation
func get_address (f float64) uint64 {
pT := unsafe.Pointer (&f)
p := (*uint64)(pT)
*p = 7.0
return *p
}
func main () {
num := 1.0
fmt.Printf ("%f n", num)
fmt.Printf ("%#016x n", get_address (num))
fmt.Printf ("%f n", num)
}
http://strikr.in/ CC BY NC-SA 4.0
Code organization 101
● As functionality grows, functions are
categorized together
● Unit of organization is then
– Static library
– Dynamic library
● Calling convention defined to support linkage
considerations
– Who cleans up the stack
– What happens to name mangling
http://strikr.in/ CC BY NC-SA 4.0
A C function calling a C function
from a library
char*
say
(const char *name);
file_libname.c
libname.so
Code gen option
-fPIC
linker option
-shared
http://strikr.in/ CC BY NC-SA 4.0
A C function calling a C function
from a library
main ()
char*
say
(const char *name);
file_caller.c file_libname.c
LD_LIBRARY_PATH
ld
libname.so
file_caller.c
CPATH
C_INCLUDE_PATH
cc
http://strikr.in/ CC BY NC-SA 4.0
Memory layout of C program
http://strikr.in/ CC BY NC-SA 4.0
A C function calling a C function
http://strikr.in/ CC BY NC-SA 4.0
Code organization 202
● Binary generated code is arranged in ELF
format
● Executable and Linkable Format
● Expressed in terms of sections
– .text
– .data
– .rodata
– .bss
● DWARF for debugging
http://strikr.in/ CC BY NC-SA 4.0
ELF
http://strikr.in/ CC BY NC-SA 4.0
Two views
http://strikr.in/ CC BY NC-SA 4.0
Code organization 303
● Dynamically loaded libraries
– Loaded on demand
– Used to implement plugins, modules
– On Linux built as standard object modules
● Linkage
– extern “C”
– no name mangling
http://strikr.in/ CC BY NC-SA 4.0
Code organization 303
● Infrastructure to work with sections and
symbols
– #include <dlfcn.h>
– /usr/include/dlfcn.h
– Same as in Solaris
● API
– dlopen()
– dlsym()
– dlerror()
– dlclose()
http://strikr.in/ CC BY NC-SA 4.0
Infrastructure to work with ELF
http://strikr.in/ CC BY NC-SA 4.0
Shared object API
● void * dlopen(const char *filename, int flag);
– Open the shared file and map it.
● void * dlsym(void *handle, char *symbol);
– Find the run-time address in shared object
● char *dlerror (void);
– Return a string describing the error.
● int dlclose (void *__handle);
– Unmap and close a shared object
http://strikr.in/ CC BY NC-SA 4.0
cgo
● Useful technology that allows Go to
interoperate with C libraries
● Generates Thunks and Stubs to bind
● C to Go
● Go to C
● Challenges
– Different stacks for Go and C
– Garbage collector 'drama'
●
http://strikr.in/ CC BY NC-SA 4.0
cgo
● package
– https://golang.org/cmd/cgo/
● Rules for passing pointers
– https://github.com/golang/proposal/blob/master/de
●
http://strikr.in/ CC BY NC-SA 4.0
char*
say
(const char *name);
file_caller.c file_libname.c
LD_LIBRARY_PATH
ld
libname.so
file_caller.go
CPATH
C_INCLUDE_PATH
cc
import “C”
Go code here
cgo
http://strikr.in/ CC BY NC-SA 4.0
cgo Pointer 'passing' restrictions
● Go code may pass a Go pointer to C provided
the Go memory to which it points does not
contain any Go pointers.
● C code must not store any Go pointers in Go
memory, even temporarily.
● C code may not keep a copy of a Go pointer
after the call returns.
● Go code may not store a Go pointer in C
memory.
● Checked dynamically at runtime
GODEBUG=cgocheck=2
http://strikr.in/ CC BY NC-SA 4.0
go packages and 'cgo'
crypto/x509
os/user
go/internal
cmd
net
runtime
runtime/cgo
runtime/race
conf_netcgo.go
cgo_stub.go
cgo_resnew.go
cgo_resold.go
cgo_sockold.go
cgo_socknew.go
cgo_linux.go
cgo_windows.go
cgo_openbsd.go
cgo_bsd.go
cgo_netbsd.go
cgo_solaris.go
cgo_unix.go
cgo_unix_test.go
cgo_android.go
src/net
http://strikr.in/ CC BY NC-SA 4.0
cgo – what to know
● Unavoidable when working with binary blob
– Graphics driver
– Windowing system
● Slower build times
– C compiler in focus, works on every C file
across packages to create a single .o file
– Linker works through .o file to resolve the
shared objects referenced
– Cross compiling not possible
http://strikr.in/ CC BY NC-SA 4.0
cgo – what to know
● cgo is not go, both cc and go compiler needed
● Cross-compiling is disabled when cgo is
operational
● Go tools don't work
● Performance issues due mis-matched 'call'
stacks
● C decides not Go (addr, sig, tls)
● No longer single static binary
● What was the garbage collector upto ;P
http://strikr.in/ CC BY NC-SA 4.0
cgo usage references
● 37: error : use of undeclared identifier
http://www.mischiefblog.com/2014/06/24/a-go-cgo-go
● Using C libraries with Go
https://jamesadam.me/2014/11/23/using-c-libraries-w
● cgo is not Go
https://dave.cheney.net/2016/01/18/cgo-is-not-go
http://strikr.in/ CC BY NC-SA 4.0
Gotcha's
● Why use unicode characters in function names
in the Go source code
https://groups.google.com/forum/#!msg/golang-nuts/
● Slashes and dots in function names in
prototypes
https://stackoverflow.com/questions/13475908/slashe
● errno
http://noeffclue.blogspot.in/2011/10/experimenting-wi
●
http://strikr.in/ CC BY NC-SA 4.0
plugin
● A plugin is a Go main package with exported
functions and variables that has been built with
– go build -buildmode=plugin
● Isomorphic to dlfcn design
● Plugins work only on Linux
● import “plugin”
● A plugin is only initialized once, and cannot be
closed.
● https://golang.org/pkg/plugin/
http://strikr.in/ CC BY NC-SA 4.0
plugins
● Export symbol
– using “//export”
● Leverage -buildmode argument
– go build -buildmode= archive
c-archive
c-shared
default
shared
exe
pie
plugin
http://strikr.in/ CC BY NC-SA 4.0
plugin
plugin.go
plugin_dlopen.go
plugin_stubs.go
type Plugin struct {
pluginpath string
loaded chan struct{} // closed when loaded
syms map[string]interface{}
}
func Open(path string) (*Plugin, error) {
return open(path)
}
func (p *Plugin) Lookup(symName string) (Symbol, error) {
return lookup(p, symName)
}
type Symbol interface{}
http://strikr.in/ CC BY NC-SA 4.0
plugin_dlopen.go
import “C”
static uintptr_t pluginOpen(const char* path, char** err);
static void* pluginLookup(uintptr_t h, const char* name, char** err);
func pathToPrefix(s string) string
func open(name string) (*Plugin, error)
func lookup(p *Plugin, symName string) (Symbol, error)
func lastmoduleinit() (pluginpath string, syms map[string]interface{}, mismatchpkg string)
C part
Go part
http://strikr.in/ CC BY NC-SA 4.0
plugin patterns
os.exec.Command()
pluginmain
RPC
stdOUT stdIN
stdIN stdOUT
os.exec.Command()
pluginmain
RPC
net.Conn
External process using RPC via std IN/OUT
External process using RPC via network
main
plugin plugin
nanomsg “scalability protocols”
Pair
PubSub
Bus
Survey
Pipeline
ReqRep
http://strikr.in/ CC BY NC-SA 4.0
Code references
● A toolkit for creating plugins for Go applications
https://github.com/natefinch/pie
● nanomsg socket library for several
communication patterns
http://nanomsg.org/
● scalable protocol implementations in Go
https://github.com/go-mangos/mangos
● Hashicorp go plugin system
https://github.com/hashicorp/go-plugin
http://strikr.in/ CC BY NC-SA 4.0
References
● Go plugins are easy as a pie
https://npf.io/2015/05/pie/
● Go lang plugin system over RPC
https://github.com/hashicorp/go-plugin
● Plugin in Go
https://appliedgo.net/plugins/
http://strikr.in/ CC BY NC-SA 4.0
Thank You
http://strikr.in/ CC BY NC-SA 4.0
Thank You

More Related Content

What's hot

Electron - Build cross platform desktop apps
Electron - Build cross platform desktop appsElectron - Build cross platform desktop apps
Electron - Build cross platform desktop appsPriyaranjan Mohanty
 
Ksplice - Keep your Database systems up to date with no downtime
Ksplice - Keep your Database systems up to date with no downtime Ksplice - Keep your Database systems up to date with no downtime
Ksplice - Keep your Database systems up to date with no downtime Luis Marques
 
Tutorial ns 3-tutorial-slides
Tutorial ns 3-tutorial-slidesTutorial ns 3-tutorial-slides
Tutorial ns 3-tutorial-slidesVinayagam D
 
Embedded Linux Quick Start Guide v1.5
Embedded Linux Quick Start Guide v1.5Embedded Linux Quick Start Guide v1.5
Embedded Linux Quick Start Guide v1.5Chris Simmonds
 
Ceph Day Taipei - Accelerate Ceph via SPDK
Ceph Day Taipei - Accelerate Ceph via SPDK Ceph Day Taipei - Accelerate Ceph via SPDK
Ceph Day Taipei - Accelerate Ceph via SPDK Ceph Community
 
LCE13: Android Graphics Upstreaming
LCE13: Android Graphics UpstreamingLCE13: Android Graphics Upstreaming
LCE13: Android Graphics UpstreamingLinaro
 
Building Topology in NS3
Building Topology in NS3Building Topology in NS3
Building Topology in NS3Rahul Hada
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchlinuxlab_conf
 
BeagleBone Black: Platform Bring-Up with Upstream Components
BeagleBone Black: Platform Bring-Up with Upstream ComponentsBeagleBone Black: Platform Bring-Up with Upstream Components
BeagleBone Black: Platform Bring-Up with Upstream ComponentsGlobalLogic Ukraine
 

What's hot (13)

Electron - Build cross platform desktop apps
Electron - Build cross platform desktop appsElectron - Build cross platform desktop apps
Electron - Build cross platform desktop apps
 
Ksplice - Keep your Database systems up to date with no downtime
Ksplice - Keep your Database systems up to date with no downtime Ksplice - Keep your Database systems up to date with no downtime
Ksplice - Keep your Database systems up to date with no downtime
 
Tutorial ns 3-tutorial-slides
Tutorial ns 3-tutorial-slidesTutorial ns 3-tutorial-slides
Tutorial ns 3-tutorial-slides
 
Embedded Linux Quick Start Guide v1.5
Embedded Linux Quick Start Guide v1.5Embedded Linux Quick Start Guide v1.5
Embedded Linux Quick Start Guide v1.5
 
Ceph Day Taipei - Accelerate Ceph via SPDK
Ceph Day Taipei - Accelerate Ceph via SPDK Ceph Day Taipei - Accelerate Ceph via SPDK
Ceph Day Taipei - Accelerate Ceph via SPDK
 
LCE13: Android Graphics Upstreaming
LCE13: Android Graphics UpstreamingLCE13: Android Graphics Upstreaming
LCE13: Android Graphics Upstreaming
 
Software user manual
Software user manualSoftware user manual
Software user manual
 
Building Topology in NS3
Building Topology in NS3Building Topology in NS3
Building Topology in NS3
 
ONOS
ONOSONOS
ONOS
 
Drupal
DrupalDrupal
Drupal
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratch
 
BeagleBone Black: Platform Bring-Up with Upstream Components
BeagleBone Black: Platform Bring-Up with Upstream ComponentsBeagleBone Black: Platform Bring-Up with Upstream Components
BeagleBone Black: Platform Bring-Up with Upstream Components
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 

Similar to cgo and Go plugins

from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?strikr .
 
OVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeOVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeChang W. Doh
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golangdo_aki
 
Developing with the Go client for Apache Kafka
Developing with the Go client for Apache KafkaDeveloping with the Go client for Apache Kafka
Developing with the Go client for Apache KafkaJoe Stein
 
The usage and dependency resolving mechanism of go module
The usage and dependency resolving mechanism of go moduleThe usage and dependency resolving mechanism of go module
The usage and dependency resolving mechanism of go moduleLung-Hsuan Hung
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
Scaling Development Environments with Docker
Scaling Development Environments with DockerScaling Development Environments with Docker
Scaling Development Environments with DockerDocker, Inc.
 
Crash course in git and github
Crash course in git and githubCrash course in git and github
Crash course in git and githubMithun Shanbhag
 
Android 5.0 Lollipop platform change investigation report
Android 5.0 Lollipop platform change investigation reportAndroid 5.0 Lollipop platform change investigation report
Android 5.0 Lollipop platform change investigation reporthidenorly
 
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScript
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScriptENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScript
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScriptHoracio Gonzalez
 
markedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMtakezoe
 
Porion a new Build Manager
Porion a new Build ManagerPorion a new Build Manager
Porion a new Build ManagerStephane Carrez
 
How to plan and define your CI-CD pipeline
How to plan and define your CI-CD pipelineHow to plan and define your CI-CD pipeline
How to plan and define your CI-CD pipelineElasTest Project
 
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808Cisco DevNet
 
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Pantheon
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingAlessandro Molina
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 

Similar to cgo and Go plugins (20)

from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?from Docker to Moby and back. what changed ?
from Docker to Moby and back. what changed ?
 
OVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source TreeOVERVIEW: Chromium Source Tree
OVERVIEW: Chromium Source Tree
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
 
Developing with the Go client for Apache Kafka
Developing with the Go client for Apache KafkaDeveloping with the Go client for Apache Kafka
Developing with the Go client for Apache Kafka
 
The usage and dependency resolving mechanism of go module
The usage and dependency resolving mechanism of go moduleThe usage and dependency resolving mechanism of go module
The usage and dependency resolving mechanism of go module
 
CI-CD WITH GITLAB WORKFLOW
CI-CD WITH GITLAB WORKFLOWCI-CD WITH GITLAB WORKFLOW
CI-CD WITH GITLAB WORKFLOW
 
Comparing C and Go
Comparing C and GoComparing C and Go
Comparing C and Go
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Scaling Development Environments with Docker
Scaling Development Environments with DockerScaling Development Environments with Docker
Scaling Development Environments with Docker
 
Crash course in git and github
Crash course in git and githubCrash course in git and github
Crash course in git and github
 
Android 5.0 Lollipop platform change investigation report
Android 5.0 Lollipop platform change investigation reportAndroid 5.0 Lollipop platform change investigation report
Android 5.0 Lollipop platform change investigation report
 
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScript
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScriptENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScript
ENIB 2015 2016 - CAI Web S02E03- Forge JS 1/4 - La forge JavaScript
 
markedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVM
 
Porion a new Build Manager
Porion a new Build ManagerPorion a new Build Manager
Porion a new Build Manager
 
How to plan and define your CI-CD pipeline
How to plan and define your CI-CD pipelineHow to plan and define your CI-CD pipeline
How to plan and define your CI-CD pipeline
 
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808
Golang 101 for IT-Pros - Cisco Live Orlando 2018 - DEVNET-1808
 
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears Training
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
01 - Git vs SVN
01 - Git vs SVN01 - Git vs SVN
01 - Git vs SVN
 

More from strikr .

Monitoring
MonitoringMonitoring
Monitoringstrikr .
 
OpenStack for Telco Cloud
OpenStack for Telco CloudOpenStack for Telco Cloud
OpenStack for Telco Cloudstrikr .
 
Oracle to PostgreSQL migration
Oracle to PostgreSQL migrationOracle to PostgreSQL migration
Oracle to PostgreSQL migrationstrikr .
 
Making Automation Work
Making Automation WorkMaking Automation Work
Making Automation Workstrikr .
 
Taking the Containers First Approach
Taking the Containers First ApproachTaking the Containers First Approach
Taking the Containers First Approachstrikr .
 
Docker enterprise Technologies
Docker enterprise TechnologiesDocker enterprise Technologies
Docker enterprise Technologiesstrikr .
 
Data Center to Cloud
Data Center to CloudData Center to Cloud
Data Center to Cloudstrikr .
 
containerD
containerDcontainerD
containerDstrikr .
 
OCI Image Spec
OCI Image SpecOCI Image Spec
OCI Image Specstrikr .
 
OCI Runtime Spec
OCI Runtime SpecOCI Runtime Spec
OCI Runtime Specstrikr .
 
Container Orchestration
Container OrchestrationContainer Orchestration
Container Orchestrationstrikr .
 
Referee project
Referee projectReferee project
Referee projectstrikr .
 
Immutable Infrastructure
Immutable InfrastructureImmutable Infrastructure
Immutable Infrastructurestrikr .
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Gostrikr .
 
Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking featuresstrikr .
 

More from strikr . (16)

Monitoring
MonitoringMonitoring
Monitoring
 
OpenStack for Telco Cloud
OpenStack for Telco CloudOpenStack for Telco Cloud
OpenStack for Telco Cloud
 
Oracle to PostgreSQL migration
Oracle to PostgreSQL migrationOracle to PostgreSQL migration
Oracle to PostgreSQL migration
 
DBOps
DBOpsDBOps
DBOps
 
Making Automation Work
Making Automation WorkMaking Automation Work
Making Automation Work
 
Taking the Containers First Approach
Taking the Containers First ApproachTaking the Containers First Approach
Taking the Containers First Approach
 
Docker enterprise Technologies
Docker enterprise TechnologiesDocker enterprise Technologies
Docker enterprise Technologies
 
Data Center to Cloud
Data Center to CloudData Center to Cloud
Data Center to Cloud
 
containerD
containerDcontainerD
containerD
 
OCI Image Spec
OCI Image SpecOCI Image Spec
OCI Image Spec
 
OCI Runtime Spec
OCI Runtime SpecOCI Runtime Spec
OCI Runtime Spec
 
Container Orchestration
Container OrchestrationContainer Orchestration
Container Orchestration
 
Referee project
Referee projectReferee project
Referee project
 
Immutable Infrastructure
Immutable InfrastructureImmutable Infrastructure
Immutable Infrastructure
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
 
Go 1.8 'new' networking features
Go 1.8 'new' networking featuresGo 1.8 'new' networking features
Go 1.8 'new' networking features
 

Recently uploaded

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Hivelance Technology
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILNatan Silnitsky
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of ProgrammingMatt Welsh
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptxGeorgi Kodinov
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024Ortus Solutions, Corp
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandIES VE
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 

cgo and Go plugins

  • 1. http://strikr.in/ CC BY NC-SA 4.0 unsafe, cgo and go plugins saifi@acm.org
  • 2. http://strikr.in/ CC BY NC-SA 4.0 In the world of 'go' ● Safety guarantees – Static checks ● Type checks ● Strict rules for type conversions – Dynamic checks ● Out-of-array bounds ● Nil pointer references
  • 3. http://strikr.in/ CC BY NC-SA 4.0 In the world of 'go' ... ● Implementation details are not accessible – Discover layout of struct – Pointer identifies a variable without revealing its address. – Identity of the OS thread on which the current stackless function (g*) is running – Go scheduler moves stackless function (g*) from one thread to another. – Address changes and pointer updates as garbage collector moves variables
  • 4. http://strikr.in/ CC BY NC-SA 4.0 Side stepping the safety ● unsafe ● Expose details of Go memory layout ● Looks like a regular package ● Import “unsafe” ● Actually implemented by the compiler os runtime syscall net unsafe
  • 5. http://strikr.in/ CC BY NC-SA 4.0 unsafe src/unsafe/unsafe.go type ArbitraryType int type Pointer *ArbitraryType func Sizeof (x ArbitraryType) uintptr func Offsetof (x ArbitraryType) uintptr func AlignOf (x ArbitraryType) uintptr go vet may help but can't depend on it.
  • 6. http://strikr.in/ CC BY NC-SA 4.0 unsafe pointer manipulation func get_address (f float64) uint64 { pT := unsafe.Pointer (&f) p := (*uint64)(pT) *p = 7.0 return *p } func main () { num := 1.0 fmt.Printf ("%f n", num) fmt.Printf ("%#016x n", get_address (num)) fmt.Printf ("%f n", num) }
  • 7. http://strikr.in/ CC BY NC-SA 4.0 Code organization 101 ● As functionality grows, functions are categorized together ● Unit of organization is then – Static library – Dynamic library ● Calling convention defined to support linkage considerations – Who cleans up the stack – What happens to name mangling
  • 8. http://strikr.in/ CC BY NC-SA 4.0 A C function calling a C function from a library char* say (const char *name); file_libname.c libname.so Code gen option -fPIC linker option -shared
  • 9. http://strikr.in/ CC BY NC-SA 4.0 A C function calling a C function from a library main () char* say (const char *name); file_caller.c file_libname.c LD_LIBRARY_PATH ld libname.so file_caller.c CPATH C_INCLUDE_PATH cc
  • 10. http://strikr.in/ CC BY NC-SA 4.0 Memory layout of C program
  • 11. http://strikr.in/ CC BY NC-SA 4.0 A C function calling a C function
  • 12. http://strikr.in/ CC BY NC-SA 4.0 Code organization 202 ● Binary generated code is arranged in ELF format ● Executable and Linkable Format ● Expressed in terms of sections – .text – .data – .rodata – .bss ● DWARF for debugging
  • 13. http://strikr.in/ CC BY NC-SA 4.0 ELF
  • 14. http://strikr.in/ CC BY NC-SA 4.0 Two views
  • 15. http://strikr.in/ CC BY NC-SA 4.0 Code organization 303 ● Dynamically loaded libraries – Loaded on demand – Used to implement plugins, modules – On Linux built as standard object modules ● Linkage – extern “C” – no name mangling
  • 16. http://strikr.in/ CC BY NC-SA 4.0 Code organization 303 ● Infrastructure to work with sections and symbols – #include <dlfcn.h> – /usr/include/dlfcn.h – Same as in Solaris ● API – dlopen() – dlsym() – dlerror() – dlclose()
  • 17. http://strikr.in/ CC BY NC-SA 4.0 Infrastructure to work with ELF
  • 18. http://strikr.in/ CC BY NC-SA 4.0 Shared object API ● void * dlopen(const char *filename, int flag); – Open the shared file and map it. ● void * dlsym(void *handle, char *symbol); – Find the run-time address in shared object ● char *dlerror (void); – Return a string describing the error. ● int dlclose (void *__handle); – Unmap and close a shared object
  • 19. http://strikr.in/ CC BY NC-SA 4.0 cgo ● Useful technology that allows Go to interoperate with C libraries ● Generates Thunks and Stubs to bind ● C to Go ● Go to C ● Challenges – Different stacks for Go and C – Garbage collector 'drama' ●
  • 20. http://strikr.in/ CC BY NC-SA 4.0 cgo ● package – https://golang.org/cmd/cgo/ ● Rules for passing pointers – https://github.com/golang/proposal/blob/master/de ●
  • 21. http://strikr.in/ CC BY NC-SA 4.0 char* say (const char *name); file_caller.c file_libname.c LD_LIBRARY_PATH ld libname.so file_caller.go CPATH C_INCLUDE_PATH cc import “C” Go code here cgo
  • 22. http://strikr.in/ CC BY NC-SA 4.0 cgo Pointer 'passing' restrictions ● Go code may pass a Go pointer to C provided the Go memory to which it points does not contain any Go pointers. ● C code must not store any Go pointers in Go memory, even temporarily. ● C code may not keep a copy of a Go pointer after the call returns. ● Go code may not store a Go pointer in C memory. ● Checked dynamically at runtime GODEBUG=cgocheck=2
  • 23. http://strikr.in/ CC BY NC-SA 4.0 go packages and 'cgo' crypto/x509 os/user go/internal cmd net runtime runtime/cgo runtime/race conf_netcgo.go cgo_stub.go cgo_resnew.go cgo_resold.go cgo_sockold.go cgo_socknew.go cgo_linux.go cgo_windows.go cgo_openbsd.go cgo_bsd.go cgo_netbsd.go cgo_solaris.go cgo_unix.go cgo_unix_test.go cgo_android.go src/net
  • 24. http://strikr.in/ CC BY NC-SA 4.0 cgo – what to know ● Unavoidable when working with binary blob – Graphics driver – Windowing system ● Slower build times – C compiler in focus, works on every C file across packages to create a single .o file – Linker works through .o file to resolve the shared objects referenced – Cross compiling not possible
  • 25. http://strikr.in/ CC BY NC-SA 4.0 cgo – what to know ● cgo is not go, both cc and go compiler needed ● Cross-compiling is disabled when cgo is operational ● Go tools don't work ● Performance issues due mis-matched 'call' stacks ● C decides not Go (addr, sig, tls) ● No longer single static binary ● What was the garbage collector upto ;P
  • 26. http://strikr.in/ CC BY NC-SA 4.0 cgo usage references ● 37: error : use of undeclared identifier http://www.mischiefblog.com/2014/06/24/a-go-cgo-go ● Using C libraries with Go https://jamesadam.me/2014/11/23/using-c-libraries-w ● cgo is not Go https://dave.cheney.net/2016/01/18/cgo-is-not-go
  • 27. http://strikr.in/ CC BY NC-SA 4.0 Gotcha's ● Why use unicode characters in function names in the Go source code https://groups.google.com/forum/#!msg/golang-nuts/ ● Slashes and dots in function names in prototypes https://stackoverflow.com/questions/13475908/slashe ● errno http://noeffclue.blogspot.in/2011/10/experimenting-wi ●
  • 28. http://strikr.in/ CC BY NC-SA 4.0 plugin ● A plugin is a Go main package with exported functions and variables that has been built with – go build -buildmode=plugin ● Isomorphic to dlfcn design ● Plugins work only on Linux ● import “plugin” ● A plugin is only initialized once, and cannot be closed. ● https://golang.org/pkg/plugin/
  • 29. http://strikr.in/ CC BY NC-SA 4.0 plugins ● Export symbol – using “//export” ● Leverage -buildmode argument – go build -buildmode= archive c-archive c-shared default shared exe pie plugin
  • 30. http://strikr.in/ CC BY NC-SA 4.0 plugin plugin.go plugin_dlopen.go plugin_stubs.go type Plugin struct { pluginpath string loaded chan struct{} // closed when loaded syms map[string]interface{} } func Open(path string) (*Plugin, error) { return open(path) } func (p *Plugin) Lookup(symName string) (Symbol, error) { return lookup(p, symName) } type Symbol interface{}
  • 31. http://strikr.in/ CC BY NC-SA 4.0 plugin_dlopen.go import “C” static uintptr_t pluginOpen(const char* path, char** err); static void* pluginLookup(uintptr_t h, const char* name, char** err); func pathToPrefix(s string) string func open(name string) (*Plugin, error) func lookup(p *Plugin, symName string) (Symbol, error) func lastmoduleinit() (pluginpath string, syms map[string]interface{}, mismatchpkg string) C part Go part
  • 32. http://strikr.in/ CC BY NC-SA 4.0 plugin patterns os.exec.Command() pluginmain RPC stdOUT stdIN stdIN stdOUT os.exec.Command() pluginmain RPC net.Conn External process using RPC via std IN/OUT External process using RPC via network main plugin plugin nanomsg “scalability protocols” Pair PubSub Bus Survey Pipeline ReqRep
  • 33. http://strikr.in/ CC BY NC-SA 4.0 Code references ● A toolkit for creating plugins for Go applications https://github.com/natefinch/pie ● nanomsg socket library for several communication patterns http://nanomsg.org/ ● scalable protocol implementations in Go https://github.com/go-mangos/mangos ● Hashicorp go plugin system https://github.com/hashicorp/go-plugin
  • 34. http://strikr.in/ CC BY NC-SA 4.0 References ● Go plugins are easy as a pie https://npf.io/2015/05/pie/ ● Go lang plugin system over RPC https://github.com/hashicorp/go-plugin ● Plugin in Go https://appliedgo.net/plugins/
  • 35. http://strikr.in/ CC BY NC-SA 4.0 Thank You
  • 36. http://strikr.in/ CC BY NC-SA 4.0 Thank You