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