mksyscall.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // Copyright 2018 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. // +build ignore
  5. /*
  6. This program reads a file containing function prototypes
  7. (like syscall_darwin.go) and generates system call bodies.
  8. The prototypes are marked by lines beginning with "//sys"
  9. and read like func declarations if //sys is replaced by func, but:
  10. * The parameter lists must give a name for each argument.
  11. This includes return parameters.
  12. * The parameter lists must give a type for each argument:
  13. the (x, y, z int) shorthand is not allowed.
  14. * If the return parameter is an error number, it must be named errno.
  15. A line beginning with //sysnb is like //sys, except that the
  16. goroutine will not be suspended during the execution of the system
  17. call. This must only be used for system calls which can never
  18. block, as otherwise the system call could cause all goroutines to
  19. hang.
  20. */
  21. package main
  22. import (
  23. "bufio"
  24. "flag"
  25. "fmt"
  26. "os"
  27. "regexp"
  28. "strings"
  29. )
  30. var (
  31. b32 = flag.Bool("b32", false, "32bit big-endian")
  32. l32 = flag.Bool("l32", false, "32bit little-endian")
  33. plan9 = flag.Bool("plan9", false, "plan9")
  34. openbsd = flag.Bool("openbsd", false, "openbsd")
  35. netbsd = flag.Bool("netbsd", false, "netbsd")
  36. dragonfly = flag.Bool("dragonfly", false, "dragonfly")
  37. arm = flag.Bool("arm", false, "arm") // 64-bit value should use (even, odd)-pair
  38. tags = flag.String("tags", "", "build tags")
  39. filename = flag.String("output", "", "output file name (standard output if omitted)")
  40. )
  41. // cmdLine returns this programs's commandline arguments
  42. func cmdLine() string {
  43. return "go run mksyscall.go " + strings.Join(os.Args[1:], " ")
  44. }
  45. // buildTags returns build tags
  46. func buildTags() string {
  47. return *tags
  48. }
  49. // Param is function parameter
  50. type Param struct {
  51. Name string
  52. Type string
  53. }
  54. // usage prints the program usage
  55. func usage() {
  56. fmt.Fprintf(os.Stderr, "usage: go run mksyscall.go [-b32 | -l32] [-tags x,y] [file ...]\n")
  57. os.Exit(1)
  58. }
  59. // parseParamList parses parameter list and returns a slice of parameters
  60. func parseParamList(list string) []string {
  61. list = strings.TrimSpace(list)
  62. if list == "" {
  63. return []string{}
  64. }
  65. return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
  66. }
  67. // parseParam splits a parameter into name and type
  68. func parseParam(p string) Param {
  69. ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
  70. if ps == nil {
  71. fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
  72. os.Exit(1)
  73. }
  74. return Param{ps[1], ps[2]}
  75. }
  76. func main() {
  77. // Get the OS and architecture (using GOARCH_TARGET if it exists)
  78. goos := os.Getenv("GOOS")
  79. if goos == "" {
  80. fmt.Fprintln(os.Stderr, "GOOS not defined in environment")
  81. os.Exit(1)
  82. }
  83. goarch := os.Getenv("GOARCH_TARGET")
  84. if goarch == "" {
  85. goarch = os.Getenv("GOARCH")
  86. }
  87. // Check that we are using the Docker-based build system if we should
  88. if goos == "linux" {
  89. if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
  90. fmt.Fprintf(os.Stderr, "In the Docker-based build system, mksyscall should not be called directly.\n")
  91. fmt.Fprintf(os.Stderr, "See README.md\n")
  92. os.Exit(1)
  93. }
  94. }
  95. flag.Usage = usage
  96. flag.Parse()
  97. if len(flag.Args()) <= 0 {
  98. fmt.Fprintf(os.Stderr, "no files to parse provided\n")
  99. usage()
  100. }
  101. endianness := ""
  102. if *b32 {
  103. endianness = "big-endian"
  104. } else if *l32 {
  105. endianness = "little-endian"
  106. }
  107. libc := false
  108. if goos == "darwin" && (strings.Contains(buildTags(), ",go1.12") || strings.Contains(buildTags(), ",go1.13")) {
  109. libc = true
  110. }
  111. trampolines := map[string]bool{}
  112. text := ""
  113. for _, path := range flag.Args() {
  114. file, err := os.Open(path)
  115. if err != nil {
  116. fmt.Fprintf(os.Stderr, err.Error())
  117. os.Exit(1)
  118. }
  119. s := bufio.NewScanner(file)
  120. for s.Scan() {
  121. t := s.Text()
  122. t = strings.TrimSpace(t)
  123. t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
  124. nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
  125. if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
  126. continue
  127. }
  128. // Line must be of the form
  129. // func Open(path string, mode int, perm int) (fd int, errno error)
  130. // Split into name, in params, out params.
  131. f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$`).FindStringSubmatch(t)
  132. if f == nil {
  133. fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
  134. os.Exit(1)
  135. }
  136. funct, inps, outps, sysname := f[2], f[3], f[4], f[5]
  137. // ClockGettime doesn't have a syscall number on Darwin, only generate libc wrappers.
  138. if goos == "darwin" && !libc && funct == "ClockGettime" {
  139. continue
  140. }
  141. // Split argument lists on comma.
  142. in := parseParamList(inps)
  143. out := parseParamList(outps)
  144. // Try in vain to keep people from editing this file.
  145. // The theory is that they jump into the middle of the file
  146. // without reading the header.
  147. text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
  148. // Go function header.
  149. outDecl := ""
  150. if len(out) > 0 {
  151. outDecl = fmt.Sprintf(" (%s)", strings.Join(out, ", "))
  152. }
  153. text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outDecl)
  154. // Check if err return available
  155. errvar := ""
  156. for _, param := range out {
  157. p := parseParam(param)
  158. if p.Type == "error" {
  159. errvar = p.Name
  160. break
  161. }
  162. }
  163. // Prepare arguments to Syscall.
  164. var args []string
  165. n := 0
  166. for _, param := range in {
  167. p := parseParam(param)
  168. if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
  169. args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
  170. } else if p.Type == "string" && errvar != "" {
  171. text += fmt.Sprintf("\tvar _p%d *byte\n", n)
  172. text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name)
  173. text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
  174. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  175. n++
  176. } else if p.Type == "string" {
  177. fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
  178. text += fmt.Sprintf("\tvar _p%d *byte\n", n)
  179. text += fmt.Sprintf("\t_p%d, _ = BytePtrFromString(%s)\n", n, p.Name)
  180. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  181. n++
  182. } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil {
  183. // Convert slice into pointer, length.
  184. // Have to be careful not to take address of &a[0] if len == 0:
  185. // pass dummy pointer in that case.
  186. // Used to pass nil, but some OSes or simulators reject write(fd, nil, 0).
  187. text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n)
  188. text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name)
  189. text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n)
  190. args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
  191. n++
  192. } else if p.Type == "int64" && (*openbsd || *netbsd) {
  193. args = append(args, "0")
  194. if endianness == "big-endian" {
  195. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  196. } else if endianness == "little-endian" {
  197. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  198. } else {
  199. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  200. }
  201. } else if p.Type == "int64" && *dragonfly {
  202. if regexp.MustCompile(`^(?i)extp(read|write)`).FindStringSubmatch(funct) == nil {
  203. args = append(args, "0")
  204. }
  205. if endianness == "big-endian" {
  206. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  207. } else if endianness == "little-endian" {
  208. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  209. } else {
  210. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  211. }
  212. } else if (p.Type == "int64" || p.Type == "uint64") && endianness != "" {
  213. if len(args)%2 == 1 && *arm {
  214. // arm abi specifies 64-bit argument uses
  215. // (even, odd) pair
  216. args = append(args, "0")
  217. }
  218. if endianness == "big-endian" {
  219. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  220. } else {
  221. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  222. }
  223. } else {
  224. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  225. }
  226. }
  227. // Determine which form to use; pad args with zeros.
  228. asm := "Syscall"
  229. if nonblock != nil {
  230. if errvar == "" && goos == "linux" {
  231. asm = "RawSyscallNoError"
  232. } else {
  233. asm = "RawSyscall"
  234. }
  235. } else {
  236. if errvar == "" && goos == "linux" {
  237. asm = "SyscallNoError"
  238. }
  239. }
  240. if len(args) <= 3 {
  241. for len(args) < 3 {
  242. args = append(args, "0")
  243. }
  244. } else if len(args) <= 6 {
  245. asm += "6"
  246. for len(args) < 6 {
  247. args = append(args, "0")
  248. }
  249. } else if len(args) <= 9 {
  250. asm += "9"
  251. for len(args) < 9 {
  252. args = append(args, "0")
  253. }
  254. } else {
  255. fmt.Fprintf(os.Stderr, "%s:%s too many arguments to system call\n", path, funct)
  256. }
  257. // System call number.
  258. if sysname == "" {
  259. sysname = "SYS_" + funct
  260. sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`)
  261. sysname = strings.ToUpper(sysname)
  262. }
  263. var libcFn string
  264. if libc {
  265. asm = "syscall_" + strings.ToLower(asm[:1]) + asm[1:] // internal syscall call
  266. sysname = strings.TrimPrefix(sysname, "SYS_") // remove SYS_
  267. sysname = strings.ToLower(sysname) // lowercase
  268. libcFn = sysname
  269. sysname = "funcPC(libc_" + sysname + "_trampoline)"
  270. }
  271. // Actual call.
  272. arglist := strings.Join(args, ", ")
  273. call := fmt.Sprintf("%s(%s, %s)", asm, sysname, arglist)
  274. // Assign return values.
  275. body := ""
  276. ret := []string{"_", "_", "_"}
  277. doErrno := false
  278. for i := 0; i < len(out); i++ {
  279. p := parseParam(out[i])
  280. reg := ""
  281. if p.Name == "err" && !*plan9 {
  282. reg = "e1"
  283. ret[2] = reg
  284. doErrno = true
  285. } else if p.Name == "err" && *plan9 {
  286. ret[0] = "r0"
  287. ret[2] = "e1"
  288. break
  289. } else {
  290. reg = fmt.Sprintf("r%d", i)
  291. ret[i] = reg
  292. }
  293. if p.Type == "bool" {
  294. reg = fmt.Sprintf("%s != 0", reg)
  295. }
  296. if p.Type == "int64" && endianness != "" {
  297. // 64-bit number in r1:r0 or r0:r1.
  298. if i+2 > len(out) {
  299. fmt.Fprintf(os.Stderr, "%s:%s not enough registers for int64 return\n", path, funct)
  300. }
  301. if endianness == "big-endian" {
  302. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
  303. } else {
  304. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
  305. }
  306. ret[i] = fmt.Sprintf("r%d", i)
  307. ret[i+1] = fmt.Sprintf("r%d", i+1)
  308. }
  309. if reg != "e1" || *plan9 {
  310. body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
  311. }
  312. }
  313. if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
  314. text += fmt.Sprintf("\t%s\n", call)
  315. } else {
  316. if errvar == "" && goos == "linux" {
  317. // raw syscall without error on Linux, see golang.org/issue/22924
  318. text += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], call)
  319. } else {
  320. text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
  321. }
  322. }
  323. text += body
  324. if *plan9 && ret[2] == "e1" {
  325. text += "\tif int32(r0) == -1 {\n"
  326. text += "\t\terr = e1\n"
  327. text += "\t}\n"
  328. } else if doErrno {
  329. text += "\tif e1 != 0 {\n"
  330. text += "\t\terr = errnoErr(e1)\n"
  331. text += "\t}\n"
  332. }
  333. text += "\treturn\n"
  334. text += "}\n\n"
  335. if libc && !trampolines[libcFn] {
  336. // some system calls share a trampoline, like read and readlen.
  337. trampolines[libcFn] = true
  338. // Declare assembly trampoline.
  339. text += fmt.Sprintf("func libc_%s_trampoline()\n", libcFn)
  340. // Assembly trampoline calls the libc_* function, which this magic
  341. // redirects to use the function from libSystem.
  342. text += fmt.Sprintf("//go:linkname libc_%s libc_%s\n", libcFn, libcFn)
  343. text += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"/usr/lib/libSystem.B.dylib\"\n", libcFn, libcFn)
  344. text += "\n"
  345. }
  346. }
  347. if err := s.Err(); err != nil {
  348. fmt.Fprintf(os.Stderr, err.Error())
  349. os.Exit(1)
  350. }
  351. file.Close()
  352. }
  353. fmt.Printf(srcTemplate, cmdLine(), buildTags(), text)
  354. }
  355. const srcTemplate = `// %s
  356. // Code generated by the command above; see README.md. DO NOT EDIT.
  357. // +build %s
  358. package unix
  359. import (
  360. "syscall"
  361. "unsafe"
  362. )
  363. var _ syscall.Errno
  364. %s
  365. `