mksyscall_solaris.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Copyright 2019 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_solaris.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 err.
  15. * If go func name needs to be different than its libc name,
  16. * or the function is not in libc, name could be specified
  17. * at the end, after "=" sign, like
  18. //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
  19. */
  20. package main
  21. import (
  22. "bufio"
  23. "flag"
  24. "fmt"
  25. "os"
  26. "regexp"
  27. "strings"
  28. )
  29. var (
  30. b32 = flag.Bool("b32", false, "32bit big-endian")
  31. l32 = flag.Bool("l32", false, "32bit little-endian")
  32. tags = flag.String("tags", "", "build tags")
  33. illumos = flag.Bool("illumos", false, "illumos specific code generation")
  34. )
  35. // cmdLine returns this programs's commandline arguments
  36. func cmdLine() string {
  37. return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ")
  38. }
  39. // buildTags returns build tags
  40. func buildTags() string {
  41. return *tags
  42. }
  43. // Param is function parameter
  44. type Param struct {
  45. Name string
  46. Type string
  47. }
  48. // usage prints the program usage
  49. func usage() {
  50. fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n")
  51. os.Exit(1)
  52. }
  53. // parseParamList parses parameter list and returns a slice of parameters
  54. func parseParamList(list string) []string {
  55. list = strings.TrimSpace(list)
  56. if list == "" {
  57. return []string{}
  58. }
  59. return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
  60. }
  61. // parseParam splits a parameter into name and type
  62. func parseParam(p string) Param {
  63. ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
  64. if ps == nil {
  65. fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
  66. os.Exit(1)
  67. }
  68. return Param{ps[1], ps[2]}
  69. }
  70. func main() {
  71. flag.Usage = usage
  72. flag.Parse()
  73. if len(flag.Args()) <= 0 {
  74. fmt.Fprintf(os.Stderr, "no files to parse provided\n")
  75. usage()
  76. }
  77. endianness := ""
  78. if *b32 {
  79. endianness = "big-endian"
  80. } else if *l32 {
  81. endianness = "little-endian"
  82. }
  83. pack := ""
  84. text := ""
  85. dynimports := ""
  86. linknames := ""
  87. var vars []string
  88. for _, path := range flag.Args() {
  89. file, err := os.Open(path)
  90. if err != nil {
  91. fmt.Fprintf(os.Stderr, err.Error())
  92. os.Exit(1)
  93. }
  94. s := bufio.NewScanner(file)
  95. for s.Scan() {
  96. t := s.Text()
  97. t = strings.TrimSpace(t)
  98. t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
  99. if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" {
  100. pack = p[1]
  101. }
  102. nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
  103. if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
  104. continue
  105. }
  106. // Line must be of the form
  107. // func Open(path string, mode int, perm int) (fd int, err error)
  108. // Split into name, in params, out params.
  109. f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t)
  110. if f == nil {
  111. fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
  112. os.Exit(1)
  113. }
  114. funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6]
  115. // Split argument lists on comma.
  116. in := parseParamList(inps)
  117. out := parseParamList(outps)
  118. inps = strings.Join(in, ", ")
  119. outps = strings.Join(out, ", ")
  120. // Try in vain to keep people from editing this file.
  121. // The theory is that they jump into the middle of the file
  122. // without reading the header.
  123. text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
  124. // So file name.
  125. if modname == "" {
  126. modname = "libc"
  127. }
  128. // System call name.
  129. if sysname == "" {
  130. sysname = funct
  131. }
  132. // System call pointer variable name.
  133. sysvarname := fmt.Sprintf("proc%s", sysname)
  134. strconvfunc := "BytePtrFromString"
  135. strconvtype := "*byte"
  136. sysname = strings.ToLower(sysname) // All libc functions are lowercase.
  137. // Runtime import of function to allow cross-platform builds.
  138. dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname)
  139. // Link symbol to proc address variable.
  140. linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname)
  141. // Library proc address variable.
  142. vars = append(vars, sysvarname)
  143. // Go function header.
  144. outlist := strings.Join(out, ", ")
  145. if outlist != "" {
  146. outlist = fmt.Sprintf(" (%s)", outlist)
  147. }
  148. if text != "" {
  149. text += "\n"
  150. }
  151. text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist)
  152. // Check if err return available
  153. errvar := ""
  154. for _, param := range out {
  155. p := parseParam(param)
  156. if p.Type == "error" {
  157. errvar = p.Name
  158. continue
  159. }
  160. }
  161. // Prepare arguments to Syscall.
  162. var args []string
  163. n := 0
  164. for _, param := range in {
  165. p := parseParam(param)
  166. if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
  167. args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
  168. } else if p.Type == "string" && errvar != "" {
  169. text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
  170. text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name)
  171. text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
  172. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  173. n++
  174. } else if p.Type == "string" {
  175. fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
  176. text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
  177. text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name)
  178. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
  179. n++
  180. } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil {
  181. // Convert slice into pointer, length.
  182. // Have to be careful not to take address of &a[0] if len == 0:
  183. // pass nil in that case.
  184. text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1])
  185. text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name)
  186. args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
  187. n++
  188. } else if p.Type == "int64" && endianness != "" {
  189. if endianness == "big-endian" {
  190. args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
  191. } else {
  192. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
  193. }
  194. } else if p.Type == "bool" {
  195. text += fmt.Sprintf("\tvar _p%d uint32\n", n)
  196. text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n)
  197. args = append(args, fmt.Sprintf("uintptr(_p%d)", n))
  198. n++
  199. } else {
  200. args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
  201. }
  202. }
  203. nargs := len(args)
  204. // Determine which form to use; pad args with zeros.
  205. asm := "sysvicall6"
  206. if nonblock != nil {
  207. asm = "rawSysvicall6"
  208. }
  209. if len(args) <= 6 {
  210. for len(args) < 6 {
  211. args = append(args, "0")
  212. }
  213. } else {
  214. fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path)
  215. os.Exit(1)
  216. }
  217. // Actual call.
  218. arglist := strings.Join(args, ", ")
  219. call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist)
  220. // Assign return values.
  221. body := ""
  222. ret := []string{"_", "_", "_"}
  223. doErrno := false
  224. for i := 0; i < len(out); i++ {
  225. p := parseParam(out[i])
  226. reg := ""
  227. if p.Name == "err" {
  228. reg = "e1"
  229. ret[2] = reg
  230. doErrno = true
  231. } else {
  232. reg = fmt.Sprintf("r%d", i)
  233. ret[i] = reg
  234. }
  235. if p.Type == "bool" {
  236. reg = fmt.Sprintf("%d != 0", reg)
  237. }
  238. if p.Type == "int64" && endianness != "" {
  239. // 64-bit number in r1:r0 or r0:r1.
  240. if i+2 > len(out) {
  241. fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path)
  242. os.Exit(1)
  243. }
  244. if endianness == "big-endian" {
  245. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
  246. } else {
  247. reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
  248. }
  249. ret[i] = fmt.Sprintf("r%d", i)
  250. ret[i+1] = fmt.Sprintf("r%d", i+1)
  251. }
  252. if reg != "e1" {
  253. body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
  254. }
  255. }
  256. if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
  257. text += fmt.Sprintf("\t%s\n", call)
  258. } else {
  259. text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
  260. }
  261. text += body
  262. if doErrno {
  263. text += "\tif e1 != 0 {\n"
  264. text += "\t\terr = e1\n"
  265. text += "\t}\n"
  266. }
  267. text += "\treturn\n"
  268. text += "}\n"
  269. }
  270. if err := s.Err(); err != nil {
  271. fmt.Fprintf(os.Stderr, err.Error())
  272. os.Exit(1)
  273. }
  274. file.Close()
  275. }
  276. imp := ""
  277. if pack != "unix" {
  278. imp = "import \"golang.org/x/sys/unix\"\n"
  279. }
  280. syscallimp := ""
  281. if !*illumos {
  282. syscallimp = "\"syscall\""
  283. }
  284. vardecls := "\t" + strings.Join(vars, ",\n\t")
  285. vardecls += " syscallFunc"
  286. fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, syscallimp, imp, dynimports, linknames, vardecls, text)
  287. }
  288. const srcTemplate = `// %s
  289. // Code generated by the command above; see README.md. DO NOT EDIT.
  290. // +build %s
  291. package %s
  292. import (
  293. "unsafe"
  294. %s
  295. )
  296. %s
  297. %s
  298. %s
  299. var (
  300. %s
  301. )
  302. %s
  303. `