SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Dealing with Merge Conflicts in Git
Dealing with Merge Conflicts in GitDealing with Merge Conflicts in Git
Dealing with Merge Conflicts in Gitgittower
 
実践 Git - 低レベルに知る Git
実践 Git - 低レベルに知る Git実践 Git - 低レベルに知る Git
実践 Git - 低レベルに知る GitYouhei Nitta
 
Git 기본개념과 사용법 그리고 어플리케이션
Git 기본개념과 사용법 그리고 어플리케이션Git 기본개념과 사용법 그리고 어플리케이션
Git 기본개념과 사용법 그리고 어플리케이션Dabi Ahn
 
Git with bitbucket
Git with bitbucketGit with bitbucket
Git with bitbucketSumin Byeon
 
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べた
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べたiOS/macOSとAndroid/Linuxのサンドボックス機構について調べた
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べたYoshio Hanawa
 
PHP 8 で Web 以外の世界の扉を叩く
PHP 8 で Web 以外の世界の扉を叩くPHP 8 で Web 以外の世界の扉を叩く
PHP 8 で Web 以外の世界の扉を叩くshinjiigarashi
 
PHPとシグナル、その裏側
PHPとシグナル、その裏側PHPとシグナル、その裏側
PHPとシグナル、その裏側do_aki
 
Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화Juwon Kim
 
Windows subsystem for linuxで始める組み込みlinux ラズパイ3のブートイメージを作ってみる-
Windows subsystem for linuxで始める組み込みlinux  ラズパイ3のブートイメージを作ってみる-Windows subsystem for linuxで始める組み込みlinux  ラズパイ3のブートイメージを作ってみる-
Windows subsystem for linuxで始める組み込みlinux ラズパイ3のブートイメージを作ってみる-Toyohiko Komatsu
 
Nginx Unitを試してみた話
Nginx Unitを試してみた話Nginx Unitを試してみた話
Nginx Unitを試してみた話Takehiro Torigaki
 
하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조Logpresso
 
「Tsurugi Linux」プレゼンテーションAVTOKYO2018
「Tsurugi Linux」プレゼンテーションAVTOKYO2018「Tsurugi Linux」プレゼンテーションAVTOKYO2018
「Tsurugi Linux」プレゼンテーションAVTOKYO2018unixfreaxjp
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Pythonkwatch
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGoTakuya Ueda
 
Git basics to advance with diagrams
Git basics to advance with diagramsGit basics to advance with diagrams
Git basics to advance with diagramsDilum Navanjana
 

Tendances (20)

Git tutorial
Git tutorialGit tutorial
Git tutorial
 
Dealing with Merge Conflicts in Git
Dealing with Merge Conflicts in GitDealing with Merge Conflicts in Git
Dealing with Merge Conflicts in Git
 
GIT AND GITHUB (1).pptx
GIT AND GITHUB (1).pptxGIT AND GITHUB (1).pptx
GIT AND GITHUB (1).pptx
 
実践 Git - 低レベルに知る Git
実践 Git - 低レベルに知る Git実践 Git - 低レベルに知る Git
実践 Git - 低レベルに知る Git
 
Git 기본개념과 사용법 그리고 어플리케이션
Git 기본개념과 사용법 그리고 어플리케이션Git 기본개념과 사용법 그리고 어플리케이션
Git 기본개념과 사용법 그리고 어플리케이션
 
Git with bitbucket
Git with bitbucketGit with bitbucket
Git with bitbucket
 
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べた
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べたiOS/macOSとAndroid/Linuxのサンドボックス機構について調べた
iOS/macOSとAndroid/Linuxのサンドボックス機構について調べた
 
PHP 8 で Web 以外の世界の扉を叩く
PHP 8 で Web 以外の世界の扉を叩くPHP 8 で Web 以外の世界の扉を叩く
PHP 8 で Web 以外の世界の扉を叩く
 
Git
GitGit
Git
 
PHPとシグナル、その裏側
PHPとシグナル、その裏側PHPとシグナル、その裏側
PHPとシグナル、その裏側
 
Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화Envoy 를 이용한 코드 배포 자동화
Envoy 를 이용한 코드 배포 자동화
 
Windows subsystem for linuxで始める組み込みlinux ラズパイ3のブートイメージを作ってみる-
Windows subsystem for linuxで始める組み込みlinux  ラズパイ3のブートイメージを作ってみる-Windows subsystem for linuxで始める組み込みlinux  ラズパイ3のブートイメージを作ってみる-
Windows subsystem for linuxで始める組み込みlinux ラズパイ3のブートイメージを作ってみる-
 
Nginx Unitを試してみた話
Nginx Unitを試してみた話Nginx Unitを試してみた話
Nginx Unitを試してみた話
 
하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조
 
「Tsurugi Linux」プレゼンテーションAVTOKYO2018
「Tsurugi Linux」プレゼンテーションAVTOKYO2018「Tsurugi Linux」プレゼンテーションAVTOKYO2018
「Tsurugi Linux」プレゼンテーションAVTOKYO2018
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
Git training v10
Git training v10Git training v10
Git training v10
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGo
 
Go入門
Go入門Go入門
Go入門
 
Git basics to advance with diagrams
Git basics to advance with diagramsGit basics to advance with diagrams
Git basics to advance with diagrams
 

Similaire à 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
 

Similaire à 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
 

Plus de 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 .
 

Plus de 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
 

Dernier

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Dernier (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
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-...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
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...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

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