mksyscall.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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_plan9.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. goarch := os.Getenv("GOARCH_TARGET")
  80. if goarch == "" {
  81. goarch = os.Getenv("GOARCH")
  82. }
  83. // Check that we are using the Docker-based build system if we should
  84. if goos == "linux" {
  85. if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
  86. fmt.Fprintf(os.Stderr, "In the Docker-based build system, mksyscall should not be called directly.\n")
  87. fmt.Fprintf(os.Stderr, "See README.md\n")
  88. os.Exit(1)
  89. }
  90. }
  91. flag.Usage = usage
  92. flag.Parse()
  93. if len(flag.Args()) <= 0 {
  94. fmt.Fprintf(os.Stderr, "no files to parse provided\n")
  95. usage()
  96. }
  97. endianness := ""
  98. if *b32 {
  99. endianness = "big-endian"
  100. } else if *l32 {
  101. endianness = "little-endian"
  102. }
  103. libc := false
  104. if goos == "darwin" && strings.Contains(buildTags(), ",go1.12") {
  105. libc = true
  106. }
  107. trampolines := map[string]bool{}
  108. text := ""
  109. for _, path := range flag.Args() {
  110. file, err := os.Open(path)
  111. if err != nil {
  112. fmt.Fprintf(os.Stderr, err.Error())
  113. os.Exit(1)
  114. }
  115. s := bufio.NewScanner(file)
  116. for s.Scan() {
  117. t := s.Text()
  118. t = strings.TrimSpace(t)
  119. t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
  120. nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
  121. if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
  122. continue
  123. }
  124. // Line must be of the form
  125. // func Open(path string, mode int, perm int) (fd int, errno error)
  126. // Split into name, in params, out params.
  127. f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$`).FindStringSubmatch(t)
  128. if f == nil {
  129. fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
  130. os.Exit(1)
  131. }
  132. funct, inps, outps, sysname := f[2], f[3], f[4], f[5]
  133. // Split argument lists on comma.
  134. in := parseParamList(inps)
  135. out := parseParamList(outps)
  136. // Try in vain to keep people from editing this file.
  137. // The theory is that they jump into the middle of the file
  138. // without reading the header.
  139. text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
  140. // Go function header.
  141. outDecl := ""
  142. if len(out) > 0 {
  143. outDecl = fmt.Sprintf(" (%s)", strings.Join(out, ", "))
  144. }
  145. text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outDecl)
  146. // Check if err return available
  147. errvar := ""
  148. for _, param := range out {
  149. p := parseParam(param)
  150. if p.Type == "error" {
  151. errvar = p.Name
  152. break
  153. }
  154. }
  155. // Prepare arguments to Syscall.
  156. var args []string
  157. n := 0
  158. for _, param := range in {
  159. p := parseParam(param)
  160. if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
  161. args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
  162. } else if p.Type == "string" && errvar != "" {
  163. text += fmt.Sprintf("\tvar _p%d *byte\n", n)
  164. text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name)
  165. text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
  166. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  167. n++
  168. } else if p.Type == "string" {
  169. fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
  170. text += fmt.Sprintf("\tvar _p%d *byte\n", n)
  171. text += fmt.Sprintf("\t_p%d, _ = BytePtrFromString(%s)\n", n, p.Name)
  172. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  173. n++
  174. } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil {
  175. // Convert slice into pointer, length.
  176. // Have to be careful not to take address of &a[0] if len == 0:
  177. // pass dummy pointer in that case.
  178. // Used to pass nil, but some OSes or simulators reject write(fd, nil, 0).
  179. text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n)
  180. text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name)
  181. text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n)
  182. args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
  183. n++
  184. } else if p.Type == "int64" && (*openbsd || *netbsd) {
  185. args = append(args, "0")
  186. if endianness == "big-endian" {
  187. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  188. } else if endianness == "little-endian" {
  189. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  190. } else {
  191. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  192. }
  193. } else if p.Type == "int64" && *dragonfly {
  194. if regexp.MustCompile(`^(?i)extp(read|write)`).FindStringSubmatch(funct) == nil {
  195. args = append(args, "0")
  196. }
  197. if endianness == "big-endian" {
  198. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  199. } else if endianness == "little-endian" {
  200. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  201. } else {
  202. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  203. }
  204. } else if p.Type == "int64" && endianness != "" {
  205. if len(args)%2 == 1 && *arm {
  206. // arm abi specifies 64-bit argument uses
  207. // (even, odd) pair
  208. args = append(args, "0")
  209. }
  210. if endianness == "big-endian" {
  211. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  212. } else {
  213. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  214. }
  215. } else {
  216. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  217. }
  218. }
  219. // Determine which form to use; pad args with zeros.
  220. asm := "Syscall"
  221. if nonblock != nil {
  222. if errvar == "" && goos == "linux" {
  223. asm = "RawSyscallNoError"
  224. } else {
  225. asm = "RawSyscall"
  226. }
  227. } else {
  228. if errvar == "" && goos == "linux" {
  229. asm = "SyscallNoError"
  230. }
  231. }
  232. if len(args) <= 3 {
  233. for len(args) < 3 {
  234. args = append(args, "0")
  235. }
  236. } else if len(args) <= 6 {
  237. asm += "6"
  238. for len(args) < 6 {
  239. args = append(args, "0")
  240. }
  241. } else if len(args) <= 9 {
  242. asm += "9"
  243. for len(args) < 9 {
  244. args = append(args, "0")
  245. }
  246. } else {
  247. fmt.Fprintf(os.Stderr, "%s:%s too many arguments to system call\n", path, funct)
  248. }
  249. // System call number.
  250. if sysname == "" {
  251. sysname = "SYS_" + funct
  252. sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`)
  253. sysname = strings.ToUpper(sysname)
  254. }
  255. var libcFn string
  256. if libc {
  257. asm = "syscall_" + strings.ToLower(asm[:1]) + asm[1:] // internal syscall call
  258. sysname = strings.TrimPrefix(sysname, "SYS_") // remove SYS_
  259. sysname = strings.ToLower(sysname) // lowercase
  260. if sysname == "getdirentries64" {
  261. // Special case - libSystem name and
  262. // raw syscall name don't match.
  263. sysname = "__getdirentries64"
  264. }
  265. libcFn = sysname
  266. sysname = "funcPC(libc_" + sysname + "_trampoline)"
  267. }
  268. // Actual call.
  269. arglist := strings.Join(args, ", ")
  270. call := fmt.Sprintf("%s(%s, %s)", asm, sysname, arglist)
  271. // Assign return values.
  272. body := ""
  273. ret := []string{"_", "_", "_"}
  274. doErrno := false
  275. for i := 0; i < len(out); i++ {
  276. p := parseParam(out[i])
  277. reg := ""
  278. if p.Name == "err" && !*plan9 {
  279. reg = "e1"
  280. ret[2] = reg
  281. doErrno = true
  282. } else if p.Name == "err" && *plan9 {
  283. ret[0] = "r0"
  284. ret[2] = "e1"
  285. break
  286. } else {
  287. reg = fmt.Sprintf("r%d", i)
  288. ret[i] = reg
  289. }
  290. if p.Type == "bool" {
  291. reg = fmt.Sprintf("%s != 0", reg)
  292. }
  293. if p.Type == "int64" && endianness != "" {
  294. // 64-bit number in r1:r0 or r0:r1.
  295. if i+2 > len(out) {
  296. fmt.Fprintf(os.Stderr, "%s:%s not enough registers for int64 return\n", path, funct)
  297. }
  298. if endianness == "big-endian" {
  299. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
  300. } else {
  301. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
  302. }
  303. ret[i] = fmt.Sprintf("r%d", i)
  304. ret[i+1] = fmt.Sprintf("r%d", i+1)
  305. }
  306. if reg != "e1" || *plan9 {
  307. body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
  308. }
  309. }
  310. if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
  311. text += fmt.Sprintf("\t%s\n", call)
  312. } else {
  313. if errvar == "" && goos == "linux" {
  314. // raw syscall without error on Linux, see golang.org/issue/22924
  315. text += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], call)
  316. } else {
  317. text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
  318. }
  319. }
  320. text += body
  321. if *plan9 && ret[2] == "e1" {
  322. text += "\tif int32(r0) == -1 {\n"
  323. text += "\t\terr = e1\n"
  324. text += "\t}\n"
  325. } else if doErrno {
  326. text += "\tif e1 != 0 {\n"
  327. text += "\t\terr = errnoErr(e1)\n"
  328. text += "\t}\n"
  329. }
  330. text += "\treturn\n"
  331. text += "}\n\n"
  332. if libc && !trampolines[libcFn] {
  333. // some system calls share a trampoline, like read and readlen.
  334. trampolines[libcFn] = true
  335. // Declare assembly trampoline.
  336. text += fmt.Sprintf("func libc_%s_trampoline()\n", libcFn)
  337. // Assembly trampoline calls the libc_* function, which this magic
  338. // redirects to use the function from libSystem.
  339. text += fmt.Sprintf("//go:linkname libc_%s libc_%s\n", libcFn, libcFn)
  340. text += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"/usr/lib/libSystem.B.dylib\"\n", libcFn, libcFn)
  341. text += "\n"
  342. }
  343. }
  344. if err := s.Err(); err != nil {
  345. fmt.Fprintf(os.Stderr, err.Error())
  346. os.Exit(1)
  347. }
  348. file.Close()
  349. }
  350. fmt.Printf(srcTemplate, cmdLine(), buildTags(), text)
  351. }
  352. const srcTemplate = `// %s
  353. // Code generated by the command above; see README.md. DO NOT EDIT.
  354. // +build %s
  355. package plan9
  356. import "unsafe"
  357. %s
  358. `