You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

482 lines
14 KiB

  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 11 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. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "runtime"
  22. "strings"
  23. "unicode"
  24. )
  25. // These will be paths to the appropriate source directories.
  26. var LinuxDir string
  27. var GlibcDir string
  28. const TempDir = "/tmp"
  29. const IncludeDir = TempDir + "/include" // To hold our C headers
  30. const BuildDir = TempDir + "/build" // To hold intermediate build files
  31. const GOOS = "linux" // Only for Linux targets
  32. const BuildArch = "amd64" // Must be built on this architecture
  33. const MinKernel = "2.6.23" // https://golang.org/doc/install#requirements
  34. type target struct {
  35. GoArch string // Architecture name according to Go
  36. LinuxArch string // Architecture name according to the Linux Kernel
  37. GNUArch string // Architecture name according to GNU tools (https://wiki.debian.org/Multiarch/Tuples)
  38. BigEndian bool // Default Little Endian
  39. SignedChar bool // Is -fsigned-char needed (default no)
  40. Bits int
  41. }
  42. // List of the 11 Linux targets supported by the go compiler. sparc64 is not
  43. // currently supported, though a port is in progress.
  44. var targets = []target{
  45. {
  46. GoArch: "386",
  47. LinuxArch: "x86",
  48. GNUArch: "i686-linux-gnu", // Note "i686" not "i386"
  49. Bits: 32,
  50. },
  51. {
  52. GoArch: "amd64",
  53. LinuxArch: "x86",
  54. GNUArch: "x86_64-linux-gnu",
  55. Bits: 64,
  56. },
  57. {
  58. GoArch: "arm64",
  59. LinuxArch: "arm64",
  60. GNUArch: "aarch64-linux-gnu",
  61. SignedChar: true,
  62. Bits: 64,
  63. },
  64. {
  65. GoArch: "arm",
  66. LinuxArch: "arm",
  67. GNUArch: "arm-linux-gnueabi",
  68. Bits: 32,
  69. },
  70. {
  71. GoArch: "mips",
  72. LinuxArch: "mips",
  73. GNUArch: "mips-linux-gnu",
  74. BigEndian: true,
  75. Bits: 32,
  76. },
  77. {
  78. GoArch: "mipsle",
  79. LinuxArch: "mips",
  80. GNUArch: "mipsel-linux-gnu",
  81. Bits: 32,
  82. },
  83. {
  84. GoArch: "mips64",
  85. LinuxArch: "mips",
  86. GNUArch: "mips64-linux-gnuabi64",
  87. BigEndian: true,
  88. Bits: 64,
  89. },
  90. {
  91. GoArch: "mips64le",
  92. LinuxArch: "mips",
  93. GNUArch: "mips64el-linux-gnuabi64",
  94. Bits: 64,
  95. },
  96. {
  97. GoArch: "ppc64",
  98. LinuxArch: "powerpc",
  99. GNUArch: "powerpc64-linux-gnu",
  100. BigEndian: true,
  101. Bits: 64,
  102. },
  103. {
  104. GoArch: "ppc64le",
  105. LinuxArch: "powerpc",
  106. GNUArch: "powerpc64le-linux-gnu",
  107. Bits: 64,
  108. },
  109. {
  110. GoArch: "s390x",
  111. LinuxArch: "s390",
  112. GNUArch: "s390x-linux-gnu",
  113. BigEndian: true,
  114. SignedChar: true,
  115. Bits: 64,
  116. },
  117. // {
  118. // GoArch: "sparc64",
  119. // LinuxArch: "sparc",
  120. // GNUArch: "sparc64-linux-gnu",
  121. // BigEndian: true,
  122. // Bits: 64,
  123. // },
  124. }
  125. // ptracePairs is a list of pairs of targets that can, in some cases,
  126. // run each other's binaries.
  127. var ptracePairs = []struct{ a1, a2 string }{
  128. {"386", "amd64"},
  129. {"arm", "arm64"},
  130. {"mips", "mips64"},
  131. {"mipsle", "mips64le"},
  132. }
  133. func main() {
  134. if runtime.GOOS != GOOS || runtime.GOARCH != BuildArch {
  135. fmt.Printf("Build system has GOOS_GOARCH = %s_%s, need %s_%s\n",
  136. runtime.GOOS, runtime.GOARCH, GOOS, BuildArch)
  137. return
  138. }
  139. // Check that we are using the new build system if we should
  140. if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
  141. fmt.Println("In the new build system, mkall.go should not be called directly.")
  142. fmt.Println("See README.md")
  143. return
  144. }
  145. // Parse the command line options
  146. if len(os.Args) != 3 {
  147. fmt.Println("USAGE: go run linux/mkall.go <linux_dir> <glibc_dir>")
  148. return
  149. }
  150. LinuxDir = os.Args[1]
  151. GlibcDir = os.Args[2]
  152. for _, t := range targets {
  153. fmt.Printf("----- GENERATING: %s -----\n", t.GoArch)
  154. if err := t.generateFiles(); err != nil {
  155. fmt.Printf("%v\n***** FAILURE: %s *****\n\n", err, t.GoArch)
  156. } else {
  157. fmt.Printf("----- SUCCESS: %s -----\n\n", t.GoArch)
  158. }
  159. }
  160. fmt.Printf("----- GENERATING ptrace pairs -----\n")
  161. ok := true
  162. for _, p := range ptracePairs {
  163. if err := generatePtracePair(p.a1, p.a2); err != nil {
  164. fmt.Printf("%v\n***** FAILURE: %s/%s *****\n\n", err, p.a1, p.a2)
  165. ok = false
  166. }
  167. }
  168. if ok {
  169. fmt.Printf("----- SUCCESS ptrace pairs -----\n\n")
  170. }
  171. }
  172. // Makes an exec.Cmd with Stderr attached to os.Stderr
  173. func makeCommand(name string, args ...string) *exec.Cmd {
  174. cmd := exec.Command(name, args...)
  175. cmd.Stderr = os.Stderr
  176. return cmd
  177. }
  178. // Runs the command, pipes output to a formatter, pipes that to an output file.
  179. func (t *target) commandFormatOutput(formatter string, outputFile string,
  180. name string, args ...string) (err error) {
  181. mainCmd := makeCommand(name, args...)
  182. fmtCmd := makeCommand(formatter)
  183. if formatter == "mkpost" {
  184. fmtCmd = makeCommand("go", "run", "mkpost.go")
  185. // Set GOARCH_TARGET so mkpost knows what GOARCH is..
  186. fmtCmd.Env = append(os.Environ(), "GOARCH_TARGET="+t.GoArch)
  187. // Set GOARCH to host arch for mkpost, so it can run natively.
  188. for i, s := range fmtCmd.Env {
  189. if strings.HasPrefix(s, "GOARCH=") {
  190. fmtCmd.Env[i] = "GOARCH=" + BuildArch
  191. }
  192. }
  193. }
  194. // mainCmd | fmtCmd > outputFile
  195. if fmtCmd.Stdin, err = mainCmd.StdoutPipe(); err != nil {
  196. return
  197. }
  198. if fmtCmd.Stdout, err = os.Create(outputFile); err != nil {
  199. return
  200. }
  201. // Make sure the formatter eventually closes
  202. if err = fmtCmd.Start(); err != nil {
  203. return
  204. }
  205. defer func() {
  206. fmtErr := fmtCmd.Wait()
  207. if err == nil {
  208. err = fmtErr
  209. }
  210. }()
  211. return mainCmd.Run()
  212. }
  213. // Generates all the files for a Linux target
  214. func (t *target) generateFiles() error {
  215. // Setup environment variables
  216. os.Setenv("GOOS", GOOS)
  217. os.Setenv("GOARCH", t.GoArch)
  218. // Get appropriate compiler and emulator (unless on x86)
  219. if t.LinuxArch != "x86" {
  220. // Check/Setup cross compiler
  221. compiler := t.GNUArch + "-gcc"
  222. if _, err := exec.LookPath(compiler); err != nil {
  223. return err
  224. }
  225. os.Setenv("CC", compiler)
  226. // Check/Setup emulator (usually first component of GNUArch)
  227. qemuArchName := t.GNUArch[:strings.Index(t.GNUArch, "-")]
  228. if t.LinuxArch == "powerpc" {
  229. qemuArchName = t.GoArch
  230. }
  231. os.Setenv("GORUN", "qemu-"+qemuArchName)
  232. } else {
  233. os.Setenv("CC", "gcc")
  234. }
  235. // Make the include directory and fill it with headers
  236. if err := os.MkdirAll(IncludeDir, os.ModePerm); err != nil {
  237. return err
  238. }
  239. defer os.RemoveAll(IncludeDir)
  240. if err := t.makeHeaders(); err != nil {
  241. return fmt.Errorf("could not make header files: %v", err)
  242. }
  243. fmt.Println("header files generated")
  244. // Make each of the four files
  245. if err := t.makeZSysnumFile(); err != nil {
  246. return fmt.Errorf("could not make zsysnum file: %v", err)
  247. }
  248. fmt.Println("zsysnum file generated")
  249. if err := t.makeZSyscallFile(); err != nil {
  250. return fmt.Errorf("could not make zsyscall file: %v", err)
  251. }
  252. fmt.Println("zsyscall file generated")
  253. if err := t.makeZTypesFile(); err != nil {
  254. return fmt.Errorf("could not make ztypes file: %v", err)
  255. }
  256. fmt.Println("ztypes file generated")
  257. if err := t.makeZErrorsFile(); err != nil {
  258. return fmt.Errorf("could not make zerrors file: %v", err)
  259. }
  260. fmt.Println("zerrors file generated")
  261. return nil
  262. }
  263. // Create the Linux and glibc headers in the include directory.
  264. func (t *target) makeHeaders() error {
  265. // Make the Linux headers we need for this architecture
  266. linuxMake := makeCommand("make", "headers_install", "ARCH="+t.LinuxArch, "INSTALL_HDR_PATH="+TempDir)
  267. linuxMake.Dir = LinuxDir
  268. if err := linuxMake.Run(); err != nil {
  269. return err
  270. }
  271. // A Temporary build directory for glibc
  272. if err := os.MkdirAll(BuildDir, os.ModePerm); err != nil {
  273. return err
  274. }
  275. defer os.RemoveAll(BuildDir)
  276. // Make the glibc headers we need for this architecture
  277. confScript := filepath.Join(GlibcDir, "configure")
  278. glibcConf := makeCommand(confScript, "--prefix="+TempDir, "--host="+t.GNUArch, "--enable-kernel="+MinKernel)
  279. glibcConf.Dir = BuildDir
  280. if err := glibcConf.Run(); err != nil {
  281. return err
  282. }
  283. glibcMake := makeCommand("make", "install-headers")
  284. glibcMake.Dir = BuildDir
  285. if err := glibcMake.Run(); err != nil {
  286. return err
  287. }
  288. // We only need an empty stubs file
  289. stubsFile := filepath.Join(IncludeDir, "gnu/stubs.h")
  290. if file, err := os.Create(stubsFile); err != nil {
  291. return err
  292. } else {
  293. file.Close()
  294. }
  295. return nil
  296. }
  297. // makes the zsysnum_linux_$GOARCH.go file
  298. func (t *target) makeZSysnumFile() error {
  299. zsysnumFile := fmt.Sprintf("zsysnum_linux_%s.go", t.GoArch)
  300. unistdFile := filepath.Join(IncludeDir, "asm/unistd.h")
  301. args := append(t.cFlags(), unistdFile)
  302. return t.commandFormatOutput("gofmt", zsysnumFile, "linux/mksysnum.pl", args...)
  303. }
  304. // makes the zsyscall_linux_$GOARCH.go file
  305. func (t *target) makeZSyscallFile() error {
  306. zsyscallFile := fmt.Sprintf("zsyscall_linux_%s.go", t.GoArch)
  307. // Find the correct architecture syscall file (might end with x.go)
  308. archSyscallFile := fmt.Sprintf("syscall_linux_%s.go", t.GoArch)
  309. if _, err := os.Stat(archSyscallFile); os.IsNotExist(err) {
  310. shortArch := strings.TrimSuffix(t.GoArch, "le")
  311. archSyscallFile = fmt.Sprintf("syscall_linux_%sx.go", shortArch)
  312. }
  313. args := append(t.mksyscallFlags(), "-tags", "linux,"+t.GoArch,
  314. "syscall_linux.go", archSyscallFile)
  315. return t.commandFormatOutput("gofmt", zsyscallFile, "./mksyscall.pl", args...)
  316. }
  317. // makes the zerrors_linux_$GOARCH.go file
  318. func (t *target) makeZErrorsFile() error {
  319. zerrorsFile := fmt.Sprintf("zerrors_linux_%s.go", t.GoArch)
  320. return t.commandFormatOutput("gofmt", zerrorsFile, "./mkerrors.sh", t.cFlags()...)
  321. }
  322. // makes the ztypes_linux_$GOARCH.go file
  323. func (t *target) makeZTypesFile() error {
  324. ztypesFile := fmt.Sprintf("ztypes_linux_%s.go", t.GoArch)
  325. args := []string{"tool", "cgo", "-godefs", "--"}
  326. args = append(args, t.cFlags()...)
  327. args = append(args, "linux/types.go")
  328. return t.commandFormatOutput("mkpost", ztypesFile, "go", args...)
  329. }
  330. // Flags that should be given to gcc and cgo for this target
  331. func (t *target) cFlags() []string {
  332. // Compile statically to avoid cross-architecture dynamic linking.
  333. flags := []string{"-Wall", "-Werror", "-static", "-I" + IncludeDir}
  334. // Architecture-specific flags
  335. if t.SignedChar {
  336. flags = append(flags, "-fsigned-char")
  337. }
  338. if t.LinuxArch == "x86" {
  339. flags = append(flags, fmt.Sprintf("-m%d", t.Bits))
  340. }
  341. return flags
  342. }
  343. // Flags that should be given to mksyscall for this target
  344. func (t *target) mksyscallFlags() (flags []string) {
  345. if t.Bits == 32 {
  346. if t.BigEndian {
  347. flags = append(flags, "-b32")
  348. } else {
  349. flags = append(flags, "-l32")
  350. }
  351. }
  352. // This flag menas a 64-bit value should use (even, odd)-pair.
  353. if t.GoArch == "arm" || (t.LinuxArch == "mips" && t.Bits == 32) {
  354. flags = append(flags, "-arm")
  355. }
  356. return
  357. }
  358. // generatePtracePair takes a pair of GOARCH values that can run each
  359. // other's binaries, such as 386 and amd64. It extracts the PtraceRegs
  360. // type for each one. It writes a new file defining the types
  361. // PtraceRegsArch1 and PtraceRegsArch2 and the corresponding functions
  362. // Ptrace{Get,Set}Regs{arch1,arch2}. This permits debugging the other
  363. // binary on a native system.
  364. func generatePtracePair(arch1, arch2 string) error {
  365. def1, err := ptraceDef(arch1)
  366. if err != nil {
  367. return err
  368. }
  369. def2, err := ptraceDef(arch2)
  370. if err != nil {
  371. return err
  372. }
  373. f, err := os.Create(fmt.Sprintf("zptrace%s_linux.go", arch1))
  374. if err != nil {
  375. return err
  376. }
  377. buf := bufio.NewWriter(f)
  378. fmt.Fprintf(buf, "// Code generated by linux/mkall.go generatePtracePair(%s, %s). DO NOT EDIT.\n", arch1, arch2)
  379. fmt.Fprintf(buf, "\n")
  380. fmt.Fprintf(buf, "// +build linux\n")
  381. fmt.Fprintf(buf, "// +build %s %s\n", arch1, arch2)
  382. fmt.Fprintf(buf, "\n")
  383. fmt.Fprintf(buf, "package unix\n")
  384. fmt.Fprintf(buf, "\n")
  385. fmt.Fprintf(buf, "%s\n", `import "unsafe"`)
  386. fmt.Fprintf(buf, "\n")
  387. writeOnePtrace(buf, arch1, def1)
  388. fmt.Fprintf(buf, "\n")
  389. writeOnePtrace(buf, arch2, def2)
  390. if err := buf.Flush(); err != nil {
  391. return err
  392. }
  393. if err := f.Close(); err != nil {
  394. return err
  395. }
  396. return nil
  397. }
  398. // ptraceDef returns the definition of PtraceRegs for arch.
  399. func ptraceDef(arch string) (string, error) {
  400. filename := fmt.Sprintf("ztypes_linux_%s.go", arch)
  401. data, err := ioutil.ReadFile(filename)
  402. if err != nil {
  403. return "", fmt.Errorf("reading %s: %v", filename, err)
  404. }
  405. start := bytes.Index(data, []byte("type PtraceRegs struct"))
  406. if start < 0 {
  407. return "", fmt.Errorf("%s: no definition of PtraceRegs", filename)
  408. }
  409. data = data[start:]
  410. end := bytes.Index(data, []byte("\n}\n"))
  411. if end < 0 {
  412. return "", fmt.Errorf("%s: can't find end of PtraceRegs definition", filename)
  413. }
  414. return string(data[:end+2]), nil
  415. }
  416. // writeOnePtrace writes out the ptrace definitions for arch.
  417. func writeOnePtrace(w io.Writer, arch, def string) {
  418. uarch := string(unicode.ToUpper(rune(arch[0]))) + arch[1:]
  419. fmt.Fprintf(w, "// PtraceRegs%s is the registers used by %s binaries.\n", uarch, arch)
  420. fmt.Fprintf(w, "%s\n", strings.Replace(def, "PtraceRegs", "PtraceRegs"+uarch, 1))
  421. fmt.Fprintf(w, "\n")
  422. fmt.Fprintf(w, "// PtraceGetRegs%s fetches the registers used by %s binaries.\n", uarch, arch)
  423. fmt.Fprintf(w, "func PtraceGetRegs%s(pid int, regsout *PtraceRegs%s) error {\n", uarch, uarch)
  424. fmt.Fprintf(w, "\treturn ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))\n")
  425. fmt.Fprintf(w, "}\n")
  426. fmt.Fprintf(w, "\n")
  427. fmt.Fprintf(w, "// PtraceSetRegs%s sets the registers used by %s binaries.\n", uarch, arch)
  428. fmt.Fprintf(w, "func PtraceSetRegs%s(pid int, regs *PtraceRegs%s) error {\n", uarch, uarch)
  429. fmt.Fprintf(w, "\treturn ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))\n")
  430. fmt.Fprintf(w, "}\n")
  431. }