How to call private functions in Golang (bound hidden identifiers)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. * April 28, 2016 * The importance of names in Golang is the same as in any other language. They even have a semantic effect: the visibility of a name outside a package is determined by whether the first letter of the name is capitalized. Sometimes you need to overcome this limitation in order to better organize your code or use some hidden functions in other packages. In the good old days, there are 2 implementations that can bypass the compiler's check: cannot reference the name of the Pkg.symbol:-The old way, now no longer used-the assembly level is implicitly connected to the desired symbol, called assembly stubs, see [Go Runtime, O S/signal:use//go:linkname instead of assembly stubs to get access to runtime functions] (https://groups.google.com/forum/ #!topic/golang-codereviews/j0hk9glc76m). -The current way-go compiler supports name redirection via Go:linkname, referring to 11.11.14 [dev.cc code review 169360043:cmd/gc:changes for removing runtime C Code (issue 169360043 by R. @golang. org)] (Https://groups.google.com/forum/#!topic/golang-codereviews/5Ps_El_RpNE), Github.com's issue can be found on the [cmd/compile: "Missing function Body" error when using the//go:linkname compiler directive #15 006] (https://github.com/golang/go/issues/15006). Using these techniques I have managed to bind Golang Runtime Scheduler-related functions to reduce GC pauses caused by overuse of go and internal locking mechanisms. # # # using assembly stubs idea is simple-provide a direct jump assembly instruction stubs for the required identifiers. The linker does not know if an identifier has been exported. See the previous version of Code Src/os/sigNAL/SIG.S: ' Go//Assembly to get into package runtime without using exported symbols.//+build AMD64 AMD64P32 arm arm64 386 PPC64 ppc64le#include "textflag.h" #ifdef goarch_arm#define jmp b#endif#ifdef goarch_ppc64#define jmp br#endif#ifdef Goarch_ppc64le#define JMP br#endiftext signal_disable (SB), NOSPLIT,$0JMP runtime signal_disable (SB) Text·signal_ Enable (SB), NOSPLIT,$0JMP runtime signal_enable (SB) text Signal_ignore (SB), NOSPLIT,$0JMP runtime Signal_ignore (SB) Text Signal_recv (SB), NOSPLIT,$0JMP runtime Signal_recv (SB) ' and Signal_unix.go's bindings are as follows: ' ' go//+build Darwin Dragonfly FreeBSD linux NaCl NetBSD OpenBSD solaris windowspackage signalimport ("OS" "Syscall")//In Assembly.func signal_disable (u Int32) Func signal_enable (UInt32) func Signal_ignore (UInt32) func signal_recv () UInt32 "# # # Use Go:linkname in order to use this method, The code must be ' import _ ' unsafe ' package. In order to solve the limitations of the Go compiler '-complete ' parameter, one possible way is to disable compiler checking by adding an empty assembly stub file to the main package directory. See OS/SIGNAL/SIG.S: "go//the runtime package uses//go:linkname to push a fewFunctions into this//package but we still need a. s file so the Go tool does does pass-complete//to the Go tool compile The latter does not complain on Go functions//with no bodies. "The format of this instruction is '//go:linkname localname linkname '. You can use this method to link (export) a new identifier or bind to an existing identifier (import). # # # using Go:linkname to derive the implementation of a function in Runtime/proc.go "' Go...//go:linkname sync_runtime_dospin sync.runtime_dospin//go: Nosplitfunc Sync_runtime_dospin () {Procyield (active_spin_cnt)} "is explicitly instructed by the compiler to add another name to the Runtime_dospin function code of the sync package. and the Sync pack simply reuses the code in Sync/runtime.go: "Gopackage syncimport" unsafe "...//Runtime_dospin does active Spinning.func runt Ime_dospin () "# # # with Go:linkname import in Net/parse.go has a good example:" ' Gopackage netimport (... _ "unsafe"//For Go:linkname) .../ /Byteindex is strings. Indexbyte. It returns the index of the//first instance of C in S, or-1 if C was not present in s.//strings. Indexbyte is implemented in Runtime/asm_$goarch.s//go:linkname byteindex strings. Indexbytefunc Byteindex (s string, C byte) inHow to use this technique: 1. Import _ "unsafe" package. 2. Provide a function without a function body, for example: Func byteindex (S string, C byte) Int3. Before defining a function, put the//GO:LINKNAME directive correctly, such as//go:linkname byteindex strings. Indexbyte,byteindex is the local name, strings. Indexbyte is the remote name. 4. Provide the stub file for the. s suffix so that the compiler bypasses the-complete check, allowing incomplete function definitions (meaning no function body). # # # example Goparkunlock ' Gopackage mainimport (_ "unsafe" "FMT" "Runtime/pprof" "OS" "Time")//Event types in the trace, args is Given in square brackets.const (Traceevgoblock =/goroutine blocks [timestamp, stack]) type mutex struct {//Futex-ba Sed Impl treats it as UInt32 key,//while sema-based impl as m* waitm.//used to BES a union, but unions break precise GC.K EY uintptr}//go:linkname Lock Runtime.lockfunc Lock (l *mutex)//go:linkname unlock runtime.unlockfunc unlock (l *mutex)// Go:linkname goparkunlock runtime.goparkunlockfunc Goparkunlock (lock *mutex, reason string, Traceev byte, Traceskip int) Func main () {l: = &mutex{}go func () {lock (L) Goparkunlock (l, "xxx", Traceevgoblock, 1)} () for {pprof. Lookup ("Goroutine"). WriteTo (OS. Stdout, 1) time. Sleep (time. Second * 1}} "# # # # source can be obtained here [Https://github.com/sitano/gsysint] (https://github.com/sitano/gsysint). # # # Related articles-[Docker Windows Install instructions on the state of 4 August] (https://sitano.github.io/2016/08 /04/docker-win/)-[PowerShell Ducklish typed] (https://sitano.github.io/2016/04/25/powershell-ducklish/)- [approach into strong typed configuration management DSL with FAKE, F #, WinRM and PowerShell 2016] (https://sitano.github.io/2016/03/15/powershell-winrm-fake/)

via:https://sitano.github.io/2016/04/28/golang-private/

Author: Johnkoepi Translator: Kekemuyu proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

750 reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.