mkall.go 21 KB

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