mkall.go 21 KB

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