1// Copyright 2017 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// linux/mkall.go - Generates all Linux zsysnum, zsyscall, zerror, and ztype
6// files for all Linux architectures supported by the go compiler. See
7// README.md for more information about the build system.
8
9// To run it you must have a git checkout of the Linux kernel and glibc. Once
10// the appropriate sources are ready, the program is run as:
11//     go run linux/mkall.go <linux_dir> <glibc_dir>
12
13// +build ignore
14
15package main
16
17import (
18	"bufio"
19	"bytes"
20	"debug/elf"
21	"encoding/binary"
22	"errors"
23	"fmt"
24	"io"
25	"io/ioutil"
26	"os"
27	"os/exec"
28	"path/filepath"
29	"runtime"
30	"strings"
31	"unicode"
32)
33
34// These will be paths to the appropriate source directories.
35var LinuxDir string
36var GlibcDir string
37
38const TempDir = "/tmp"
39const IncludeDir = TempDir + "/include" // To hold our C headers
40const BuildDir = TempDir + "/build"     // To hold intermediate build files
41
42const GOOS = "linux"       // Only for Linux targets
43const BuildArch = "amd64"  // Must be built on this architecture
44const MinKernel = "2.6.23" // https://golang.org/doc/install#requirements
45
46type target struct {
47	GoArch     string // Architecture name according to Go
48	LinuxArch  string // Architecture name according to the Linux Kernel
49	GNUArch    string // Architecture name according to GNU tools (https://wiki.debian.org/Multiarch/Tuples)
50	BigEndian  bool   // Default Little Endian
51	SignedChar bool   // Is -fsigned-char needed (default no)
52	Bits       int
53}
54
55// List of all Linux targets supported by the go compiler. Currently, riscv64
56// and sparc64 are not fully supported, but there is enough support already to
57// generate Go type and error definitions.
58var targets = []target{
59	{
60		GoArch:    "386",
61		LinuxArch: "x86",
62		GNUArch:   "i686-linux-gnu", // Note "i686" not "i386"
63		Bits:      32,
64	},
65	{
66		GoArch:    "amd64",
67		LinuxArch: "x86",
68		GNUArch:   "x86_64-linux-gnu",
69		Bits:      64,
70	},
71	{
72		GoArch:     "arm64",
73		LinuxArch:  "arm64",
74		GNUArch:    "aarch64-linux-gnu",
75		SignedChar: true,
76		Bits:       64,
77	},
78	{
79		GoArch:    "arm",
80		LinuxArch: "arm",
81		GNUArch:   "arm-linux-gnueabi",
82		Bits:      32,
83	},
84	{
85		GoArch:    "mips",
86		LinuxArch: "mips",
87		GNUArch:   "mips-linux-gnu",
88		BigEndian: true,
89		Bits:      32,
90	},
91	{
92		GoArch:    "mipsle",
93		LinuxArch: "mips",
94		GNUArch:   "mipsel-linux-gnu",
95		Bits:      32,
96	},
97	{
98		GoArch:    "mips64",
99		LinuxArch: "mips",
100		GNUArch:   "mips64-linux-gnuabi64",
101		BigEndian: true,
102		Bits:      64,
103	},
104	{
105		GoArch:    "mips64le",
106		LinuxArch: "mips",
107		GNUArch:   "mips64el-linux-gnuabi64",
108		Bits:      64,
109	},
110	{
111		GoArch:    "ppc64",
112		LinuxArch: "powerpc",
113		GNUArch:   "powerpc64-linux-gnu",
114		BigEndian: true,
115		Bits:      64,
116	},
117	{
118		GoArch:    "ppc64le",
119		LinuxArch: "powerpc",
120		GNUArch:   "powerpc64le-linux-gnu",
121		Bits:      64,
122	},
123	{
124		GoArch:    "riscv64",
125		LinuxArch: "riscv",
126		GNUArch:   "riscv64-linux-gnu",
127		Bits:      64,
128	},
129	{
130		GoArch:     "s390x",
131		LinuxArch:  "s390",
132		GNUArch:    "s390x-linux-gnu",
133		BigEndian:  true,
134		SignedChar: true,
135		Bits:       64,
136	},
137	{
138		GoArch:    "sparc64",
139		LinuxArch: "sparc",
140		GNUArch:   "sparc64-linux-gnu",
141		BigEndian: true,
142		Bits:      64,
143	},
144}
145
146// ptracePairs is a list of pairs of targets that can, in some cases,
147// run each other's binaries. 'archName' is the combined name of 'a1'
148// and 'a2', which is used in the file name. Generally we use an 'x'
149// suffix in the file name to indicate that the file works for both
150// big-endian and little-endian, here we use 'nn' to indicate that this
151// file is suitable for 32-bit and 64-bit.
152var ptracePairs = []struct{ a1, a2, archName string }{
153	{"386", "amd64", "x86"},
154	{"arm", "arm64", "armnn"},
155	{"mips", "mips64", "mipsnn"},
156	{"mipsle", "mips64le", "mipsnnle"},
157}
158
159func main() {
160	if runtime.GOOS != GOOS || runtime.GOARCH != BuildArch {
161		fmt.Printf("Build system has GOOS_GOARCH = %s_%s, need %s_%s\n",
162			runtime.GOOS, runtime.GOARCH, GOOS, BuildArch)
163		return
164	}
165
166	// Check that we are using the new build system if we should
167	if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
168		fmt.Println("In the new build system, mkall.go should not be called directly.")
169		fmt.Println("See README.md")
170		return
171	}
172
173	// Parse the command line options
174	if len(os.Args) != 3 {
175		fmt.Println("USAGE: go run linux/mkall.go <linux_dir> <glibc_dir>")
176		return
177	}
178	LinuxDir = os.Args[1]
179	GlibcDir = os.Args[2]
180
181	for _, t := range targets {
182		fmt.Printf("----- GENERATING: %s -----\n", t.GoArch)
183		if err := t.generateFiles(); err != nil {
184			fmt.Printf("%v\n***** FAILURE:    %s *****\n\n", err, t.GoArch)
185		} else {
186			fmt.Printf("----- SUCCESS:    %s -----\n\n", t.GoArch)
187		}
188	}
189
190	fmt.Printf("----- GENERATING ptrace pairs -----\n")
191	ok := true
192	for _, p := range ptracePairs {
193		if err := generatePtracePair(p.a1, p.a2, p.archName); err != nil {
194			fmt.Printf("%v\n***** FAILURE: %s/%s *****\n\n", err, p.a1, p.a2)
195			ok = false
196		}
197	}
198	// generate functions PtraceGetRegSetArm64 and PtraceSetRegSetArm64.
199	if err := generatePtraceRegSet("arm64"); err != nil {
200		fmt.Printf("%v\n***** FAILURE: generatePtraceRegSet(%q) *****\n\n", err, "arm64")
201		ok = false
202	}
203	if ok {
204		fmt.Printf("----- SUCCESS ptrace pairs    -----\n\n")
205	}
206}
207
208// Makes an exec.Cmd with Stderr attached to os.Stderr
209func makeCommand(name string, args ...string) *exec.Cmd {
210	cmd := exec.Command(name, args...)
211	cmd.Stderr = os.Stderr
212	return cmd
213}
214
215// Set GOARCH for target and build environments.
216func (t *target) setTargetBuildArch(cmd *exec.Cmd) {
217	// Set GOARCH_TARGET so command knows what GOARCH is..
218	cmd.Env = append(os.Environ(), "GOARCH_TARGET="+t.GoArch)
219	// Set GOARCH to host arch for command, so it can run natively.
220	for i, s := range cmd.Env {
221		if strings.HasPrefix(s, "GOARCH=") {
222			cmd.Env[i] = "GOARCH=" + BuildArch
223		}
224	}
225}
226
227// Runs the command, pipes output to a formatter, pipes that to an output file.
228func (t *target) commandFormatOutput(formatter string, outputFile string,
229	name string, args ...string) (err error) {
230	mainCmd := makeCommand(name, args...)
231	if name == "mksyscall" {
232		args = append([]string{"run", "mksyscall.go"}, args...)
233		mainCmd = makeCommand("go", args...)
234		t.setTargetBuildArch(mainCmd)
235	} else if name == "mksysnum" {
236		args = append([]string{"run", "linux/mksysnum.go"}, args...)
237		mainCmd = makeCommand("go", args...)
238		t.setTargetBuildArch(mainCmd)
239	}
240
241	fmtCmd := makeCommand(formatter)
242	if formatter == "mkpost" {
243		fmtCmd = makeCommand("go", "run", "mkpost.go")
244		t.setTargetBuildArch(fmtCmd)
245	}
246
247	// mainCmd | fmtCmd > outputFile
248	if fmtCmd.Stdin, err = mainCmd.StdoutPipe(); err != nil {
249		return
250	}
251	if fmtCmd.Stdout, err = os.Create(outputFile); err != nil {
252		return
253	}
254
255	// Make sure the formatter eventually closes
256	if err = fmtCmd.Start(); err != nil {
257		return
258	}
259	defer func() {
260		fmtErr := fmtCmd.Wait()
261		if err == nil {
262			err = fmtErr
263		}
264	}()
265
266	return mainCmd.Run()
267}
268
269// Generates all the files for a Linux target
270func (t *target) generateFiles() error {
271	// Setup environment variables
272	os.Setenv("GOOS", GOOS)
273	os.Setenv("GOARCH", t.GoArch)
274
275	// Get appropriate compiler and emulator (unless on x86)
276	if t.LinuxArch != "x86" {
277		// Check/Setup cross compiler
278		compiler := t.GNUArch + "-gcc"
279		if _, err := exec.LookPath(compiler); err != nil {
280			return err
281		}
282		os.Setenv("CC", compiler)
283
284		// Check/Setup emulator (usually first component of GNUArch)
285		qemuArchName := t.GNUArch[:strings.Index(t.GNUArch, "-")]
286		if t.LinuxArch == "powerpc" {
287			qemuArchName = t.GoArch
288		}
289		// Fake uname for QEMU to allow running on Host kernel version < 4.15
290		if t.LinuxArch == "riscv" {
291			os.Setenv("QEMU_UNAME", "4.15")
292		}
293		os.Setenv("GORUN", "qemu-"+qemuArchName)
294	} else {
295		os.Setenv("CC", "gcc")
296	}
297
298	// Make the include directory and fill it with headers
299	if err := os.MkdirAll(IncludeDir, os.ModePerm); err != nil {
300		return err
301	}
302	defer os.RemoveAll(IncludeDir)
303	if err := t.makeHeaders(); err != nil {
304		return fmt.Errorf("could not make header files: %v", err)
305	}
306	fmt.Println("header files generated")
307
308	// Make each of the four files
309	if err := t.makeZSysnumFile(); err != nil {
310		return fmt.Errorf("could not make zsysnum file: %v", err)
311	}
312	fmt.Println("zsysnum file generated")
313
314	if err := t.makeZSyscallFile(); err != nil {
315		return fmt.Errorf("could not make zsyscall file: %v", err)
316	}
317	fmt.Println("zsyscall file generated")
318
319	if err := t.makeZTypesFile(); err != nil {
320		return fmt.Errorf("could not make ztypes file: %v", err)
321	}
322	fmt.Println("ztypes file generated")
323
324	if err := t.makeZErrorsFile(); err != nil {
325		return fmt.Errorf("could not make zerrors file: %v", err)
326	}
327	fmt.Println("zerrors file generated")
328
329	return nil
330}
331
332// Create the Linux, glibc and ABI (C compiler convention) headers in the include directory.
333func (t *target) makeHeaders() error {
334	// Make the Linux headers we need for this architecture
335	linuxMake := makeCommand("make", "headers_install", "ARCH="+t.LinuxArch, "INSTALL_HDR_PATH="+TempDir)
336	linuxMake.Dir = LinuxDir
337	if err := linuxMake.Run(); err != nil {
338		return err
339	}
340
341	// A Temporary build directory for glibc
342	if err := os.MkdirAll(BuildDir, os.ModePerm); err != nil {
343		return err
344	}
345	defer os.RemoveAll(BuildDir)
346
347	// Make the glibc headers we need for this architecture
348	confScript := filepath.Join(GlibcDir, "configure")
349	glibcConf := makeCommand(confScript, "--prefix="+TempDir, "--host="+t.GNUArch, "--enable-kernel="+MinKernel)
350	glibcConf.Dir = BuildDir
351	if err := glibcConf.Run(); err != nil {
352		return err
353	}
354	glibcMake := makeCommand("make", "install-headers")
355	glibcMake.Dir = BuildDir
356	if err := glibcMake.Run(); err != nil {
357		return err
358	}
359	// We only need an empty stubs file
360	stubsFile := filepath.Join(IncludeDir, "gnu/stubs.h")
361	if file, err := os.Create(stubsFile); err != nil {
362		return err
363	} else {
364		file.Close()
365	}
366
367	// ABI headers will specify C compiler behavior for the target platform.
368	return t.makeABIHeaders()
369}
370
371// makeABIHeaders generates C header files based on the platform's calling convention.
372// While many platforms have formal Application Binary Interfaces, in practice, whatever the
373// dominant C compilers generate is the de-facto calling convention.
374//
375// We generate C headers instead of a Go file, so as to enable references to the ABI from Cgo.
376func (t *target) makeABIHeaders() (err error) {
377	abiDir := filepath.Join(IncludeDir, "abi")
378	if err = os.Mkdir(abiDir, os.ModePerm); err != nil {
379		return err
380	}
381
382	cc := os.Getenv("CC")
383	if cc == "" {
384		return errors.New("CC (compiler) env var not set")
385	}
386
387	// Build a sacrificial ELF file, to mine for C compiler behavior.
388	binPath := filepath.Join(TempDir, "tmp_abi.o")
389	bin, err := t.buildELF(cc, cCode, binPath)
390	if err != nil {
391		return fmt.Errorf("cannot build ELF to analyze: %v", err)
392	}
393	defer bin.Close()
394	defer os.Remove(binPath)
395
396	// Right now, we put everything in abi.h, but we may change this later.
397	abiFile, err := os.Create(filepath.Join(abiDir, "abi.h"))
398	if err != nil {
399		return err
400	}
401	defer func() {
402		if cerr := abiFile.Close(); cerr != nil && err == nil {
403			err = cerr
404		}
405	}()
406
407	if err = t.writeBitFieldMasks(bin, abiFile); err != nil {
408		return fmt.Errorf("cannot write bitfield masks: %v", err)
409	}
410
411	return nil
412}
413
414func (t *target) buildELF(cc, src, path string) (*elf.File, error) {
415	// Compile the cCode source using the set compiler - we will need its .data section.
416	// Do not link the binary, so that we can find .data section offsets from the symbol values.
417	ccCmd := makeCommand(cc, "-o", path, "-gdwarf", "-x", "c", "-c", "-")
418	ccCmd.Stdin = strings.NewReader(src)
419	ccCmd.Stdout = os.Stdout
420	if err := ccCmd.Run(); err != nil {
421		return nil, fmt.Errorf("compiler error: %v", err)
422	}
423
424	bin, err := elf.Open(path)
425	if err != nil {
426		return nil, fmt.Errorf("cannot read ELF file %s: %v", path, err)
427	}
428
429	return bin, nil
430}
431
432func (t *target) writeBitFieldMasks(bin *elf.File, out io.Writer) error {
433	symbols, err := bin.Symbols()
434	if err != nil {
435		return fmt.Errorf("getting ELF symbols: %v", err)
436	}
437	var masksSym *elf.Symbol
438
439	for _, sym := range symbols {
440		if sym.Name == "masks" {
441			masksSym = &sym
442		}
443	}
444
445	if masksSym == nil {
446		return errors.New("could not find the 'masks' symbol in ELF symtab")
447	}
448
449	dataSection := bin.Section(".data")
450	if dataSection == nil {
451		return errors.New("ELF file has no .data section")
452	}
453
454	data, err := dataSection.Data()
455	if err != nil {
456		return fmt.Errorf("could not read .data section: %v\n", err)
457	}
458
459	var bo binary.ByteOrder
460	if t.BigEndian {
461		bo = binary.BigEndian
462	} else {
463		bo = binary.LittleEndian
464	}
465
466	// 64 bit masks of type uint64 are stored in the data section starting at masks.Value.
467	// Here we are running on AMD64, but these values may be big endian or little endian,
468	// depending on target architecture.
469	for i := uint64(0); i < 64; i++ {
470		off := masksSym.Value + i*8
471		// Define each mask in native by order, so as to match target endian.
472		fmt.Fprintf(out, "#define BITFIELD_MASK_%d %dULL\n", i, bo.Uint64(data[off:off+8]))
473	}
474
475	return nil
476}
477
478// makes the zsysnum_linux_$GOARCH.go file
479func (t *target) makeZSysnumFile() error {
480	zsysnumFile := fmt.Sprintf("zsysnum_linux_%s.go", t.GoArch)
481	unistdFile := filepath.Join(IncludeDir, "asm/unistd.h")
482
483	args := append(t.cFlags(), unistdFile)
484	return t.commandFormatOutput("gofmt", zsysnumFile, "mksysnum", args...)
485}
486
487// makes the zsyscall_linux_$GOARCH.go file
488func (t *target) makeZSyscallFile() error {
489	zsyscallFile := fmt.Sprintf("zsyscall_linux_%s.go", t.GoArch)
490	// Find the correct architecture syscall file (might end with x.go)
491	archSyscallFile := fmt.Sprintf("syscall_linux_%s.go", t.GoArch)
492	if _, err := os.Stat(archSyscallFile); os.IsNotExist(err) {
493		shortArch := strings.TrimSuffix(t.GoArch, "le")
494		archSyscallFile = fmt.Sprintf("syscall_linux_%sx.go", shortArch)
495	}
496
497	args := append(t.mksyscallFlags(), "-tags", "linux,"+t.GoArch,
498		"syscall_linux.go", archSyscallFile)
499	return t.commandFormatOutput("gofmt", zsyscallFile, "mksyscall", args...)
500}
501
502// makes the zerrors_linux_$GOARCH.go file
503func (t *target) makeZErrorsFile() error {
504	zerrorsFile := fmt.Sprintf("zerrors_linux_%s.go", t.GoArch)
505
506	return t.commandFormatOutput("gofmt", zerrorsFile, "./mkerrors.sh", t.cFlags()...)
507}
508
509// makes the ztypes_linux_$GOARCH.go file
510func (t *target) makeZTypesFile() error {
511	ztypesFile := fmt.Sprintf("ztypes_linux_%s.go", t.GoArch)
512
513	args := []string{"tool", "cgo", "-godefs", "--"}
514	args = append(args, t.cFlags()...)
515	args = append(args, "linux/types.go")
516	return t.commandFormatOutput("mkpost", ztypesFile, "go", args...)
517}
518
519// Flags that should be given to gcc and cgo for this target
520func (t *target) cFlags() []string {
521	// Compile statically to avoid cross-architecture dynamic linking.
522	flags := []string{"-Wall", "-Werror", "-static", "-I" + IncludeDir}
523
524	// Architecture-specific flags
525	if t.SignedChar {
526		flags = append(flags, "-fsigned-char")
527	}
528	if t.LinuxArch == "x86" {
529		flags = append(flags, fmt.Sprintf("-m%d", t.Bits))
530	}
531
532	return flags
533}
534
535// Flags that should be given to mksyscall for this target
536func (t *target) mksyscallFlags() (flags []string) {
537	if t.Bits == 32 {
538		if t.BigEndian {
539			flags = append(flags, "-b32")
540		} else {
541			flags = append(flags, "-l32")
542		}
543	}
544
545	// This flag means a 64-bit value should use (even, odd)-pair.
546	if t.GoArch == "arm" || (t.LinuxArch == "mips" && t.Bits == 32) {
547		flags = append(flags, "-arm")
548	}
549	return
550}
551
552// generatePtracePair takes a pair of GOARCH values that can run each
553// other's binaries, such as 386 and amd64. It extracts the PtraceRegs
554// type for each one. It writes a new file defining the types
555// PtraceRegsArch1 and PtraceRegsArch2 and the corresponding functions
556// Ptrace{Get,Set}Regs{arch1,arch2}. This permits debugging the other
557// binary on a native system. 'archName' is the combined name of 'arch1'
558// and 'arch2', which is used in the file name.
559func generatePtracePair(arch1, arch2, archName string) error {
560	def1, err := ptraceDef(arch1)
561	if err != nil {
562		return err
563	}
564	def2, err := ptraceDef(arch2)
565	if err != nil {
566		return err
567	}
568	f, err := os.Create(fmt.Sprintf("zptrace_%s_linux.go", archName))
569	if err != nil {
570		return err
571	}
572	buf := bufio.NewWriter(f)
573	fmt.Fprintf(buf, "// Code generated by linux/mkall.go generatePtracePair(%q, %q). DO NOT EDIT.\n", arch1, arch2)
574	fmt.Fprintf(buf, "\n")
575	fmt.Fprintf(buf, "// +build linux\n")
576	fmt.Fprintf(buf, "// +build %s %s\n", arch1, arch2)
577	fmt.Fprintf(buf, "\n")
578	fmt.Fprintf(buf, "package unix\n")
579	fmt.Fprintf(buf, "\n")
580	fmt.Fprintf(buf, "%s\n", `import "unsafe"`)
581	fmt.Fprintf(buf, "\n")
582	writeOnePtrace(buf, arch1, def1)
583	fmt.Fprintf(buf, "\n")
584	writeOnePtrace(buf, arch2, def2)
585	if err := buf.Flush(); err != nil {
586		return err
587	}
588	if err := f.Close(); err != nil {
589		return err
590	}
591	return nil
592}
593
594// generatePtraceRegSet takes a GOARCH value to generate a file zptrace_linux_{arch}.go
595// containing functions PtraceGetRegSet{arch} and PtraceSetRegSet{arch}.
596func generatePtraceRegSet(arch string) error {
597	f, err := os.Create(fmt.Sprintf("zptrace_linux_%s.go", arch))
598	if err != nil {
599		return err
600	}
601	buf := bufio.NewWriter(f)
602	fmt.Fprintf(buf, "// Code generated by linux/mkall.go generatePtraceRegSet(%q). DO NOT EDIT.\n", arch)
603	fmt.Fprintf(buf, "\n")
604	fmt.Fprintf(buf, "package unix\n")
605	fmt.Fprintf(buf, "\n")
606	fmt.Fprintf(buf, "%s\n", `import "unsafe"`)
607	fmt.Fprintf(buf, "\n")
608	uarch := string(unicode.ToUpper(rune(arch[0]))) + arch[1:]
609	fmt.Fprintf(buf, "// PtraceGetRegSet%s fetches the registers used by %s binaries.\n", uarch, arch)
610	fmt.Fprintf(buf, "func PtraceGetRegSet%s(pid, addr int, regsout *PtraceRegs%s) error {\n", uarch, uarch)
611	fmt.Fprintf(buf, "\tiovec := Iovec{(*byte)(unsafe.Pointer(regsout)), uint64(unsafe.Sizeof(*regsout))}\n")
612	fmt.Fprintf(buf, "\treturn ptrace(PTRACE_GETREGSET, pid, uintptr(addr), uintptr(unsafe.Pointer(&iovec)))\n")
613	fmt.Fprintf(buf, "}\n")
614	fmt.Fprintf(buf, "\n")
615	fmt.Fprintf(buf, "// PtraceSetRegSet%s sets the registers used by %s binaries.\n", uarch, arch)
616	fmt.Fprintf(buf, "func PtraceSetRegSet%s(pid, addr int, regs *PtraceRegs%s) error {\n", uarch, uarch)
617	fmt.Fprintf(buf, "\tiovec := Iovec{(*byte)(unsafe.Pointer(regs)), uint64(unsafe.Sizeof(*regs))}\n")
618	fmt.Fprintf(buf, "\treturn ptrace(PTRACE_SETREGSET, pid, uintptr(addr), uintptr(unsafe.Pointer(&iovec)))\n")
619	fmt.Fprintf(buf, "}\n")
620	if err := buf.Flush(); err != nil {
621		return err
622	}
623	if err := f.Close(); err != nil {
624		return err
625	}
626	return nil
627}
628
629// ptraceDef returns the definition of PtraceRegs for arch.
630func ptraceDef(arch string) (string, error) {
631	filename := fmt.Sprintf("ztypes_linux_%s.go", arch)
632	data, err := ioutil.ReadFile(filename)
633	if err != nil {
634		return "", fmt.Errorf("reading %s: %v", filename, err)
635	}
636	start := bytes.Index(data, []byte("type PtraceRegs struct"))
637	if start < 0 {
638		return "", fmt.Errorf("%s: no definition of PtraceRegs", filename)
639	}
640	data = data[start:]
641	end := bytes.Index(data, []byte("\n}\n"))
642	if end < 0 {
643		return "", fmt.Errorf("%s: can't find end of PtraceRegs definition", filename)
644	}
645	return string(data[:end+2]), nil
646}
647
648// writeOnePtrace writes out the ptrace definitions for arch.
649func writeOnePtrace(w io.Writer, arch, def string) {
650	uarch := string(unicode.ToUpper(rune(arch[0]))) + arch[1:]
651	fmt.Fprintf(w, "// PtraceRegs%s is the registers used by %s binaries.\n", uarch, arch)
652	fmt.Fprintf(w, "%s\n", strings.Replace(def, "PtraceRegs", "PtraceRegs"+uarch, 1))
653	fmt.Fprintf(w, "\n")
654	fmt.Fprintf(w, "// PtraceGetRegs%s fetches the registers used by %s binaries.\n", uarch, arch)
655	fmt.Fprintf(w, "func PtraceGetRegs%s(pid int, regsout *PtraceRegs%s) error {\n", uarch, uarch)
656	fmt.Fprintf(w, "\treturn ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))\n")
657	fmt.Fprintf(w, "}\n")
658	fmt.Fprintf(w, "\n")
659	fmt.Fprintf(w, "// PtraceSetRegs%s sets the registers used by %s binaries.\n", uarch, arch)
660	fmt.Fprintf(w, "func PtraceSetRegs%s(pid int, regs *PtraceRegs%s) error {\n", uarch, uarch)
661	fmt.Fprintf(w, "\treturn ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))\n")
662	fmt.Fprintf(w, "}\n")
663}
664
665// cCode is compiled for the target architecture, and the resulting data section is carved for
666// the statically initialized bit masks.
667const cCode = `
668// Bit fields are used in some system calls and other ABIs, but their memory layout is
669// implementation-defined [1]. Even with formal ABIs, bit fields are a source of subtle bugs [2].
670// Here we generate the offsets for all 64 bits in an uint64.
671// 1: http://en.cppreference.com/w/c/language/bit_field
672// 2: https://lwn.net/Articles/478657/
673
674#include <stdint.h>
675
676struct bitfield {
677	union {
678		uint64_t val;
679		struct {
680			uint64_t u64_bit_0 : 1;
681			uint64_t u64_bit_1 : 1;
682			uint64_t u64_bit_2 : 1;
683			uint64_t u64_bit_3 : 1;
684			uint64_t u64_bit_4 : 1;
685			uint64_t u64_bit_5 : 1;
686			uint64_t u64_bit_6 : 1;
687			uint64_t u64_bit_7 : 1;
688			uint64_t u64_bit_8 : 1;
689			uint64_t u64_bit_9 : 1;
690			uint64_t u64_bit_10 : 1;
691			uint64_t u64_bit_11 : 1;
692			uint64_t u64_bit_12 : 1;
693			uint64_t u64_bit_13 : 1;
694			uint64_t u64_bit_14 : 1;
695			uint64_t u64_bit_15 : 1;
696			uint64_t u64_bit_16 : 1;
697			uint64_t u64_bit_17 : 1;
698			uint64_t u64_bit_18 : 1;
699			uint64_t u64_bit_19 : 1;
700			uint64_t u64_bit_20 : 1;
701			uint64_t u64_bit_21 : 1;
702			uint64_t u64_bit_22 : 1;
703			uint64_t u64_bit_23 : 1;
704			uint64_t u64_bit_24 : 1;
705			uint64_t u64_bit_25 : 1;
706			uint64_t u64_bit_26 : 1;
707			uint64_t u64_bit_27 : 1;
708			uint64_t u64_bit_28 : 1;
709			uint64_t u64_bit_29 : 1;
710			uint64_t u64_bit_30 : 1;
711			uint64_t u64_bit_31 : 1;
712			uint64_t u64_bit_32 : 1;
713			uint64_t u64_bit_33 : 1;
714			uint64_t u64_bit_34 : 1;
715			uint64_t u64_bit_35 : 1;
716			uint64_t u64_bit_36 : 1;
717			uint64_t u64_bit_37 : 1;
718			uint64_t u64_bit_38 : 1;
719			uint64_t u64_bit_39 : 1;
720			uint64_t u64_bit_40 : 1;
721			uint64_t u64_bit_41 : 1;
722			uint64_t u64_bit_42 : 1;
723			uint64_t u64_bit_43 : 1;
724			uint64_t u64_bit_44 : 1;
725			uint64_t u64_bit_45 : 1;
726			uint64_t u64_bit_46 : 1;
727			uint64_t u64_bit_47 : 1;
728			uint64_t u64_bit_48 : 1;
729			uint64_t u64_bit_49 : 1;
730			uint64_t u64_bit_50 : 1;
731			uint64_t u64_bit_51 : 1;
732			uint64_t u64_bit_52 : 1;
733			uint64_t u64_bit_53 : 1;
734			uint64_t u64_bit_54 : 1;
735			uint64_t u64_bit_55 : 1;
736			uint64_t u64_bit_56 : 1;
737			uint64_t u64_bit_57 : 1;
738			uint64_t u64_bit_58 : 1;
739			uint64_t u64_bit_59 : 1;
740			uint64_t u64_bit_60 : 1;
741			uint64_t u64_bit_61 : 1;
742			uint64_t u64_bit_62 : 1;
743			uint64_t u64_bit_63 : 1;
744		};
745	};
746};
747
748struct bitfield masks[] = {
749	{.u64_bit_0 = 1},
750	{.u64_bit_1 = 1},
751	{.u64_bit_2 = 1},
752	{.u64_bit_3 = 1},
753	{.u64_bit_4 = 1},
754	{.u64_bit_5 = 1},
755	{.u64_bit_6 = 1},
756	{.u64_bit_7 = 1},
757	{.u64_bit_8 = 1},
758	{.u64_bit_9 = 1},
759	{.u64_bit_10 = 1},
760	{.u64_bit_11 = 1},
761	{.u64_bit_12 = 1},
762	{.u64_bit_13 = 1},
763	{.u64_bit_14 = 1},
764	{.u64_bit_15 = 1},
765	{.u64_bit_16 = 1},
766	{.u64_bit_17 = 1},
767	{.u64_bit_18 = 1},
768	{.u64_bit_19 = 1},
769	{.u64_bit_20 = 1},
770	{.u64_bit_21 = 1},
771	{.u64_bit_22 = 1},
772	{.u64_bit_23 = 1},
773	{.u64_bit_24 = 1},
774	{.u64_bit_25 = 1},
775	{.u64_bit_26 = 1},
776	{.u64_bit_27 = 1},
777	{.u64_bit_28 = 1},
778	{.u64_bit_29 = 1},
779	{.u64_bit_30 = 1},
780	{.u64_bit_31 = 1},
781	{.u64_bit_32 = 1},
782	{.u64_bit_33 = 1},
783	{.u64_bit_34 = 1},
784	{.u64_bit_35 = 1},
785	{.u64_bit_36 = 1},
786	{.u64_bit_37 = 1},
787	{.u64_bit_38 = 1},
788	{.u64_bit_39 = 1},
789	{.u64_bit_40 = 1},
790	{.u64_bit_41 = 1},
791	{.u64_bit_42 = 1},
792	{.u64_bit_43 = 1},
793	{.u64_bit_44 = 1},
794	{.u64_bit_45 = 1},
795	{.u64_bit_46 = 1},
796	{.u64_bit_47 = 1},
797	{.u64_bit_48 = 1},
798	{.u64_bit_49 = 1},
799	{.u64_bit_50 = 1},
800	{.u64_bit_51 = 1},
801	{.u64_bit_52 = 1},
802	{.u64_bit_53 = 1},
803	{.u64_bit_54 = 1},
804	{.u64_bit_55 = 1},
805	{.u64_bit_56 = 1},
806	{.u64_bit_57 = 1},
807	{.u64_bit_58 = 1},
808	{.u64_bit_59 = 1},
809	{.u64_bit_60 = 1},
810	{.u64_bit_61 = 1},
811	{.u64_bit_62 = 1},
812	{.u64_bit_63 = 1}
813};
814
815int main(int argc, char **argv) {
816	struct bitfield *mask_ptr = &masks[0];
817	return mask_ptr->val;
818}
819
820`
821