SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeperSaurav Haloi
 
Advanced Git Tutorial
Advanced Git TutorialAdvanced Git Tutorial
Advanced Git TutorialSage Sharp
 
Boost.Graph入門
Boost.Graph入門Boost.Graph入門
Boost.Graph入門egtra
 
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》鍾誠 陳鍾誠
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction SelectionShiva Chen
 
Understanding GIT and Version Control
Understanding GIT and Version ControlUnderstanding GIT and Version Control
Understanding GIT and Version ControlSourabh Sahu
 
Git and GitHub | Concept about Git and GitHub Process | Git Process overview
Git and GitHub | Concept about Git and GitHub Process | Git Process overviewGit and GitHub | Concept about Git and GitHub Process | Git Process overview
Git and GitHub | Concept about Git and GitHub Process | Git Process overviewRueful Robin
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git FlowNick Pruehs
 
Distributed Transactions are dead, long live distributed transaction!
Distributed Transactions are dead, long live distributed transaction!Distributed Transactions are dead, long live distributed transaction!
Distributed Transactions are dead, long live distributed transaction!J On The Beach
 
寫給大家的 Git 教學
寫給大家的 Git 教學寫給大家的 Git 教學
寫給大家的 Git 教學littlebtc
 
Gitflow vs. Trunk based development
Gitflow vs. Trunk based development Gitflow vs. Trunk based development
Gitflow vs. Trunk based development István Marhefka
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLangNVISIA
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewMarkus Schneider
 

Was ist angesagt? (20)

Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Advanced Git Tutorial
Advanced Git TutorialAdvanced Git Tutorial
Advanced Git Tutorial
 
C言語よくある誤り
C言語よくある誤りC言語よくある誤り
C言語よくある誤り
 
Boost.Graph入門
Boost.Graph入門Boost.Graph入門
Boost.Graph入門
 
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》
用30分鐘深入瞭解《AlphaGo圍棋程式的設計原理》
 
Les bases de git
Les bases de gitLes bases de git
Les bases de git
 
LLVM Instruction Selection
LLVM Instruction SelectionLLVM Instruction Selection
LLVM Instruction Selection
 
Understanding GIT and Version Control
Understanding GIT and Version ControlUnderstanding GIT and Version Control
Understanding GIT and Version Control
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
Git and GitHub | Concept about Git and GitHub Process | Git Process overview
Git and GitHub | Concept about Git and GitHub Process | Git Process overviewGit and GitHub | Concept about Git and GitHub Process | Git Process overview
Git and GitHub | Concept about Git and GitHub Process | Git Process overview
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git Flow
 
Distributed Transactions are dead, long live distributed transaction!
Distributed Transactions are dead, long live distributed transaction!Distributed Transactions are dead, long live distributed transaction!
Distributed Transactions are dead, long live distributed transaction!
 
寫給大家的 Git 教學
寫給大家的 Git 教學寫給大家的 Git 教學
寫給大家的 Git 教學
 
Gitflow vs. Trunk based development
Gitflow vs. Trunk based development Gitflow vs. Trunk based development
Gitflow vs. Trunk based development
 
Git basics
Git basicsGit basics
Git basics
 
Three Optimization Tips for C++
Three Optimization Tips for C++Three Optimization Tips for C++
Three Optimization Tips for C++
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLang
 
Virtual Machine Constructions for Dummies
Virtual Machine Constructions for DummiesVirtual Machine Constructions for Dummies
Virtual Machine Constructions for Dummies
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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 .
 

Mehr von 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
 

Kürzlich hochgeladen

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Kürzlich hochgeladen (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

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