CodeSampleX

Пример

modernc.org/libc v1.72.3: GoBytes

Проверенный пример — golang modernc.org/libc v1.72.3: GoBytes. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:1e6db1c886a6416f02250cd7e532d24dcb031f60460a0d94c1d22c56a918f315

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-11-30

Кейс

HOW
Цель
verify modernc.org/libc.GoBytes in pkg:golang/modernc.org/libc@v1.72.3
Пакеты
Символы
  • modernc.org/libc.GoBytes
Создан
2026-11-30T01:11:16Z

Контракт

  1. libc.GoBytes(ptr, n) accepts a uintptr C pointer and int length and returns a []byte of len == n and cap == n containing the exact raw bytes, preserving embedded NUL (0x00) and high bytes where libc.GoString truncates at NUL
  2. libc.GoBytes returns a zero-copy slice aliasing the underlying C memory (via unsafe.Slice): C-side mutations via libc.Xmemset are immediately visible through the existing slice, so callers must clone (e.g. bytes.Clone) before calling libc.Xfree
  3. libc.GoBytes(0, 0) returns a nil slice with len 0 and cap 0, whereas libc.GoBytes(nonNullPtr, 0) returns a non-nil empty slice with len 0 and cap 0
  4. libc.GoBytes(0, positiveLen) panics on a NULL pointer with non-zero length, and libc.GoBytes(nonNullPtr, -1) panics on negative length

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • gobytes.go
  • spec.json
  • test/contract.go

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify modernc.org/libc.GoBytes in pkg:golang/modernc.org/libc@v1.72.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/modernc.org/libc@v1.72.3
Demonstrate these symbols/APIs:
  - modernc.org/libc.GoBytes

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:4645255aee6995f239fe67edad1ec123b74216b8cd6a5dd7b2d05899f5291048","contract":["libc.GoBytes(ptr, n) accepts a uintptr C pointer and int length and returns a []byte of len == n and cap == n containing the exact raw bytes, preserving embedded NUL (0x00) and high bytes where libc.GoString truncates at NUL","libc.GoBytes returns a zero-copy slice aliasing the underlying C memory (via unsafe.Slice): C-side mutations via libc.Xmemset are immediately visible through the existing slice, so callers must clone (e.g. bytes.Clone) before calling libc.Xfree","libc.GoBytes(0, 0) returns a nil slice with len 0 and cap 0, whereas libc.GoBytes(nonNullPtr, 0) returns a non-nil empty slice with len 0 and cap 0","libc.GoBytes(0, positiveLen) panics on a NULL pointer with non-zero length, and libc.GoBytes(nonNullPtr, -1) panics on negative length"],"goal":"verify modernc.org/libc.GoBytes in pkg:golang/modernc.org/libc@v1.72.3","kind":"HOW","packages":["pkg:golang/modernc.org/libc@v1.72.3"],"schemaVersion":1,"symbols":["modernc.org/libc.GoBytes"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/modernc.org/libc@v1.72.3"],"schemaVersion":1,"subject":"pkg:golang/modernc.org/libc@v1.72.3","symbols":["modernc.org/libc.GoBytes"],"verifierAdapter":"golang@1"}
go.mod
module example.com/libc-gobytes

go 1.25.0

require modernc.org/libc v1.72.3

require (
	github.com/dustin/go-humanize v1.0.1 // indirect
	github.com/google/uuid v1.6.0 // indirect
	github.com/mattn/go-isatty v0.0.20 // indirect
	github.com/ncruces/go-strftime v1.0.0 // indirect
	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
	golang.org/x/sys v0.41.0 // indirect
	modernc.org/mathutil v1.7.1 // indirect
	modernc.org/memory v1.11.0 // indirect
)
go.sum
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
gobytes.go
package gobytes

import (
	"bytes"

	"modernc.org/libc"
)

// CloneFromC returns a Go-owned copy of n bytes starting at C pointer ptr.
// Because modernc.org/libc.GoBytes returns a zero-copy slice aliasing C memory,
// cloning ensures the returned bytes remain valid after libc.Xfree.
func CloneFromC(ptr uintptr, n int) []byte {
	return bytes.Clone(libc.GoBytes(ptr, n))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify modernc.org/libc.GoBytes in pkg:golang/modernc.org/libc@v1.72.3",
  "kind": "HOW",
  "packages": [
    "pkg:golang/modernc.org/libc@v1.72.3"
  ],
  "symbols": [
    "modernc.org/libc.GoBytes"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"

	gobytes "example.com/libc-gobytes"
	"modernc.org/libc"
)

func fail(format string, args ...any) {
	fmt.Fprintf(os.Stderr, "FAIL: "+format+"\n", args...)
	os.Exit(1)
}

func assertPanics(name string, fn func()) {
	panicked := false
	func() {
		defer func() {
			if recover() != nil {
				panicked = true
			}
		}()
		fn()
	}()
	if !panicked {
		fail("%s: expected panic, but call returned normally", name)
	}
}

func main() {
	tls := libc.NewTLS()
	defer tls.Close()

	// 1. Allocate a C buffer and populate binary data containing an embedded NUL byte.
	want := []byte{'a', 'b', 0x00, 'c', 0xff, 'd'}
	ptr := libc.Xmalloc(tls, libc.Tsize_t(len(want)))
	if ptr == 0 {
		fail("libc.Xmalloc returned NULL")
	}

	view := libc.GoBytes(ptr, len(want))
	if len(view) != len(want) || cap(view) != len(want) {
		libc.Xfree(tls, ptr)
		fail("expected len=cap=%d, got len=%d cap=%d", len(want), len(view), cap(view))
	}
	copy(view, want)

	// 2. Verify GoBytes reads exact raw bytes including embedded NULs (unlike GoString).
	reread := libc.GoBytes(ptr, len(want))
	if !bytes.Equal(reread, want) {
		libc.Xfree(tls, ptr)
		fail("GoBytes mismatch: got %x, want %x", reread, want)
	}
	if gotStr := libc.GoString(ptr); gotStr != "ab" {
		libc.Xfree(tls, ptr)
		fail("expected GoString to stop at first NUL (%q), got %q", "ab", gotStr)
	}

	// 3. Verify zero-copy aliasing: C-side mutation via Xmemset updates the existing slice.
	libc.Xmemset(tls, ptr+1, 'Z', 2)
	expectedAliased := []byte{'a', 'Z', 'Z', 'c', 0xff, 'd'}
	if !bytes.Equal(view, expectedAliased) {
		libc.Xfree(tls, ptr)
		fail("expected GoBytes slice to alias C memory: got %x, want %x", view, expectedAliased)
	}

	// 4. Verify safe cloning produces a Go-owned copy that survives C-side mutation and Xfree.
	cloned := gobytes.CloneFromC(ptr, len(expectedAliased))
	libc.Xmemset(tls, ptr, 'Q', libc.Tsize_t(len(expectedAliased)))
	libc.Xfree(tls, ptr)
	if !bytes.Equal(cloned, expectedAliased) {
		fail("expected cloned slice to remain independent after Xmemset and Xfree: got %x, want %x", cloned, expectedAliased)
	}

	// 5. Verify zero-length slice edge cases.
	if s := libc.GoBytes(0, 0); s != nil || len(s) != 0 || cap(s) != 0 {
		fail("expected GoBytes(0, 0) to return nil empty slice, got %#v", s)
	}
	tmp := libc.Xmalloc(tls, 1)
	if tmp == 0 {
		fail("libc.Xmalloc(1) returned NULL")
	}
	defer libc.Xfree(tls, tmp)
	if s := libc.GoBytes(tmp, 0); s == nil || len(s) != 0 || cap(s) != 0 {
		fail("expected GoBytes(nonNull, 0) to return non-nil empty slice, got %#v", s)
	}

	// 6. Verify unsafe.Slice panic invariants for NULL+positive length and negative length.
	assertPanics("GoBytes(0, 1)", func() {
		_ = libc.GoBytes(0, 1)
	})
	assertPanics("GoBytes(nonNull, -1)", func() {
		_ = libc.GoBytes(tmp, -1)
	})
}

Исходный сидер

аноним