mksyscall.go 11 KB

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