Skip to content

Latest commit

 

History

History
847 lines (795 loc) · 78.8 KB

Limitations.md

File metadata and controls

847 lines (795 loc) · 78.8 KB

Limitations: where the seams are

So you're about to point go2cs at your own Go code. Before you spend an evening on it, here is where it will fail, where it will fight you, and where it will quietly do something a little different from Go -- better you hear it from me than from a stack trace. Specific bugs with workarounds live in Known issues. This page is the limits that come with running Go on .NET, plus the rough spots real code hits today.

This page describes go2cs as it is on the master branch and in the 1.26.11.1 release. Where the two differ, it says which one a limit applies to.

The short version

Good odds tonight: pure Go that builds with the Go release go2cs tracks and CGO_ENABLED=0, leans mostly on the standard library, and runs on Windows, Linux or macOS. A longer evening: lots of third-party modules, unsafe, assembly fast paths, cgo, or tests that pull in testify.

  • Your code must build with the Go release go2cs tracks, the one in Requirements, which the go2cs dotnet tool downloads for you.
  • cgo converts only through -cgo, and only calls of C a shared library defines or the package's own C defines (cgo).
  • Assembly, //go:linkname and deep unsafe tricks compile clean, then fail at run time. Many libraries ship a pure-Go fallback behind a build tag. A plain -recurse applies the common ones (safe, purego, noasm) for you; an explicit -tags replaces them, so restate them beside your own.
  • By default, each live goroutine holds an operating-system thread. Thousands alive at once are fine; Go's million are out of reach. A program built and run with async twins parks goroutines that wait in twinned code instead (experimental).
  • It's usually slower than Go, starts slower and uses more memory.
  • One conversion targets one operating system.
  • Most failures are loud. A few differences are silent: see the last bullet under what behaves differently.

What won't make the trip

  • cgo beyond calls of shared-library C functions: see cgo.
  • A self-referential constraint over a pointer, when a method shares the element's storage. Walk[*Node] under Walk[N Tree[N]] with Children() []N stops the run with error GO2CS2002, naming the site and the method. Two related shapes over a pointer element are refused the same way, as GO2CS2005 and GO2CS2006 (diagnostic codes). A pointer element reaches the generic code through a proxy object, and a []N, map[K]N, chan N or *N the proxy passed along would be a copy, not Go's shared value. The same function over a value element converts, and so does a constraint whose methods pass only N, funcs and arrays (how). No Go 1.26 standard-library package reaches it.
  • Go newer than the library tracks. A newer go line in your go.mod, or any dependency's, gets package requires newer Go version or a refusal naming both releases. Set GOTOOLCHAIN=local and pin older versions until go build ./... passes, as the module walkthrough does.
  • Hand-written assembly. A function whose body lives in a .s file usually becomes a stub. The conversion names each one (warning GO2CS2012, diagnostic codes), the project builds clean, and the first call throws a NotImplementedException saying no implementation reached this compilation. Convert with the library's pure-Go build tag (below), or write the body in C#. //go:linkname into the runtime gets the same stub, outside a short list the converter knows.
  • One generics form. type Cell[T any] = struct{ Row, Col T }, a generic alias of an anonymous struct or interface, gets a warning, and every use is a C# compile error. Name the struct instead.
  • Code that doesn't type-check for the target still converts, with the literal text invalid type where a type is missing (error GO2CS1003), and the C# build stops there.

What converts, but doesn't behave exactly like Go

  • Reflection cannot read a struct whose arrays are held inline. When a package reads native memory as a struct, through (*T)(unsafe.Pointer(p)), go2cs lays that struct out as Go does and holds its array fields inside it. Indexing, len, range and printing one of those arrays work as in Go. Reflection over the struct that holds them does not: fmt.Printf("%v", s), reflect.ValueOf(s).Field(i) and anything else that walks the struct's fields panics with reflect: field T.F is a Go array held inline (go.arrays); reflection does not read or address it. Print the fields one at a time instead.

  • A slice of an array held inline panics when the struct around it also holds a string, a slice, a map, an interface or a pointer. A slice of such an array (p.ID.Data4[:2]) uses the array's own bytes, as in Go, so go2cs holds the storage still for as long as the slice lives. It cannot hold still a struct that holds a Go reference, so the slice panics with inline array slice: an array held inline in a struct that also holds a Go reference cannot be held still, so it cannot be sliced. This is ordinary Go, and programs that use go-winio will hit it when they keep a GUID beside a string: type P struct { ID guid.GUID; name string }, then p.ID.Data4[:2]. go-winio's own GUID methods are not affected, because each slices its own copy of the GUID. Two forms work today: a copy into or out of the array with constant bounds (copy(buf, p.ID.Data4[:])), and slicing a local copy of the array (d := p.ID.Data4; s := d[:2]) when writes need not reach p.

  • By default, goroutines are operating-system threads (why). A goroutine holds its thread for as long as it lives; when it ends, the thread runs the next go statement, so starting goroutines one after another is cheap and holding many alive at once is not. On Windows x64, ten thousand parked goroutines cost several times Go's memory and seconds to start, a hundred thousand take minutes, and a million do not finish starting. With threads, runtime.GOMAXPROCS(1) does not make anything run one at a time. Bound your fan-out with a worker pool, and remember that a net/http server spends one on every open connection. On macOS the kernel caps the threads one process may run (kern.num_taskthreads, a few thousand on the hosted macOS 15 machines measured), and the go statement past it ends the program (Known issues). Async twins, experimental and opt-in, run goroutines that wait in twinned code on a small pool of threads.

  • A deadlock usually hangs where Go prints all goroutines are asleep - deadlock!. The message appears only when every goroutine, main included, waits on a nil channel or an empty select {}, and then with Go's goroutine blocks. A deadlock on an ordinary channel or lock blocks forever: break in with a debugger, where, by default, each goroutine is a thread named goroutine-N.

  • Stacks don't grow. By default, main runs on a thread that reserves 1 GiB, which covers Go's 1 GB limit for it, and a goroutine's thread reserves 256 MB (GO2CS_GOROUTINE_STACK changes it), or 16 MB when the converter proves it cannot recurse (how). Recursion past a thread's reserve ends the process with .NET's Stack overflow., with no panic and no deferred calls, where Go prints fatal error: stack overflow and exits 2. Your main package's init functions run on the startup thread's smaller stack, and so does main when an init called runtime.LockOSThread, as in Go. With the scheduler of async twins on, every pool thread reserves 1 GiB, or the goroutine reserve when that is larger, so main's twin and every goroutine the scheduler runs keep at least main's 1 GiB. A set GO2CS_GOROUTINE_STACK sizes the pool threads instead, lower or higher, never below 1 MiB, and then bounds main's recursion too; goroutines on threads of their own keep 256 MB (16 MB bounded).

  • recover() catches Go panics, not every .NET exception. Nil dereference, divide by zero and index out of range recover as in Go. Any other .NET exception, NotImplementedException included, runs your deferred calls and keeps unwinding, and recover() returns nil. As in Go, recover() stops a panic only when the deferred function calls it directly, with two exceptions (how): an exported function that calls recover() stops the panic even when a deferred function calls it, and an unexported one that another package defers through a func value returns nil.

  • A crash's traceback is sometimes shorter than Go's. An unrecovered panic prints Go's panic lines, the whole chain included (panic: message [recovered, repanicked]), and exits with status 2, a goroutine's panic while main returns included. Below them, the frames match Go's for a panic in a function with one deferred call. When several functions on the stack each defer a call, only the function that panicked is shown, and a named deferred function that panics again shows the line it is declared on.

  • unsafe works over plain numbers and stops at anything .NET's garbage collector tracks (the rules). A pointer to anything holding a string, slice, map, interface, pointer or fixed-size array gets a stand-in number, not an address, so the older tricks (the *(*string)(unsafe.Pointer(&b)) pun, a hand-built slice header) don't convert mechanically.

  • A func variable takes a pointer word stored into it only when the word is another func value's word. *(*unsafe.Pointer)(unsafe.Pointer(&f)) = p copies the func when p was read the same way from another func, and nil is the nil func. A hand-built funcval whose word is a code address panics by name: go2cs does not bind a function to a code address (func words). A callback from C into Go needs no such binding: C calls an //export through its native entry point, never through a Go func value. This is the master branch. In go2cs 1.26.11.1 such a store is lost with no message: the func variable keeps the value it had, so a func that was nil stays nil and a call through it panics.

  • A func value's word does not keep a closure alive. Held as an unsafe.Pointer or a uintptr, the word of a closure names it only while something else holds the closure. Once nothing does and a collection runs, storing the word back into a func variable, or calling through it, panics by name ("names no live func"). In Go, the unsafe.Pointer keeps the closure alive. A top-level function's word is good for the life of the process.

  • One array view can end the process. Go's (*[N]E)(unsafe.Pointer(&x.f))[:], where f is an array field read as an array of another element type (an [8]int8 name read as [8]byte), works when x is a variable or a pointer, and through any chain of named fields from one (&x.a.f). When the field is promoted from an embedded struct (&w.f), or belongs to a slice element (&s[i].f) or to a call's result (&g().f), the converted program can stop with an access violation, which recover does not catch. Take the field's address from a variable or a pointer instead: write the embedded field out (&w.inner.f), or bind the element or the result first (p := &s[i], then &p.f) (the field view).

  • The address of another package's pointer- or interface-typed variable is the address of a copy. An exported variable with a value type has its own storage, so &otherpkg.V, f := otherpkg.V.Reset, flag.BoolVar(&otherpkg.Debug, ...) and &otherpkg.S.Field reach the variable itself, as in Go. Two kinds are still handed to another package as a copy when it takes their address, so a write through it never reaches the variable: a variable whose type is a pointer or an interface (&otherpkg.ErrMissing), and a variable whose storage lives somewhere else (runtime.MemProfileRate, or one declared with a two-argument //go:linkname). Reading them, assigning to them and calling their methods work. Take the address in the declaring package, or have it export an accessor (Known issues).

  • Garbage collection is .NET's. An object your function just stopped using may not be collectible until the function returns, so "drop the reference, call runtime.GC(), expect the finalizer" can wait forever. GOGC and GOMEMLIMIT are read and reported, by debug.SetGCPercent for example, but .NET's collector does not follow them.

  • Runtime introspection is thinner than Go's. A dump of all goroutines lists each one and what it waits on, with frames for the calling goroutine only. pprof.StartCPUProfile gives a profile with no samples (profile with .NET's tools). debug.ReadBuildInfo() reports the module, its dependencies, GOOS, GOARCH, CGO_ENABLED and DefaultGODEBUG, but no -compiler, -buildmode, GOAMD64 or vcs.* settings and no replacements, and nothing for a program converted outside a module (how). On Windows, time.LoadLocation("Europe/Berlin") fails until you import time/tzdata (or set ZONEINFO).

  • A few quiet ones, each rare, where converted code gives a different answer and says nothing:

    • A variadic function that keeps, returns or captures its ...T parameter, or appends or copys into it, works on a private copy: after f(s...), its writes are not the caller's s.

    • Copying a struct by value shares any fixed-size array inside an embedded struct.

    • A slice of one number type laid over another's storage (unsafe.Slice((*uint64)(unsafe.Pointer(&b[0])), n)) is a copy: writes through it never reach b.

    • A write through unsafe.StringData's pointer into a string literal or a one-byte string faults in Go, because those bytes are read-only. In go2cs those bytes are shared by every equal string, so the write changes every later evaluation of that literal, in every package, or every one-byte string of that byte. Set GO2CS_CHECK_STRING_WRITES=1 (Tuning) to have it caught by name: unsafe.StringData then gives the pointer a private copy of the bytes, so the write reaches no other string, and the program panics at the next read through that pointer (*p, or a pointer unsafe.Add made from it) or at the next unsafe.StringData over the same string. A write through a view that reads the bytes directly, a slice from unsafe.Slice(p, n) or a (*[N]byte)(unsafe.Pointer(p)) array pointer, also lands in the copy, and is reported only if a later access goes through one of those two checks. The Data of a reflect.StringHeader laid over such a string names the same copy. With the check on, three cases are still not covered, and none of them panics:

      • A literal hoisted into a static readonly field ("..."u8), which the standard library does throughout and a package converted with -hoist-literals does too. A write through unsafe.StringData changes that literal wherever it is used: after a write through the pointer to err.(*strconv.NumError).Func from strconv.ParseBool("x"), every later such error names the changed function.
      • A literal written in place as "..."u8 (format strings and other string arguments in converted code). It becomes a new array at each evaluation, so a write through unsafe.StringData is private to that one value.
      • A string unsafe.String builds from unsafe.StringData's pointer. It shares the private copy, so it reads any byte later written there, and unsafe.StringData over it hands out a pointer with no check.

      A heap string (one built at run time) behaves as in Go: the write changes it and every string sharing its bytes.

    • A pointer's number kept in a uintptr and turned back into a pointer in a later statement (n := uintptr(unsafe.Pointer(p)), then (*T)(unsafe.Pointer(n))) can name memory that has since moved, and the number does not keep the value alive. Go calls this invalid too, but it often works there. Do the arithmetic and the conversion in one expression, or use unsafe.Add.
    • A pointer to a field made by arithmetic does not compare equal to the field's own address: (*int64)(unsafe.Add(unsafe.Pointer(&p), 8)) == &p.y is false where Go says true.
    • A left shift of an untyped constant that takes a named integer type from its context, such as m & (1 << uint(32-1-i)) with m an fs.FileMode, wraps its count at the type's width: a count of the width or more gives the wrapped result where Go gives 0, and a negative count does not panic.
    • In a cgo package, a pointer into Go memory rebuilt from a number can reach C unchecked in three narrow cases (cgo).
  • On Windows x64, a system call to an address Control Flow Guard does not list as a call target ends the process. Converted programs run with Control Flow Guard under the JIT, as measured on the apphost and on dotnet.exe (and under Native AOT when built with <ControlFlowGuard>Guard</ControlFlowGuard>), and syscall's call trampoline checks the function it is given the way the process's own indirect calls are checked. An exported function, or a pointer the API handed out, passes. An address computed by offset inside a system DLL, which Go and an unguarded call would reach, ends the process with 0xc0000409 and no go2cs message. Call exported functions, through LazyProc or GetProcAddress. The trampoline makes one more check with the same exit code: its argument block must lie on the calling thread's live stack, which every Proc.Call and SyscallN meets, so a process that ends with 0xc0000409 at a system call was stopped by one of the two.

    • Under Native AOT on Windows, syscall.NewCallback refuses a func whose type no call site names: one that reaches it only as an any value (one stored in an interface before the call, as the runtime's own callback tests do), one whose func type names a type parameter, and, from hand-written C#, a variadic or optional-parameter method, one with a ref parameter or more than 16 parameters, or one with a pointer, ref-like or file-local type in its signature. The call panics with "no native code for callback type". Pass the func itself, of its own func type.
    • On Windows, syscall.NewCallback takes a func of 0 to 16 arguments. Go takes any number whose argument frame fits 64 words. A func of 17 or more panics with "N-argument callbacks are not implemented in this port"; under Native AOT it panics with "no native code for callback type" instead, since a func of that many arguments has no type a call site can name.

cgo

What converts. Without -cgo, a package whose build selects a file with import "C" stops the run with error GO2CS2001, which names the file. With -cgo, on a machine with a C compiler (go env CC), a package converts when every C use it makes is a call of a C function a shared library defines, passing integers, floating-point numbers and pointers, structs of integers and pointers by value, one struct or one scalar by pointer, or a void * that is nil or points at C memory. A struct with a void * member converts by pointer, the member nil or C memory, and a C pointer typedef (typedef const char *T) converts as a result and as a parameter. C.CString, C.CBytes, C.GoString, C.GoStringN, C.GoBytes, C.malloc, C.free and defer C.f(…) convert, with the package's C types and constants. A program that uses the converted package needs only the C library.

On the master branch, Go code that walks C memory converts too: it reads and writes a pointer field of a C struct that lives in C memory (l.next), and loads and stores through a **C.T (*p, as a walk down a C list such as addrinfo's ai_next does). A pointer field reached through a nested struct value, an array of pointers, a field whose type is a C pointer typedef, and a union are still refused by name, and so is storing a pointer into Go memory into C memory. In go2cs 1.26.11.1, reading a pointer field of a C struct in C memory fails with a panic.

On the master branch, a slice of C memory whose element is a C struct with a pointer field (from unsafe.Slice, or (*[N]C.T)(p)[:]) converts as in Go: an element's fields are read and written through the index, a pointer field included, an element read by value is a copy decoded out of C memory, and a slice of an array member is a window on the C bytes. Storing a whole element by value (s[i] = v, or a range statement that assigns s[i]), storing into an element of an array member (s[i].a[j] = x), and copy into, clear of or an append within the capacity of such a slice are refused by name. Through a pointer to an element (p := &s[i]) the fields and the whole element read as through the index, but an element of an array member (p.a[j]) is refused by name: read it as s[i].a[j]. Handing such a pointer to a function (f(p) with a *C.T parameter) and reading a field through a written dereference ((*p).f) are refused by name: read the element as *p or the field as p.f where the pointer is. A slice of an array member of a nested struct (s[i].in.a[:]) is refused by name.

On the master branch, a number made from a Go pointer (unsafe.Pointer(uintptr(unsafe.Pointer(&x)) + off), in one expression or through a variable) is handed to C as a void * when it points into Go memory that holds no Go pointers, and that memory is held still for the call. A number one past the end of that memory, the end of a begin/end pair, is not held still, so C may only compare it, never read or write through it. A 64-bit integer argument that is go2cs's stand-in for the address of a Go value holding Go pointers is refused by name.

On the master branch, C may keep a Go pointer past the call when a runtime.Pinner pins the memory, as cgo requires: the pin holds the value and every array inside it still until Unpin. A pinned value whose Go layout is not its C layout (a struct holding an array, for instance) is refused by name. Two cases are not covered:

  • A pointer C keeps without a Pinner is invalid Go, though it usually works under Go, whose heap does not move. Here the memory can move at the next collection, and nothing reports it.
  • Pinning an element of an array does not pin the struct that holds the array (Go's pin does). Pin the whole value.

One target. A -cgo conversion is for one operating system and architecture: the machine's own, or another one named with -platforms when CC names that target's C compiler (for example zig cc -target <triple>). The converted package refuses its C bindings on any other: when the package loads, before any of its code runs. A single-package conversion builds against a go2cs clone (dotnet build -p:go2csPath=<go2cs>/src/). Under -recurse -cgo a module's cgo packages convert with the module, and under -recurse=nuget -cgo they reference the go.* packages. A module with a cgo package packs for publishing as a package for each of win-x64, linux-x64, osx-x64, linux-arm64 and osx-arm64, each with its own C binding. Such a package is published only against a go.lib that carries the load-time target check, which the go.* 1.26.11.1 packages do not. The standard library itself is converted with CGO_ENABLED=0, and a module converted with -recurse -cgo uses it as it is. So a package that imports net or os/user gets their builds without cgo, the ones Go itself uses with CGO_ENABLED=0: net resolves host names with Go's own resolver, not the C library's, and os/user reads the user database files directly. go2cs does not convert the net resolver with cgo yet (Roadmap). A package that imports runtime/cgo or plugin is refused by name: without cgo they are not working builds.

That is the master branch. go2cs 1.26.11.1 converts one cgo package at a time, for the machine's own operating system and architecture only: there -cgo does not combine with -recurse, a cgo package cannot be packed, and the target check runs at the package's first C call rather than when it loads.

What is refused, by name. Each of these is not supported yet; the Roadmap says what is planned.

  • a pointer into Go memory handed to C as a void *, or to C.GoBytes, C.GoString or C.GoStringN. A pointer into a slice or an array is refused when the package is converted; unsafe.Pointer(&x) is refused when the call runs, with a message that names the call. Inside a method with a pointer receiver, unsafe.Pointer(p) of a pointer of the receiver's own type is refused when the package is converted: move the call into a function that takes the pointer as a parameter;
  • a #define that is not a constant. A function or variable the preamble defines, or a C or assembly file of the package's own defines, is compiled into a side library beside the bindings (cgo Phase 4 and 4b), except in a package that names #cgo pkg-config. A name a C++, Objective-C, Fortran or .syso file of the package's own could define is refused by name, and so is a name two of the package's files define as a global symbol, which C's link and Go's both reject. A name the package's own C calls that nothing in the package defines and no library it links exports (another package's C, or a Go //export called by its C name) is refused by name when the side library is linked, on every target: Go links all of a program's C together, and go2cs links each package's C alone. So is a name in a library the package does not name in #cgo LDFLAGS (a preamble calling sin with no -lm), which go's link refuses too. A file of the package's own that nothing the package's Go uses needs is left out of the conversion, and named (warning GO2CS2017): a constructor in it runs under go and not here;
  • an //export C calls on a thread no goroutine called C from (a thread the C library made), which ends the program by name; an export C calls by its name rather than through a function pointer Go handed it; and an export that is a method, returns more than one result or a result that is not a C scalar, or takes a parameter that is not a C scalar, a void *, a pointer to a C type, or a pointer to a pointer to a C struct (C's array of struct pointers, read through its address, an array view over it as go-sqlite3 reads argv, or a direct *argv). A pointer to a pointer to a C scalar, char **argv among them, is refused. An export C calls back through a pointer, on the thread of the Go call into C, runs as Go runs it (cgo Phase 5). A panic in it reaches the Go code that called C, as it does under go, and recover() there stops it; but C gets the result's zero value and runs on to the end of its call, where under go the C frames between are abandoned. A further callback during that C call returns zero without running Go code, and the panic arrives only when the C call returns: a C call that never returns (a loop that keeps calling back) never delivers it, where go ends the program or unwinds at the panic;
  • a C variable whose type is not a C scalar or struct (an array, a pointer, a function pointer or a union); C.x of a scalar or struct type reads and writes the variable in place, as Go does, once a library the package links exports it;
  • a C function used as a value, unless it is an //export (its address is then the export's native entry point), and go C.f(…) with a pointer cmd/cgo checks;
  • a C function Go's own cgo build does not import by its C name: one a header renames (macOS on x64 makes fstat the symbol fstat$INODE64), or one the C compiler inlines. go2cs cannot tell the two apart, so it refuses both rather than bind a function C would not call: error GO2CS2001: C.abs: cmd/cgo's own binary does not import a symbol named abs, .... Which functions those are depends on the compiler and the C library: abs and labs everywhere, and with glibc also atoi, atol, toupper, tolower and fabs.

Where it differs from Go. go2cs never hands C a pointer into Go's memory: it hands C a copy of the one struct a pointer points at, and copies it back after the call. So cgo's pointer check differs from Go's in five cases, all where a program breaks or bends cgo's pointer rules. In two, Go panics and go2cs proceeds:

  • a pointer held in a variable, when the object it points into also holds a Go pointer;
  • a pointer held in a variable, when the object it points into lives in package-level memory.

Go checks a pointer held in a variable against the whole object it points into. go2cs proceeds in both cases, since C only sees the copy. This variable check is the one most cgo calls in the Go toolchain's own cgo packages take.

In three, Go proceeds and go2cs refuses the call when it is made:

  • a struct member that points at memory pinned with runtime.Pinner;
  • any pointer under GODEBUG=cgocheck=0;
  • a struct passed by value whose pointer member points into Go memory that holds no pointer.

A Go struct viewed as a C struct crosses as an image, and C's writes land when the call returns. A struct pointer that views a Go struct of another type which holds an array (net's (*C.struct_sockaddr)(unsafe.Pointer(&sa)), sa a syscall.RawSockaddrInet4) has no storage go2cs can hand C, so go2cs hands C an image of the whole Go struct, at Go's own offsets, and decodes it back after the call. It decodes only when C changed the image, so C's write lands in the Go struct when the call returns, not while C runs:

  • a goroutine that reads the struct during a blocking call sees the old value;
  • if C and a goroutine both write it during the call, C's write wins at the return;
  • a bool C writes as a byte other than 0 or 1 reads back as true.

Three views of one Go value in one call share one image, as Go's one memory does. One Go value handed to C both as such a view and through another pointer of the same call is refused by name, and so is a view of a Go struct that holds a Go pointer.

A known memory-safety gap: a pointer rebuilt from a number, in three narrow cases. go2cs refuses, by name, any address inside Go memory that it is holding still, even after the address has been through a uintptr: u := uintptr(unsafe.Pointer(p)), then unsafe.Pointer(u + n), the reversed sum unsafe.Pointer(n + uintptr(unsafe.Pointer(p))), and a slice element viewed as another type ((*C.int)(unsafe.Pointer(&b[4]))) and then held as a uintptr. Go's own one-expression form, unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n), converts to unsafe.Add, which go2cs refuses by name, as it does unsafe.Pointer(p) itself. Three cases still cross, because go2cs is no longer holding the memory, or never was. In each, the call goes ahead, and the memory may move while C uses it:

  • a number kept after nothing uses p any more. go2cs stops holding the memory still, and the number reads as C memory. Go's own rules already forbid keeping a pointer as a uintptr like this;
  • a number taken inside a method with a pointer receiver, from a pointer of the receiver's own type. go2cs makes that number without holding the memory still. Passing such a pointer to C directly is refused when the package is converted; taking it through a uintptr first is not caught;
  • Go memory held still before the program's first cgo package was loaded, which can be missing from go2cs's record of what it holds.

A Go pointer in a void * member of one struct is refused with Go's text for the call's form. For C.f(&x) Go names the member's kind, "Go pointer to unpinned Go unsafe pointer"; through a variable holding the struct's address (p := &x; C.f(p)) Go checks the whole object and says "Go pointer to unpinned Go pointer". go2cs says the same in each, from the call form the conversion passes the wrapper.

A Go array of C pointers costs its whole length on every call. C.f(&argv[0]) lets C read or fill every pointer in the array, as in Go. go2cs holds such an array as Go pointers rather than as machine words, so for the call it copies every element of the array into a word array, hands C that, and copies every word C changed back afterwards. The copy covers the whole array behind the slice, not only the part C uses: argv[2:] of a long array copies the long array, on every call. A word C writes that points into the Go memory the call handed it, the array itself included (argv[0] = &argv[2]), is refused by name, where Go would keep it. An array of C pointers that lives in C memory crosses by its own address, with no copy.

A Go array or slice of C structs costs its whole length on every call. C.f(&cols[0]) lets C read or write every struct in the array, before the one it is handed included, as in Go. go2cs holds such structs in a layout C cannot read, so for the call it copies every element of the backing array into an array of C structs, hands C the element's copy, and after the call copies back each element whose bytes C changed. So a goroutine's write to an element C did not touch survives the call. The copy covers the whole backing array, from its first element, whatever part C uses. Where go2cs differs from Go:

  • C's writes land in the Go array when the call returns, not while C runs;
  • two pointers into one Go array in one call (swap(&a[i], &a[j])), or one such pointer beside another pointer to the same array, are refused by name, where Go hands C the one array;
  • a pointer C returns, or writes into a struct, that points inside an element (not at an element's start), or one past the array's end, is refused by name, and so is a pointer member C sets to another element;
  • for an element before the slice Go checks (&s[0] where s is cols[1:]), or past its capacity (cols[0:2:2]), a Go pointer in a pointer member crosses as NULL, and a NULL C stores there is not seen; Go checks nothing there either;
  • a C function used as a value (defer C.f(&s[0]), go C.f(…), f := C.f) is checked as the address form, from the first element of the backing array, where Go checks the slice the call names;
  • for p := &x.cols[0]; C.f(p), Go checks the whole object that holds the array, and for a package-level variable holding Go pointers it panics; go2cs checks the array itself. An element of an array in C memory crosses by its own address, with no copy.

Platforms. A converted cgo program was built and run against the Go build of the same program on linux/amd64, darwin/amd64, darwin/arm64 and windows/amd64, and printed what Go printed apart from the differences above.

What works, but costs you something

  • Speed. In the performance comparison, measured on win-x64, most compute lands within a small multiple of Go's time, string-heavy work takes several times longer, maps run at parity or better, and asking at run time whether a value satisfies an interface (v.(fmt.Stringer)) is the slowest thing converted code does. Tuning converted code says which deployment and runtime settings to choose. Measure your own hot path, in Release.
  • Startup, memory and shipping. A converted program loads .NET and one DLL per converted Go package it uses, and the JIT compiles each method the first time it runs; package-level tables are built when first read. You ship a .NET app, not Go's small static binary: dotnet build output needs the .NET 10 runtime, and dotnet publish -r <runtime> gives a self-contained folder compiled ahead of time with ReadyToRun, which starts noticeably faster (on linux-x64). dotnet run and dotnet build never get ReadyToRun (how).
  • Trimming. A converted project carries the partial trim mode, and a C# project you write gets the same default from the packages. A trimmed publish runs, and its output matches the untrimmed build's. It warns (on linux-x64): one IL2104 for each go.* package with trim warnings, a handful for a program that uses fmt, and -p:TrimmerSingleWarn=false lists the warnings behind them, most of them golib's, runtime's and reflect's use of reflection. A project built from the converted source lists them all. A Native AOT publish adds two more codes: one IL3053 for each package with AOT analysis warnings (three: runtime, internal.abi and reflect), and one IL3000, where runtime reads Assembly.Location to open a symbol file; the path is empty in a native image, and runtime falls back to reading the file another way.
  • Single-file and Native AOT. A single-file publish needs ReadyToRun compiled per assembly (Known issues). Native AOT starts much faster and holds less memory, but once running it is slower than the JIT on most rows of the comparison (win-x64), and a publish compiles every converted package your program references in full (Known issues has the measurements).
  • Allocation. Converted code allocates where Go's compiler doesn't, so expect more garbage and failing testing.AllocsPerRun assertions.
  • Crypto, most hashing and math/big run Go's portable code, the way Go builds with -tags purego: correct, validated, and slower than Go's assembly. A TLS handshake is where you will notice.

Third-party modules: where they trip today

The validated modules page lists the modules validated so far.

  • A dependency's assembly converts to methods that throw when called, unless a tag deselects it. A plain -recurse (your module plus its dependencies) applies safe, purego and noasm for you, so a fast path behind !purego or !noasm is replaced by the library's pure-Go fallback (Build tags for a module). A file gated on the architecture alone has no such fallback, and the conversion names each stub it leaves (warning GO2CS2012). Where the same package already holds the answer in Go under another name, go2cs forwards the stub to it: zeebo/xxh3's accumNEON and accumBlockNEON, which its arm64 build calls for every input over 240 bytes, run its own accumScalar and accumBlockScalar. Plain xxh3 still stops earlier, on every architecture, at its unsafe string views (below); use the repository's copy of it named there. An explicit -tags replaces every default, so include safe,purego,noasm with yours, and under -tests include math_big_pure_go too.

  • A test suite that imports testify depends on the safe tag. Its bundled go-spew does pointer arithmetic into reflect.Value at load, which the runtime library refuses by design, and go-spew's safe tag selects its fallback. Drop the tag, with -module-safe-tag=false or an explicit -tags that leaves it out, and the converted test program dies at startup. With the tag on, testify works: on the master branch, github.com/stretchr/objx's suite, which uses testify, validates (validated modules).

  • A hung test is stopped, where go test waits. A converted test still running 15 minutes after it started is reported as a failure and marked abandoned, and the run moves on to the next test (-test-deadline changes the limit, Command line). Its goroutines keep running, so every later result says it ran after the abandoned test.

  • Converter bugs that surface as C# compile errors, usually in corners of the type system. In your own code, reshape the Go. In a dependency, point a replace at a patched copy, or fix the generated .cs and mark the file [module: go.GoManualConversion] so the next conversion leaves it alone. New ones still turn up: tell me.

  • unsafe views of a string's or a slice's bytes are not supported yet. Go code can read a string or a []byte through its header, *(*struct{ p unsafe.Pointer; n uint })(unsafe.Pointer(&s)), and then read bytes at unsafe.Pointer(uintptr(p) + i) or through (*[8]byte)(p). Converted, these stop with a named runtime panic, because the string or slice lives in .NET-managed memory with no fixed address to offset. github.com/zeebo/xxh3 is the common case; the repository carries an unsafe-free copy of it that computes the same hashes, for a replace github.com/zeebo/xxh3 => <go2cs clone>/src/forks/github.com/zeebo/xxh3@v1.1.0. go2cs has no general fix for these views yet.

  • A store through a []byte read as a string panics, or is lost. *(*string)(unsafe.Pointer(&b)) = s, and the same store through a two-word string header (*(*struct{ p unsafe.Pointer; n uint })(unsafe.Pointer(&b)) = h), replaces the slice's data pointer and length in Go and keeps its capacity. The views go2cs reads these through are read-only. When the conversion is written in the assignment itself, as above, the converted statement panics with go2cs: store through a read-only view; in a for statement's init or post clause, the converter stops on the file and names it (GO2CS2008). When the view is held in a variable first (p := (*string)(unsafe.Pointer(&b)); *p = s), or passed to a function that stores through it, the store goes into the view, which panics by name on the next access through p. If there is none, the store is lost with no word: len(b) still reads the old length.

  • One bad dependency blocks everything above it. A package that fails to convert, or that the converter refuses, is reported and skipped: the rest of the module still converts, and every project that imports it fails to build. The run ends with exit 1, and its summary names each such package and, for a refused one, each converted package that imports it. -recurse=module converts only your packages.

What "validated" means, and what it doesn't

A package's own Go Test functions were converted, run, and compared with go test verdict for verdict, by full test name. That's a real bar, and narrower than the word sounds:

  • Tests only. Examples, benchmarks and fuzz targets never run. No race detector either.
  • Matched is not passed. A test that skips on both sides counts as a match and measures nothing.
  • Disclosed differences are real differences. Where a Go test asserts something a managed runtime can't satisfy, or doesn't yet, its exact failure is pinned and listed on the package's proof page, linked from Validated Test Packages (Disclosures explains the kinds). Read the list for a package you lean on.
  • Nothing about your dependencies. go2cs -tests -recurse tests the packages of the module you point it at, never its dependencies, so run it on each dependency you lean on.

Platforms and toolchain

  • Go's security fixes arrive with go2cs releases. The converted standard library is a conversion of the Go release in Requirements. A fix Go issues later reaches you when go2cs converts and publishes that patch. A project converted with -recurse=nuget takes it on its next restore, because its GoStdLibVersion is the Go minor with a float, such as 1.26.* (Roadmap).
  • One Go release, one .NET release. Convert with the Go release in Requirements, which the go2cs dotnet tool downloads for you; building the converter from a clone needs Go 1.26.11 or later (the release src/go2cs/go.mod names). go2cs -version should show that one release throughout. Rebuild after every pull. Each GitHub release carries the converter prebuilt for six platforms, with Authenticode-signed Windows executables and a GPG-signed SHA256SUMS (SHA256SUMS.asc, by the key that signs the release tag). Converted projects and the go.* packages target net10.0.
  • Where it runs. The standard library is validated on x64 Windows, on Linux, x64 and Arm64 (glibc, on Microsoft's build of .NET: Ubuntu's own package has an entry in Known issues), and on macOS, Intel and Apple silicon. The roster shows each package's counts on each platform; two Windows-only packages have no Linux or macOS reading. The packages ship win-x64, linux-x64, linux-arm64, osx-x64 and osx-arm64; a build for any other platform is refused or warned about (Known issues).
  • One conversion, one operating system. Go picks build-tagged files at conversion time, so convert once per OS (-platforms linux/amd64), into separate output folders.

Reading and debugging the output

  • You debug the C#. Breakpoints, stepping and compiler errors are on the generated .cs. A Go panic's own traceback does name the Go file and line, read from the program's .pdb files: a publish with -p:DebugType=none keeps the frames and loses every file and line.
  • Some of the letters aren't on your keyboard. ж<T>, Ꮡx, goǃ(...), ᐸꟷ(ch): several look like punctuation and are letters, so an ASCII search finds nothing. Keep the glyph table open.
  • Don't hand-edit converted files, the .csproj included. The next conversion rewrites them, so pass build settings with -p:. For code, fix the Go, keep your own C# in a separate file, or mark a whole file [module: go.GoManualConversion] (how) and merge later Go changes yourself. A renamed Go file leaves its old .cs behind, still compiled.
  • Start with go2cs -recurse=nuget <module> <out>, the one form whose output restores and builds with nothing staged. Go comments are dropped unless you pass -comments.
  • Calling converted Go from your own C#? See Rough edges. The road runs one way: Go source can't call a .NET API.

What you might expect to break, and doesn't

The language itself (generics, closures, struct embedding, range-over-func, typed nil pointers in interfaces, randomized map order), defer/panic/recover, channels and select, reflect (encoding/json and text/template pass their own suites on it, on Windows, Linux and macOS), and net/http with HTTP/2 and crypto/tls over real sockets.

When you hit a seam

  1. Start from a clean Go build: GOTOOLCHAIN=local, then go build ./... for the same OS and tags.
  2. Read the conversion's warnings and its summary line, not the exit code.
  3. A clean build that throws NotImplementedException wants a pure-Go build tag. A C# compile error in converted code is a converter bug until proven otherwise.
  4. A behavior difference in the standard library? Check the package's disclosures on Validated Test Packages.
  5. Check Known issues, then open an issue with the output of go2cs -version, your OS, the error text, and the smallest Go that reproduces it.

If you find a seam that isn't on this page, that's the one I most want to hear about.