mkall.go 21 KB

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