Skip to content

Latest commit

 

History

History
543 lines (510 loc) · 49.2 KB

Limitations.md

File metadata and controls

543 lines (510 loc) · 49.2 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.

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 functions a shared library 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.
  • 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).
  • 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. 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.
  • 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, until cgo callbacks bind functions to code addresses (func words).
  • 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 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).

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

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 to call C on any other. 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. Packing a cgo package against the go.* packages for every platform is still to come (Roadmap). 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. Converting the net resolver with cgo is planned, and is what will change this. A package that imports runtime/cgo or plugin is refused by name: without cgo they are not working builds.

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 function the preamble itself defines, and a #define that is not a constant, both of which need compiled C;
  • //export;
  • a C variable, a C function used as a value, 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 places, all where a program breaks or bends cgo's pointer rules:

  • Go checks a pointer held in a variable against the whole object it points into, and panics when that object also holds a Go pointer or lives in package-level memory. go2cs proceeds, since C only sees the copy. This is the check most cgo calls in the Go toolchain's own cgo packages take.
  • Go accepts a struct member that points at memory pinned with runtime.Pinner, any pointer under GODEBUG=cgocheck=0, and a struct passed by value whose pointer member points into Go memory that holds no pointer. go2cs refuses all three when the call is made.

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.

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.
  • 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. The general fix is planned.
  • 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.