Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
doc.go1112 linesDownload Raw Back to cgo
1// Copyright 2009 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5/*6Cgo enables the creation of Go packages that call C code.7 8# Using cgo with the go command9 10To use cgo write normal Go code that imports a pseudo-package "C".11The Go code can then refer to types such as C.size_t, variables such12as C.stdout, or functions such as C.putchar.13 14If the import of "C" is immediately preceded by a comment, that15comment, called the preamble, is used as a header when compiling16the C parts of the package. For example:17 18	// #include <stdio.h>19	// #include <errno.h>20	import "C"21 22The preamble may contain any C code, including function and variable23declarations and definitions. These may then be referred to from Go24code as though they were defined in the package "C". All names25declared in the preamble may be used, even if they start with a26lower-case letter. Exception: static variables in the preamble may27not be referenced from Go code; static functions are permitted.28 29See $GOROOT/cmd/cgo/internal/teststdio and $GOROOT/misc/cgo/gmp for examples. See30"C? Go? Cgo!" for an introduction to using cgo:31https://golang.org/doc/articles/c_go_cgo.html.32 33CFLAGS, CPPFLAGS, CXXFLAGS, FFLAGS and LDFLAGS may be defined with pseudo34#cgo directives within these comments to tweak the behavior of the C, C++35or Fortran compiler. Values defined in multiple directives are concatenated36together. The directive can include a list of build constraints limiting its37effect to systems satisfying one of the constraints38(see https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax).39For example:40 41	// #cgo CFLAGS: -DPNG_DEBUG=142	// #cgo amd64 386 CFLAGS: -DX86=143	// #cgo LDFLAGS: -lpng44	// #include <png.h>45	import "C"46 47Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config tool48using a '#cgo pkg-config:' directive followed by the package names.49For example:50 51	// #cgo pkg-config: png cairo52	// #include <png.h>53	import "C"54 55The default pkg-config tool may be changed by setting the PKG_CONFIG environment variable.56 57For security reasons, only a limited set of flags are allowed, notably -D, -U, -I, and -l.58To allow additional flags, set CGO_CFLAGS_ALLOW to a regular expression59matching the new flags. To disallow flags that would otherwise be allowed,60set CGO_CFLAGS_DISALLOW to a regular expression matching arguments61that must be disallowed. In both cases the regular expression must match62a full argument: to allow -mfoo=bar, use CGO_CFLAGS_ALLOW='-mfoo.*',63not just CGO_CFLAGS_ALLOW='-mfoo'. Similarly named variables control64the allowed CPPFLAGS, CXXFLAGS, FFLAGS, and LDFLAGS.65 66Also for security reasons, only a limited set of characters are67permitted, notably alphanumeric characters and a few symbols, such as68'.', that will not be interpreted in unexpected ways. Attempts to use69forbidden characters will get a "malformed #cgo argument" error.70 71When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS, CGO_FFLAGS and72CGO_LDFLAGS environment variables are added to the flags derived from73these directives. Package-specific flags should be set using the74directives, not the environment variables, so that builds work in75unmodified environments. Flags obtained from environment variables76are not subject to the security limitations described above.77 78All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and79used to compile C files in that package. All the CPPFLAGS and CXXFLAGS80directives in a package are concatenated and used to compile C++ files in that81package. All the CPPFLAGS and FFLAGS directives in a package are concatenated82and used to compile Fortran files in that package. All the LDFLAGS directives83in any package in the program are concatenated and used at link time. All the84pkg-config directives are concatenated and sent to pkg-config simultaneously85to add to each appropriate set of command-line flags.86 87When the cgo directives are parsed, any occurrence of the string ${SRCDIR}88will be replaced by the absolute path to the directory containing the source89file. This allows pre-compiled static libraries to be included in the package90directory and linked properly.91For example if package foo is in the directory /go/src/foo:92 93	// #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo94 95Will be expanded to:96 97	// #cgo LDFLAGS: -L/go/src/foo/libs -lfoo98 99When the Go tool sees that one or more Go files use the special import100"C", it will look for other non-Go files in the directory and compile101them as part of the Go package. Any .c, .s, .S or .sx files will be102compiled with the C compiler. Any .cc, .cpp, or .cxx files will be103compiled with the C++ compiler. Any .f, .F, .for or .f90 files will be104compiled with the fortran compiler. Any .h, .hh, .hpp, or .hxx files will105not be compiled separately, but, if these header files are changed,106the package (including its non-Go source files) will be recompiled.107Note that changes to files in other directories do not cause the package108to be recompiled, so all non-Go source code for the package should be109stored in the package directory, not in subdirectories.110The default C and C++ compilers may be changed by the CC and CXX111environment variables, respectively; those environment variables112may include command line options.113 114The cgo tool will always invoke the C compiler with the source file's115directory in the include path; i.e. -I${SRCDIR} is always implied. This116means that if a header file foo/bar.h exists both in the source117directory and also in the system include directory (or some other place118specified by a -I flag), then "#include <foo/bar.h>" will always find the119local version in preference to any other version.120 121The cgo tool is enabled by default for native builds on systems where122it is expected to work. It is disabled by default when cross-compiling123as well as when the CC environment variable is unset and the default124C compiler (typically gcc or clang) cannot be found on the system PATH.125You can override the default by setting the CGO_ENABLED126environment variable when running the go tool: set it to 1 to enable127the use of cgo, and to 0 to disable it. The go tool will set the128build constraint "cgo" if cgo is enabled. The special import "C"129implies the "cgo" build constraint, as though the file also said130"//go:build cgo". Therefore, if cgo is disabled, files that import131"C" will not be built by the go tool. (For more about build constraints132see https://golang.org/pkg/go/build/#hdr-Build_Constraints).133 134When cross-compiling, you must specify a C cross-compiler for cgo to135use. You can do this by setting the generic CC_FOR_TARGET or the136more specific CC_FOR_${GOOS}_${GOARCH} (for example, CC_FOR_linux_arm)137environment variable when building the toolchain using make.bash,138or you can set the CC environment variable any time you run the go tool.139 140The CXX_FOR_TARGET, CXX_FOR_${GOOS}_${GOARCH}, and CXX141environment variables work in a similar way for C++ code.142 143# Go references to C144 145Within the Go file, C's struct field names that are keywords in Go146can be accessed by prefixing them with an underscore: if x points at a C147struct with a field named "type", x._type accesses the field.148C struct fields that cannot be expressed in Go, such as bit fields149or misaligned data, are omitted in the Go struct, replaced by150appropriate padding to reach the next field or the end of the struct.151 152The standard C numeric types are available under the names153C.char, C.schar (signed char), C.uchar (unsigned char),154C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int),155C.long, C.ulong (unsigned long), C.longlong (long long),156C.ulonglong (unsigned long long), C.float, C.double,157C.complexfloat (complex float), and C.complexdouble (complex double).158The C type void* is represented by Go's unsafe.Pointer.159The C types __int128_t and __uint128_t are represented by [16]byte.160 161A few special C types which would normally be represented by a pointer162type in Go are instead represented by a uintptr.  See the Special163cases section below.164 165To access a struct, union, or enum type directly, prefix it with166struct_, union_, or enum_, as in C.struct_stat. The size of any C type167T is available as C.sizeof_T, as in C.sizeof_struct_stat. These168special prefixes means that there is no way to directly reference a C169identifier that starts with "struct_", "union_", "enum_", or170"sizeof_", such as a function named "struct_function".171A workaround is to use a "#define" in the preamble, as in172"#define c_struct_function struct_function" and then in the173Go code refer to "C.c_struct_function".174 175A C function may be declared in the Go file with a parameter type of176the special name _GoString_. This function may be called with an177ordinary Go string value. The string length, and a pointer to the178string contents, may be accessed by calling the C functions179 180	size_t _GoStringLen(_GoString_ s);181	const char *_GoStringPtr(_GoString_ s);182 183These functions are only available in the preamble, not in other C184files. The C code must not modify the contents of the pointer returned185by _GoStringPtr. Note that the string contents may not have a trailing186NUL byte.187 188As Go doesn't have support for C's union type in the general case,189C's union types are represented as a Go byte array with the same length.190 191Go structs cannot embed fields with C types.192 193Go code cannot refer to zero-sized fields that occur at the end of194non-empty C structs. To get the address of such a field (which is the195only operation you can do with a zero-sized field) you must take the196address of the struct and add the size of the struct.197 198Cgo translates C types into equivalent unexported Go types.199Because the translations are unexported, a Go package should not200expose C types in its exported API: a C type used in one Go package201is different from the same C type used in another.202 203Any C function (even void functions) may be called in a multiple204assignment context to retrieve both the return value (if any) and the205C errno variable as an error (use _ to skip the result value if the206function returns void). For example:207 208	n, err = C.sqrt(-1)209	_, err := C.voidFunc()210	var n, err = C.sqrt(1)211 212Note that the C errno value may be non-zero, and thus the err result may be213non-nil, even if the function call is successful. Unlike normal Go conventions,214you should first check whether the call succeeded before checking the error215result. For example:216 217	n, err := C.setenv(key, value, 1)218	if n != 0 {219		// we know the call failed, so it is now valid to use err220		return err221	}222 223Calling C function pointers is currently not supported, however you can224declare Go variables which hold C function pointers and pass them225back and forth between Go and C. C code may call function pointers226received from Go. For example:227 228	package main229 230	// typedef int (*intFunc) ();231	//232	// int233	// bridge_int_func(intFunc f)234	// {235	//		return f();236	// }237	//238	// int fortytwo()239	// {240	//	    return 42;241	// }242	import "C"243	import "fmt"244 245	func main() {246		f := C.intFunc(C.fortytwo)247		fmt.Println(int(C.bridge_int_func(f)))248		// Output: 42249	}250 251In C, a function argument written as a fixed size array252actually requires a pointer to the first element of the array.253C compilers are aware of this calling convention and adjust254the call accordingly, but Go cannot. In Go, you must pass255the pointer to the first element explicitly: C.f(&C.x[0]).256 257Calling variadic C functions is not supported. It is possible to258circumvent this by using a C function wrapper. For example:259 260	package main261 262	// #include <stdio.h>263	// #include <stdlib.h>264	//265	// static void myprint(char* s) {266	//   printf("%s\n", s);267	// }268	import "C"269	import "unsafe"270 271	func main() {272		cs := C.CString("Hello from stdio")273		C.myprint(cs)274		C.free(unsafe.Pointer(cs))275	}276 277A few special functions convert between Go and C types278by making copies of the data. In pseudo-Go definitions:279 280	// Go string to C string281	// The C string is allocated in the C heap using malloc.282	// It is the caller's responsibility to arrange for it to be283	// freed, such as by calling C.free (be sure to include stdlib.h284	// if C.free is needed).285	func C.CString(string) *C.char286 287	// Go []byte slice to C array288	// The C array is allocated in the C heap using malloc.289	// It is the caller's responsibility to arrange for it to be290	// freed, such as by calling C.free (be sure to include stdlib.h291	// if C.free is needed).292	func C.CBytes([]byte) unsafe.Pointer293 294	// C string to Go string295	func C.GoString(*C.char) string296 297	// C data with explicit length to Go string298	func C.GoStringN(*C.char, C.int) string299 300	// C data with explicit length to Go []byte301	func C.GoBytes(unsafe.Pointer, C.int) []byte302 303As a special case, C.malloc does not call the C library malloc directly304but instead calls a Go helper function that wraps the C library malloc305but guarantees never to return nil. If C's malloc indicates out of memory,306the helper function crashes the program, like when Go itself runs out307of memory. Because C.malloc cannot fail, it has no two-result form308that returns errno.309 310# C references to Go311 312Go functions can be exported for use by C code in the following way:313 314	//export MyFunction315	func MyFunction(arg1, arg2 int, arg3 string) int64 {...}316 317	//export MyFunction2318	func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}319 320They will be available in the C code as:321 322	extern GoInt64 MyFunction(int arg1, int arg2, GoString arg3);323	extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);324 325found in the _cgo_export.h generated header, after any preambles326copied from the cgo input files. Functions with multiple327return values are mapped to functions returning a struct.328 329Not all Go types can be mapped to C types in a useful way.330Go struct types are not supported; use a C struct type.331Go array types are not supported; use a C pointer.332 333Go functions that take arguments of type string may be called with the334C type _GoString_, described above. The _GoString_ type will be335automatically defined in the preamble. Note that there is no way for C336code to create a value of this type; this is only useful for passing337string values from Go to C and back to Go.338 339Using //export in a file places a restriction on the preamble:340since it is copied into two different C output files, it must not341contain any definitions, only declarations. If a file contains both342definitions and declarations, then the two output files will produce343duplicate symbols and the linker will fail. To avoid this, definitions344must be placed in preambles in other files, or in C source files.345 346# Passing pointers347 348Go is a garbage collected language, and the garbage collector needs to349know the location of every pointer to Go memory. Because of this,350there are restrictions on passing pointers between Go and C.351 352In this section the term Go pointer means a pointer to memory353allocated by Go (such as by using the & operator or calling the354predefined new function) and the term C pointer means a pointer to355memory allocated by C (such as by a call to C.malloc). Whether a356pointer is a Go pointer or a C pointer is a dynamic property357determined by how the memory was allocated; it has nothing to do with358the type of the pointer.359 360Note that values of some Go types, other than the type's zero value,361always include Go pointers. This is true of interface, channel, map,362and function types. A pointer type may hold a Go pointer or a C pointer.363Array, slice, string, and struct types may or may not include Go pointers,364depending on their type and how they are constructed. All the discussion365below about Go pointers applies not just to pointer types,366but also to other types that include Go pointers.367 368All Go pointers passed to C must point to pinned Go memory. Go pointers369passed as function arguments to C functions have the memory they point to370implicitly pinned for the duration of the call. Go memory reachable from371these function arguments must be pinned as long as the C code has access372to it. Whether Go memory is pinned is a dynamic property of that memory373region; it has nothing to do with the type of the pointer.374 375Go values created by calling new, by taking the address of a composite376literal, or by taking the address of a local variable may also have their377memory pinned using [runtime.Pinner]. This type may be used to manage378the duration of the memory's pinned status, potentially beyond the379duration of a C function call. Memory may be pinned more than once and380must be unpinned exactly the same number of times it has been pinned.381 382Go code may pass a Go pointer to C provided the memory to which it383points does not contain any Go pointers to memory that is unpinned. When384passing a pointer to a field in a struct, the Go memory in question is385the memory occupied by the field, not the entire struct. When passing a386pointer to an element in an array or slice, the Go memory in question is387the entire array or the entire backing array of the slice.388 389C code may keep a copy of a Go pointer only as long as the memory it390points to is pinned.391 392C code may not keep a copy of a Go pointer after the call returns,393unless the memory it points to is pinned with [runtime.Pinner] and the394Pinner is not unpinned while the Go pointer is stored in C memory.395This implies that C code may not keep a copy of a string, slice,396channel, and so forth, because they cannot be pinned with397[runtime.Pinner].398 399The _GoString_ type also may not be pinned with [runtime.Pinner].400Because it includes a Go pointer, the memory it points to is only pinned401for the duration of the call; _GoString_ values may not be retained by C402code.403 404A Go function called by C code may return a Go pointer to pinned memory405(which implies that it may not return a string, slice, channel, and so406forth). A Go function called by C code may take C pointers as arguments,407and it may store non-pointer data, C pointers, or Go pointers to pinned408memory through those pointers. It may not store a Go pointer to unpinned409memory in memory pointed to by a C pointer (which again, implies that it410may not store a string, slice, channel, and so forth). A Go function411called by C code may take a Go pointer but it must preserve the property412that the Go memory to which it points (and the Go memory to which that413memory points, and so on) is pinned.414 415These rules are checked dynamically at runtime. The checking is416controlled by the cgocheck setting of the GODEBUG environment417variable. The default setting is GODEBUG=cgocheck=1, which implements418reasonably cheap dynamic checks. These checks may be disabled419entirely using GODEBUG=cgocheck=0. Complete checking of pointer420handling, at some cost in run time, is available by setting421GOEXPERIMENT=cgocheck2 at build time.422 423It is possible to defeat this enforcement by using the unsafe package,424and of course there is nothing stopping the C code from doing anything425it likes. However, programs that break these rules are likely to fail426in unexpected and unpredictable ways.427 428The type [runtime/cgo.Handle] can be used to safely pass Go values429between Go and C.430 431Note: the current implementation has a bug. While Go code is permitted432to write nil or a C pointer (but not a Go pointer) to C memory, the433current implementation may sometimes cause a runtime error if the434contents of the C memory appear to be a Go pointer. Therefore, avoid435passing uninitialized C memory to Go code if the Go code is going to436store pointer values in it. Zero out the memory in C before passing it437to Go.438 439# Optimizing calls of C code440 441When passing a Go pointer to a C function the compiler normally ensures442that the Go object lives on the heap. If the C function does not keep443a copy of the Go pointer, and never passes the Go pointer back to Go code,444then this is unnecessary. The #cgo noescape directive may be used to tell445the compiler that no Go pointers escape via the named C function.446If the noescape directive is used and the C function does not handle the447pointer safely, the program may crash or see memory corruption.448 449For example:450 451	// #cgo noescape cFunctionName452 453When a Go function calls a C function, it prepares for the C function to454call back to a Go function. The #cgo nocallback directive may be used to455tell the compiler that these preparations are not necessary.456If the nocallback directive is used and the C function does call back into457Go code, the program will panic.458 459For example:460 461	// #cgo nocallback cFunctionName462 463# Special cases464 465A few special C types which would normally be represented by a pointer466type in Go are instead represented by a uintptr. Those include:467 4681. The *Ref types on Darwin, rooted at CoreFoundation's CFTypeRef type.469 4702. The object types from Java's JNI interface:471 472	jobject473	jclass474	jthrowable475	jstring476	jarray477	jbooleanArray478	jbyteArray479	jcharArray480	jshortArray481	jintArray482	jlongArray483	jfloatArray484	jdoubleArray485	jobjectArray486	jweak487 4883. The EGLDisplay and EGLConfig types from the EGL API.489 490These types are uintptr on the Go side because they would otherwise491confuse the Go garbage collector; they are sometimes not really492pointers but data structures encoded in a pointer type. All operations493on these types must happen in C. The proper constant to initialize an494empty such reference is 0, not nil.495 496These special cases were introduced in Go 1.10. For auto-updating code497from Go 1.9 and earlier, use the cftype or jni rewrites in the Go fix tool:498 499	go tool fix -r cftype <pkg>500	go tool fix -r jni <pkg>501 502It will replace nil with 0 in the appropriate places.503 504The EGLDisplay case was introduced in Go 1.12. Use the egl rewrite505to auto-update code from Go 1.11 and earlier:506 507	go tool fix -r egl <pkg>508 509The EGLConfig case was introduced in Go 1.15. Use the eglconf rewrite510to auto-update code from Go 1.14 and earlier:511 512	go tool fix -r eglconf <pkg>513 514# Using cgo directly515 516Usage:517 518	go tool cgo [cgo options] [-- compiler options] gofiles...519 520Cgo transforms the specified input Go source files into several output521Go and C source files.522 523The compiler options are passed through uninterpreted when524invoking the C compiler to compile the C parts of the package.525 526The following options are available when running cgo directly:527 528	-V529		Print cgo version and exit.530	-debug-define531		Debugging option. Print #defines.532	-debug-gcc533		Debugging option. Trace C compiler execution and output.534	-dynimport file535		Write list of symbols imported by file. Write to536		-dynout argument or to standard output. Used by go537		build when building a cgo package.538	-dynlinker539		Write dynamic linker as part of -dynimport output.540	-dynout file541		Write -dynimport output to file.542	-dynpackage package543		Set Go package for -dynimport output.544	-exportheader file545		If there are any exported functions, write the546		generated export declarations to file.547		C code can #include this to see the declarations.548	-gccgo549		Generate output for the gccgo compiler rather than the550		gc compiler.551	-gccgoprefix prefix552		The -fgo-prefix option to be used with gccgo.553	-gccgopkgpath path554		The -fgo-pkgpath option to be used with gccgo.555	-gccgo_define_cgoincomplete556		Define cgo.Incomplete locally rather than importing it from557		the "runtime/cgo" package. Used for old gccgo versions.558	-godefs559		Write out input file in Go syntax replacing C package560		names with real values. Used to generate files in the561		syscall package when bootstrapping a new target.562	-importpath string563		The import path for the Go package. Optional; used for564		nicer comments in the generated files.565	-import_runtime_cgo566		If set (which it is by default) import runtime/cgo in567		generated output.568	-import_syscall569		If set (which it is by default) import syscall in570		generated output.571	-ldflags flags572		Flags to pass to the C linker. The cmd/go tool uses573		this to pass in the flags in the CGO_LDFLAGS variable.574	-objdir directory575		Put all generated files in directory.576	-srcdir directory577		Find the Go input files, listed on the command line,578		in directory.579	-trimpath rewrites580		Apply trims and rewrites to source file paths.581*/582package main583 584/*585Implementation details.586 587Cgo provides a way for Go programs to call C code linked into the same588address space. This comment explains the operation of cgo.589 590Cgo reads a set of Go source files and looks for statements saying591import "C". If the import has a doc comment, that comment is592taken as literal C code to be used as a preamble to any C code593generated by cgo. A typical preamble #includes necessary definitions:594 595	// #include <stdio.h>596	import "C"597 598For more details about the usage of cgo, see the documentation599comment at the top of this file.600 601Understanding C602 603Cgo scans the Go source files that import "C" for uses of that604package, such as C.puts. It collects all such identifiers. The next605step is to determine each kind of name. In C.xxx the xxx might refer606to a type, a function, a constant, or a global variable. Cgo must607decide which.608 609The obvious thing for cgo to do is to process the preamble, expanding610#includes and processing the corresponding C code. That would require611a full C parser and type checker that was also aware of any extensions612known to the system compiler (for example, all the GNU C extensions) as613well as the system-specific header locations and system-specific614pre-#defined macros. This is certainly possible to do, but it is an615enormous amount of work.616 617Cgo takes a different approach. It determines the meaning of C618identifiers not by parsing C code but by feeding carefully constructed619programs into the system C compiler and interpreting the generated620error messages, debug information, and object files. In practice,621parsing these is significantly less work and more robust than parsing622C source.623 624Cgo first invokes gcc -E -dM on the preamble, in order to find out625about simple #defines for constants and the like. These are recorded626for later use.627 628Next, cgo needs to identify the kinds for each identifier. For the629identifiers C.foo, cgo generates this C program:630 631	<preamble>632	#line 1 "not-declared"633	void __cgo_f_1_1(void) { __typeof__(foo) *__cgo_undefined__1; }634	#line 1 "not-type"635	void __cgo_f_1_2(void) { foo *__cgo_undefined__2; }636	#line 1 "not-int-const"637	void __cgo_f_1_3(void) { enum { __cgo_undefined__3 = (foo)*1 }; }638	#line 1 "not-num-const"639	void __cgo_f_1_4(void) { static const double __cgo_undefined__4 = (foo); }640	#line 1 "not-str-lit"641	void __cgo_f_1_5(void) { static const char __cgo_undefined__5[] = (foo); }642 643This program will not compile, but cgo can use the presence or absence644of an error message on a given line to deduce the information it645needs. The program is syntactically valid regardless of whether each646name is a type or an ordinary identifier, so there will be no syntax647errors that might stop parsing early.648 649An error on not-declared:1 indicates that foo is undeclared.650An error on not-type:1 indicates that foo is not a type (if declared at all, it is an identifier).651An error on not-int-const:1 indicates that foo is not an integer constant.652An error on not-num-const:1 indicates that foo is not a number constant.653An error on not-str-lit:1 indicates that foo is not a string literal.654An error on not-signed-int-const:1 indicates that foo is not a signed integer constant.655 656The line number specifies the name involved. In the example, 1 is foo.657 658Next, cgo must learn the details of each type, variable, function, or659constant. It can do this by reading object files. If cgo has decided660that t1 is a type, v2 and v3 are variables or functions, and i4, i5661are integer constants, u6 is an unsigned integer constant, and f7 and f8662are float constants, and s9 and s10 are string constants, it generates:663 664	<preamble>665	__typeof__(t1) *__cgo__1;666	__typeof__(v2) *__cgo__2;667	__typeof__(v3) *__cgo__3;668	__typeof__(i4) *__cgo__4;669	enum { __cgo_enum__4 = i4 };670	__typeof__(i5) *__cgo__5;671	enum { __cgo_enum__5 = i5 };672	__typeof__(u6) *__cgo__6;673	enum { __cgo_enum__6 = u6 };674	__typeof__(f7) *__cgo__7;675	__typeof__(f8) *__cgo__8;676	__typeof__(s9) *__cgo__9;677	__typeof__(s10) *__cgo__10;678 679	long long __cgodebug_ints[] = {680		0, // t1681		0, // v2682		0, // v3683		i4,684		i5,685		u6,686		0, // f7687		0, // f8688		0, // s9689		0, // s10690		1691	};692 693	double __cgodebug_floats[] = {694		0, // t1695		0, // v2696		0, // v3697		0, // i4698		0, // i5699		0, // u6700		f7,701		f8,702		0, // s9703		0, // s10704		1705	};706 707	const char __cgodebug_str__9[] = s9;708	const unsigned long long __cgodebug_strlen__9 = sizeof(s9)-1;709	const char __cgodebug_str__10[] = s10;710	const unsigned long long __cgodebug_strlen__10 = sizeof(s10)-1;711 712and again invokes the system C compiler, to produce an object file713containing debug information. Cgo parses the DWARF debug information714for __cgo__N to learn the type of each identifier. (The types also715distinguish functions from global variables.) Cgo reads the constant716values from the __cgodebug_* from the object file's data segment.717 718At this point cgo knows the meaning of each C.xxx well enough to start719the translation process.720 721Translating Go722 723Given the input Go files x.go and y.go, cgo generates these source724files:725 726	x.cgo1.go       # for gc (cmd/compile)727	y.cgo1.go       # for gc728	_cgo_gotypes.go # for gc729	_cgo_import.go  # for gc (if -dynout _cgo_import.go)730	x.cgo2.c        # for gcc731	y.cgo2.c        # for gcc732	_cgo_defun.c    # for gcc (if -gccgo)733	_cgo_export.c   # for gcc734	_cgo_export.h   # for gcc735	_cgo_main.c     # for gcc736	_cgo_flags      # for build tool (if -gccgo)737 738The file x.cgo1.go is a copy of x.go with the import "C" removed and739references to C.xxx replaced with names like _Cfunc_xxx or _Ctype_xxx.740The definitions of those identifiers, written as Go functions, types,741or variables, are provided in _cgo_gotypes.go.742 743Here is a _cgo_gotypes.go containing definitions for needed C types:744 745	type _Ctype_char int8746	type _Ctype_int int32747	type _Ctype_void [0]byte748 749The _cgo_gotypes.go file also contains the definitions of the750functions. They all have similar bodies that invoke runtime·cgocall751to make a switch from the Go runtime world to the system C (GCC-based)752world.753 754For example, here is the definition of _Cfunc_puts:755 756	//go:cgo_import_static _cgo_be59f0f25121_Cfunc_puts757	//go:linkname __cgofn__cgo_be59f0f25121_Cfunc_puts _cgo_be59f0f25121_Cfunc_puts758	var __cgofn__cgo_be59f0f25121_Cfunc_puts byte759	var _cgo_be59f0f25121_Cfunc_puts = unsafe.Pointer(&__cgofn__cgo_be59f0f25121_Cfunc_puts)760 761	func _Cfunc_puts(p0 *_Ctype_char) (r1 _Ctype_int) {762		_cgo_runtime_cgocall(_cgo_be59f0f25121_Cfunc_puts, uintptr(unsafe.Pointer(&p0)))763		return764	}765 766The hexadecimal number is a hash of cgo's input, chosen to be767deterministic yet unlikely to collide with other uses. The actual768function _cgo_be59f0f25121_Cfunc_puts is implemented in a C source769file compiled by gcc, the file x.cgo2.c:770 771	void772	_cgo_be59f0f25121_Cfunc_puts(void *v)773	{774		struct {775			char* p0;776			int r;777			char __pad12[4];778		} __attribute__((__packed__, __gcc_struct__)) *a = v;779		a->r = puts((void*)a->p0);780	}781 782It extracts the arguments from the pointer to _Cfunc_puts's argument783frame, invokes the system C function (in this case, puts), stores the784result in the frame, and returns.785 786Linking787 788Once the _cgo_export.c and *.cgo2.c files have been compiled with gcc,789they need to be linked into the final binary, along with the libraries790they might depend on (in the case of puts, stdio). cmd/link has been791extended to understand basic ELF files, but it does not understand ELF792in the full complexity that modern C libraries embrace, so it cannot793in general generate direct references to the system libraries.794 795Instead, the build process generates an object file using dynamic796linkage to the desired libraries. The main function is provided by797_cgo_main.c:798 799	int main(int argc, char **argv) { return 0; }800	void crosscall2(void(*fn)(void*), void *a, int c, uintptr_t ctxt) { }801	uintptr_t _cgo_wait_runtime_init_done(void) { return 0; }802	void _cgo_release_context(uintptr_t ctxt) { }803	char* _cgo_topofstack(void) { return (char*)0; }804	void _cgo_allocate(void *a, int c) { }805	void _cgo_panic(void *a, int c) { }806	void _cgo_reginit(void) { }807 808The extra functions here are stubs to satisfy the references in the C809code generated for gcc. The build process links this stub, along with810_cgo_export.c and *.cgo2.c, into a dynamic executable and then lets811cgo examine the executable. Cgo records the list of shared library812references and resolved names and writes them into a new file813_cgo_import.go, which looks like:814 815	//go:cgo_dynamic_linker "/lib64/ld-linux-x86-64.so.2"816	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"817	//go:cgo_import_dynamic __libc_start_main __libc_start_main#GLIBC_2.2.5 "libc.so.6"818	//go:cgo_import_dynamic stdout stdout#GLIBC_2.2.5 "libc.so.6"819	//go:cgo_import_dynamic fflush fflush#GLIBC_2.2.5 "libc.so.6"820	//go:cgo_import_dynamic _ _ "libpthread.so.0"821	//go:cgo_import_dynamic _ _ "libc.so.6"822 823In the end, the compiled Go package, which will eventually be824presented to cmd/link as part of a larger program, contains:825 826	_go_.o        # gc-compiled object for _cgo_gotypes.go, _cgo_import.go, *.cgo1.go827	_all.o        # gcc-compiled object for _cgo_export.c, *.cgo2.c828 829If there is an error generating the _cgo_import.go file, then, instead830of adding _cgo_import.go to the package, the go tool adds an empty831file named dynimportfail. The _cgo_import.go file is only needed when832using internal linking mode, which is not the default when linking833programs that use cgo (as described below). If the linker sees a file834named dynimportfail it reports an error if it has been told to use835internal linking mode. This approach is taken because generating836_cgo_import.go requires doing a full C link of the package, which can837fail for reasons that are irrelevant when using external linking mode.838 839The final program will be a dynamic executable, so that cmd/link can avoid840needing to process arbitrary .o files. It only needs to process the .o841files generated from C files that cgo writes, and those are much more842limited in the ELF or other features that they use.843 844In essence, the _cgo_import.o file includes the extra linking845directives that cmd/link is not sophisticated enough to derive from _all.o846on its own. Similarly, the _all.o uses dynamic references to real847system object code because cmd/link is not sophisticated enough to process848the real code.849 850The main benefits of this system are that cmd/link remains relatively simple851(it does not need to implement a complete ELF and Mach-O linker) and852that gcc is not needed after the package is compiled. For example,853package net uses cgo for access to name resolution functions provided854by libc. Although gcc is needed to compile package net, gcc is not855needed to link programs that import package net.856 857Runtime858 859When using cgo, Go must not assume that it owns all details of the860process. In particular it needs to coordinate with C in the use of861threads and thread-local storage. The runtime package declares a few862variables:863 864	var (865		iscgo             bool866		_cgo_init         unsafe.Pointer867		_cgo_thread_start unsafe.Pointer868	)869 870Any package using cgo imports "runtime/cgo", which provides871initializations for these variables. It sets iscgo to true, _cgo_init872to a gcc-compiled function that can be called early during program873startup, and _cgo_thread_start to a gcc-compiled function that can be874used to create a new thread, in place of the runtime's usual direct875system calls.876 877Internal and External Linking878 879The text above describes "internal" linking, in which cmd/link parses and880links host object files (ELF, Mach-O, PE, and so on) into the final881executable itself. Keeping cmd/link simple means we cannot possibly882implement the full semantics of the host linker, so the kinds of883objects that can be linked directly into the binary is limited (other884code can only be used as a dynamic library). On the other hand, when885using internal linking, cmd/link can generate Go binaries by itself.886 887In order to allow linking arbitrary object files without requiring888dynamic libraries, cgo supports an "external" linking mode too. In889external linking mode, cmd/link does not process any host object files.890Instead, it collects all the Go code and writes a single go.o object891file containing it. Then it invokes the host linker (usually gcc) to892combine the go.o object file and any supporting non-Go code into a893final executable. External linking avoids the dynamic library894requirement but introduces a requirement that the host linker be895present to create such a binary.896 897Most builds both compile source code and invoke the linker to create a898binary. When cgo is involved, the compile step already requires gcc, so899it is not problematic for the link step to require gcc too.900 901An important exception is builds using a pre-compiled copy of the902standard library. In particular, package net uses cgo on most systems,903and we want to preserve the ability to compile pure Go code that904imports net without requiring gcc to be present at link time. (In this905case, the dynamic library requirement is less significant, because the906only library involved is libc.so, which can usually be assumed907present.)908 909This conflict between functionality and the gcc requirement means we910must support both internal and external linking, depending on the911circumstances: if net is the only cgo-using package, then internal912linking is probably fine, but if other packages are involved, so that there913are dependencies on libraries beyond libc, external linking is likely914to work better. The compilation of a package records the relevant915information to support both linking modes, leaving the decision916to be made when linking the final binary.917 918Linking Directives919 920In either linking mode, package-specific directives must be passed921through to cmd/link. These are communicated by writing //go: directives in a922Go source file compiled by gc. The directives are copied into the .o923object file and then processed by the linker.924 925The directives are:926 927//go:cgo_import_dynamic <local> [<remote> ["<library>"]]928 929	In internal linking mode, allow an unresolved reference to930	<local>, assuming it will be resolved by a dynamic library931	symbol. The optional <remote> specifies the symbol's name and932	possibly version in the dynamic library, and the optional "<library>"933	names the specific library where the symbol should be found.934 935	On AIX, the library pattern is slightly different. It must be936	"lib.a/obj.o" with obj.o the member of this library exporting937	this symbol.938 939	In the <remote>, # or @ can be used to introduce a symbol version.940 941	Examples:942	//go:cgo_import_dynamic puts943	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5944	//go:cgo_import_dynamic puts puts#GLIBC_2.2.5 "libc.so.6"945 946	A side effect of the cgo_import_dynamic directive with a947	library is to make the final binary depend on that dynamic948	library. To get the dependency without importing any specific949	symbols, use _ for local and remote.950 951	Example:952	//go:cgo_import_dynamic _ _ "libc.so.6"953 954	For compatibility with current versions of SWIG,955	#pragma dynimport is an alias for //go:cgo_import_dynamic.956 957//go:cgo_dynamic_linker "<path>"958 959	In internal linking mode, use "<path>" as the dynamic linker960	in the final binary. This directive is only needed from one961	package when constructing a binary; by convention it is962	supplied by runtime/cgo.963 964	Example:965	//go:cgo_dynamic_linker "/lib/ld-linux.so.2"966 967//go:cgo_export_dynamic <local> <remote>968 969	In internal linking mode, put the Go symbol970	named <local> into the program's exported symbol table as971	<remote>, so that C code can refer to it by that name. This972	mechanism makes it possible for C code to call back into Go or973	to share Go's data.974 975	For compatibility with current versions of SWIG,976	#pragma dynexport is an alias for //go:cgo_export_dynamic.977 978//go:cgo_import_static <local>979 980	In external linking mode, allow unresolved references to981	<local> in the go.o object file prepared for the host linker,982	under the assumption that <local> will be supplied by the983	other object files that will be linked with go.o.984 985	Example:986	//go:cgo_import_static puts_wrapper987 988//go:cgo_export_static <local> <remote>989 990	In external linking mode, put the Go symbol991	named <local> into the program's exported symbol table as992	<remote>, so that C code can refer to it by that name. This993	mechanism makes it possible for C code to call back into Go or994	to share Go's data.995 996//go:cgo_ldflag "<arg>"997 998	In external linking mode, invoke the host linker (usually gcc)999	with "<arg>" as a command-line argument following the .o files.1000	Note that the arguments are for "gcc", not "ld".1001 1002	Example:1003	//go:cgo_ldflag "-lpthread"1004	//go:cgo_ldflag "-L/usr/local/sqlite3/lib"1005 1006A package compiled with cgo will include directives for both1007internal and external linking; the linker will select the appropriate1008subset for the chosen linking mode.1009 1010Example1011 1012As a simple example, consider a package that uses cgo to call C.sin.1013The following code will be generated by cgo:1014 1015	// compiled by gc1016 1017	//go:cgo_ldflag "-lm"1018 1019	type _Ctype_double float641020 1021	//go:cgo_import_static _cgo_gcc_Cfunc_sin1022	//go:linkname __cgo_gcc_Cfunc_sin _cgo_gcc_Cfunc_sin1023	var __cgo_gcc_Cfunc_sin byte1024	var _cgo_gcc_Cfunc_sin = unsafe.Pointer(&__cgo_gcc_Cfunc_sin)1025 1026	func _Cfunc_sin(p0 _Ctype_double) (r1 _Ctype_double) {1027		_cgo_runtime_cgocall(_cgo_gcc_Cfunc_sin, uintptr(unsafe.Pointer(&p0)))1028		return1029	}1030 1031	// compiled by gcc, into foo.cgo2.o1032 1033	void1034	_cgo_gcc_Cfunc_sin(void *v)1035	{1036		struct {1037			double p0;1038			double r;1039		} __attribute__((__packed__)) *a = v;1040		a->r = sin(a->p0);1041	}1042 1043What happens at link time depends on whether the final binary is linked1044using the internal or external mode. If other packages are compiled in1045"external only" mode, then the final link will be an external one.1046Otherwise the link will be an internal one.1047 1048The linking directives are used according to the kind of final link1049used.1050 1051In internal mode, cmd/link itself processes all the host object files, in1052particular foo.cgo2.o. To do so, it uses the cgo_import_dynamic and1053cgo_dynamic_linker directives to learn that the otherwise undefined1054reference to sin in foo.cgo2.o should be rewritten to refer to the1055symbol sin with version GLIBC_2.2.5 from the dynamic library1056"libm.so.6", and the binary should request "/lib/ld-linux.so.2" as its1057runtime dynamic linker.1058 1059In external mode, cmd/link does not process any host object files, in1060particular foo.cgo2.o. It links together the gc-generated object1061files, along with any other Go code, into a go.o file. While doing1062that, cmd/link will discover that there is no definition for1063_cgo_gcc_Cfunc_sin, referred to by the gc-compiled source file. This1064is okay, because cmd/link also processes the cgo_import_static directive and1065knows that _cgo_gcc_Cfunc_sin is expected to be supplied by a host1066object file, so cmd/link does not treat the missing symbol as an error when1067creating go.o. Indeed, the definition for _cgo_gcc_Cfunc_sin will be1068provided to the host linker by foo2.cgo.o, which in turn will need the1069symbol 'sin'. cmd/link also processes the cgo_ldflag directives, so that it1070knows that the eventual host link command must include the -lm1071argument, so that the host linker will be able to find 'sin' in the1072math library.1073 1074cmd/link Command Line Interface1075 1076The go command and any other Go-aware build systems invoke cmd/link1077to link a collection of packages into a single binary. By default, cmd/link will1078present the same interface it does today:1079 1080	cmd/link main.a1081 1082produces a file named a.out, even if cmd/link does so by invoking the host1083linker in external linking mode.1084 1085By default, cmd/link will decide the linking mode as follows: if the only1086packages using cgo are those on a list of known standard library1087packages (net, os/user, runtime/cgo), cmd/link will use internal linking1088mode. Otherwise, there are non-standard cgo packages involved, and cmd/link1089will use external linking mode. The first rule means that a build of1090the godoc binary, which uses net but no other cgo, can run without1091needing gcc available. The second rule means that a build of a1092cgo-wrapped library like sqlite3 can generate a standalone executable1093instead of needing to refer to a dynamic library. The specific choice1094can be overridden using a command line flag: cmd/link -linkmode=internal or1095cmd/link -linkmode=external.1096 1097In an external link, cmd/link will create a temporary directory, write any1098host object files found in package archives to that directory (renamed1099to avoid conflicts), write the go.o file to that directory, and invoke1100the host linker. The default value for the host linker is $CC, split1101into fields, or else "gcc". The specific host linker command line can1102be overridden using command line flags: cmd/link -extld=clang1103-extldflags='-ggdb -O3'. If any package in a build includes a .cc or1104other file compiled by the C++ compiler, the go tool will use the1105-extld option to set the host linker to the C++ compiler.1106 1107These defaults mean that Go-aware build systems can ignore the linking1108changes and keep running plain 'cmd/link' and get reasonable results, but1109they can also control the linking details if desired.1110 1111*/1112 
codekingpro/portable-devtools · Team Ai