Wood Chen

40 Hall of Shame Comments in Go’s Source: The Story of Sonic and linkname

Published
Views
5
Comments
0
Words
1.7k

This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文

This article was first published on the SunAI Forum. Come join the discussion.

A couple of days ago, I came across an article about how ByteDance's Sonic ended up in Go's "hall of shame". I thought it was interesting, so I dug into the Go source and the relevant issues. It turned out there was a lot more to the story than Sonic simply being called out, so I decided to piece it together from primary sources.

First, let's count: how often does Sonic appear in the Go source?

I pulled down the src directory from Go 1.24.1 and grepped for github.com/bytedance/sonic:

grep -rh "bytedance/sonic" go/src | wc -l
# 40

40 matches across 22 files. Most are in runtime: memmove, memequal, memclrNoHeapPointers, gcWriteBarrier2, various map fast paths, lastmoduledatap, and so on. Two more are in encoding/json itself: typeFields and isValidNumber. In other words, Sonic bills itself as a replacement for the standard library's JSON package, but borrows some of that very package's internal functions.

The comments all follow the same pattern. Here's memequal in runtime/stubs.go:

// memequal should be an internal detail,
// but widely used packages access it using linkname.
// Notable members of the hall of shame include:
//   - github.com/bytedance/sonic
//
// Do not remove or change the type signature.
// See go.dev/issue/67401.
//
//go:linkname memequal
//go:noescape
func memequal(a, b unsafe.Pointer, size uintptr) bool

"Hall of shame" is a bit tongue-in-cheek. The line that really matters is the one below it: don't remove the function or change its signature. It's a private function, but because outside packages use it, the Go team can no longer change it freely.

Sonic isn't the only name on the list. The memmove comment also lists wazero, purego, gvisor, and ugorji/go, and memclrNoHeapPointers lists ristretto. But with 40 mentions on its own, Sonic does stand out.

How linkname bypasses visibility rules

In Go, identifiers that start with a lowercase letter aren't exported, so other packages can't call them the usual way. //go:linkname is a compiler and linker directive that lets you bind a locally declared function directly to a symbol in another package:

package mypkg

import "unsafe"

//go:linkname fastEqual runtime.memequal
func fastEqual(a, b unsafe.Pointer, size uintptr) bool

There's no function body. The linker resolves it directly to runtime.memequal. This happens at link time, has nothing to do with reflection, and adds no runtime overhead, which is why performance-focused libraries like it.

In issue #67401, Russ Cox breaks linkname usage into three categories that make the distinction easy to follow:

  • Push: Package A renames one of its own symbols for package B to use. A knows about it.
  • Pull: A doesn't mark the symbol at all, and B uses linkname to grab it. A doesn't know about it. If A renames the symbol, B breaks, and A might not even know B exists.
  • Handshake: Both sides write a linkname directive, and the names have to match for linking to succeed. Both sides agree.

Sonic's use falls into the Pull category. The Go team's goal is for all such uses to become Handshakes.

Go 1.23: locking down linkname

#67401 was opened in May 2024 with a straightforward title: "lock down future uses of linkname". The example that prompted it was goccy/go-json. The library had copied much of the runtime's internal type API, so a seemingly unrelated runtime change (CL 583756) broke it. Kubernetes also depended on it.

Russ Cox's point in the issue was roughly this: internal means internal. If a program depends on internal details, we can't promise it'll keep working. But we also care about compatibility and don't want to break people's programs. The only way out is to prevent new dependencies from forming in the first place.

The plan had four steps:

  1. Add -checklinkname=1 to the linker so that linkname references to standard library symbols require a Handshake.
  2. Scan the open-source ecosystem for packages that Pull standard library symbols, then add //go:linkname markers to those symbols to keep existing users working. That's where the 40 "hall of shame" comments above came from.
  3. Make -checklinkname=1 the default in Go 1.23. If something breaks, -ldflags=-checklinkname=0 provides a temporary workaround.
  4. Add any missed symbols as people report them.

The result is that existing dependencies keep working, but new ones can't be added. Linkname won't be able to reach new internals such as the coroutine and weak pointer implementations added in 1.23.

I think this was the right call. An outright ban would break half the ecosystem, while doing nothing would leave the runtime stuck supporting other packages' dependencies forever. Record what's already in use, freeze the list, and leave an escape hatch. It's a practical compromise.

Go 1.24.0: the symbols that slipped through

The problem was that the scan in step 2 missed a few things.

lastmoduledatap, moduledataverify1, and morestack_noctxt originally got linkname markers because cloudwego/frugal, another JIT-based serialization library, used them. In September 2024, frugal stopped using them, so CL 609918 removed the markers under the title "remove cloudwego/frugal unused linkname". Only frugal was on the list, so the removal looked reasonable.

But around Go 1.23, Sonic had moved this code into a submodule, github.com/bytedance/sonic/loader. The loader used those same symbols but had never made it onto the list. When Go 1.24.0 shipped in February 2025, projects using Sonic hit a linker error as soon as they upgraded:

link: github.com/bytedance/sonic/loader: invalid reference to runtime.lastmoduledatap

On February 12, 2025, a Sonic maintainer opened issue #71672 asking for the linkname markers to be restored. Ian Lance Taylor's first reaction was to ask why a package imported by only 3 packages warranted special treatment. The Sonic maintainer explained that the loader was only meant to be imported by Sonic, which itself had more than 10,000 downstream repositories. The count didn't include indirect dependencies.

I think that exchange gets to the heart of what happened. Going by Ian's reply, the Go team looked at direct import counts when judging what was worth preserving. A submodule like loader, tucked behind the main package and directly imported by only a handful of packages, slipped through.

Things moved quickly from there: Michael Pratt pointed out that the same CL had removed two other symbols Sonic needed, so those were restored too. Ian requested a backport to the 1.24 branch (#71705), and on February 18, the cherry-picked CL 650375 landed under the title "runtime: add some linknames back for github.com/bytedance/sonic". The fix shipped with Go 1.24.1.

If you look at runtime/symtab.go now, the comment above lastmoduledatap points to #67401 and has an extra line: See go.dev/issues/71672.

Sonic's README still carries a warning: Go 1.24.0 isn't supported. Use a newer version or build with -ldflags="-checklinkname=0".

Why Sonic needs to touch these internals

The list gives you a pretty good idea. memmove and memequal let Sonic use the runtime's optimized memory copying and comparison routines. The map functions let it read and write maps directly without going through reflection. That's mostly borrowing tools: public APIs could do the same jobs, just a little more slowly.

gcWriteBarrier2, lastmoduledatap, and moduledataverify1 are a different story. At the heart of Sonic is a JIT: the first time it encounters a particular struct type at runtime, it generates machine code specifically to encode and decode that type, then calls that code directly from then on.

The catch is that Go has a concurrent GC. If the generated machine code writes a pointer to the heap, it has to invoke the write barrier itself. Otherwise, the GC might miss a live object. The runtime also needs to know about this code: stack unwinding, stack growth, and GC stack scanning all need to know the size of each function’s stack frame and which slots contain pointers. The compiler normally generates this metadata, which is stored in the moduledata linked list. Sonic’s loader builds its own moduledata by hand and appends it to the list at the tail pointed to by lastmoduledatap.

Put simply, Sonic implements a small dynamic linker inside the Go process. It’s an impressive bit of engineering, but the trade-off is that it depends not on Go’s API, but on the internal data structures of a particular Go version.

What this means for application developers

I don’t see this as a story about “Sonic being poorly written.” At ByteDance’s scale, those CPU savings translate into real money, and the technique itself is worth studying. But if you’re thinking about using Sonic in your own project, here are a few things to consider:

First, make sure JSON is actually the bottleneck. Use pprof to see how much CPU encoding/json takes. If a request takes 100ms and JSON accounts for 5ms, even a 5x speedup from Sonic only saves 4ms. You’re probably better off looking at that slow SQL query.

Check whether you’re already using it indirectly. Many frameworks (including some builds of Gin and frameworks in the CloudWeGo ecosystem) pull in Sonic. To check:

go list -deps ./... | grep bytedance/sonic

Be extra careful when upgrading Go. Libraries that rely heavily on linkname are a source of risk with every major Go release. The 1.24.0 breakage was fixed, but the next fix might not come as quickly.

Test for differences in behavior. By default, Sonic doesn’t sort map keys or escape HTML, unlike the standard library. If you want behavior closer to the standard library’s, use sonic.ConfigStd, but still compare the output on real data before deploying.

One last thought: I don’t think either the Go team or the Sonic team did anything wrong here. One wants to keep the runtime refactorable; the other wants to squeeze out every bit of performance. Those 40 comments are something of a truce, written into the source. Anyone who wants to change these functions will have to check the list first.

References

I got the idea for this post from “The Go Team Calls Out ByteDance’s Sonic”, an article from the CppGuide WeChat account, and wrote it using the primary sources above.


Have thoughts on linkname, Sonic, or the Go runtime? Join the discussion on the forum.

Related posts

Comments 0