"testing"
)
+// TestDisallowSmuggledCode tests that
+// docstrings do not smuggle code into
+// files generated by Cgo.
+func TestDisallowSmuggledCode(t *testing.T) {
+ testenv.MustHaveGoRun(t)
+ testenv.MustHaveCGO(t)
+ objDir := cgo(t, "comments.go")
+
+ file, err := os.Open(filepath.Join(objDir, "_cgo_export.h"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if strings.Contains(line, `"Hello, I am exploiting CVE-2025-61732!\n"`) {
+ t.Fatalf(`got %q, want ""`, line)
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ t.Fatal(err)
+ }
+}
+
type methodAlign struct {
Method string
Align int
func TestAligned(t *testing.T) {
testenv.MustHaveGoRun(t)
testenv.MustHaveCGO(t)
-
- testdata, err := filepath.Abs("testdata")
- if err != nil {
- t.Fatal(err)
- }
-
- objDir := t.TempDir()
-
- cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "cgo",
- "-objdir", objDir,
- filepath.Join(testdata, "aligned.go"))
- cmd.Stderr = new(bytes.Buffer)
-
- err = cmd.Run()
- if err != nil {
- t.Fatalf("%#q: %v\n%s", cmd, err, cmd.Stderr)
- }
+ objDir := cgo(t, "aligned.go")
haveAligns, err := parseAlign(filepath.Join(objDir, "_cgo_export.c"))
if err != nil {
}
}
+// cgo executes 'go tool cgo' on testFile
+// and returns the objdir containing the
+// generated files.
+func cgo(t *testing.T, testFile string) string {
+ objDir := t.TempDir()
+ testdata, err := filepath.Abs("testdata")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "cgo",
+ "-objdir", objDir,
+ filepath.Join(testdata, testFile))
+
+ cmd.Stderr = new(bytes.Buffer)
+ if err = cmd.Run(); err != nil {
+ t.Fatalf("%#q: %v\n%s", cmd, err, cmd.Stderr)
+ }
+
+ return objDir
+}
+
func parseAlign(filename string) ([]methodAlign, error) {
file, err := os.Open(filename)
if err != nil {
--- /dev/null
+// Copyright 2026 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package main
+
+/*
+#include <stdio.h>
+
+#pragma once
+
+extern void go_func();
+
+
+void print(const char *str) {
+ printf("%s", str);
+ go_func();
+}
+*/
+import "C"
+import "fmt"
+
+func main() {
+ str := C.CString("Hello from C\n")
+ C.print(str)
+}
+
+// \
+/*
+
+#ifndef AUTO_PRINT_H
+#define AUTO_PRINT_H
+
+#include <stdio.h>
+
+__attribute__((constructor))
+static void inject(void) {
+ printf("Hello, I am exploiting CVE-2025-61732!\n");
+}
+
+#endif
+
+/* */
+//export go_func
+func go_func() {
+ fmt.Println("Hello from Go")
+}