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.
8 This program reads a file containing function prototypes
9 (like syscall_solaris.go) and generates system call bodies.
10 The prototypes are marked by lines beginning with "//sys"
11 and read like func declarations if //sys is replaced by func, but:
12 * The parameter lists must give a name for each argument.
13 This includes return parameters.
14 * The parameter lists must give a type for each argument:
15 the (x, y, z int) shorthand is not allowed.
16 * If the return parameter is an error number, it must be named err.
17 * If go func name needs to be different than its libc name,
18 * or the function is not in libc, name could be specified
19 * at the end, after "=" sign, like
20 //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
35 b32 = flag.Bool("b32", false, "32bit big-endian")
36 l32 = flag.Bool("l32", false, "32bit little-endian")
37 tags = flag.String("tags", "", "build tags")
38 illumos = flag.Bool("illumos", false, "illumos specific code generation")
41 // cmdLine returns this programs's commandline arguments
42 func cmdLine() string {
43 return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ")
46 // buildTags returns build tags
47 func buildTags() string {
51 // Param is function parameter
57 // usage prints the program usage
59 fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n")
63 // parseParamList parses parameter list and returns a slice of parameters
64 func parseParamList(list string) []string {
65 list = strings.TrimSpace(list)
69 return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
72 // parseParam splits a parameter into name and type
73 func parseParam(p string) Param {
74 ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
76 fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
79 return Param{ps[1], ps[2]}
85 if len(flag.Args()) <= 0 {
86 fmt.Fprintf(os.Stderr, "no files to parse provided\n")
92 endianness = "big-endian"
94 endianness = "little-endian"
102 for _, path := range flag.Args() {
103 file, err := os.Open(path)
105 fmt.Fprintf(os.Stderr, err.Error())
108 s := bufio.NewScanner(file)
111 t = strings.TrimSpace(t)
112 t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
113 if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" {
116 nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
117 if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
121 // Line must be of the form
122 // func Open(path string, mode int, perm int) (fd int, err error)
123 // Split into name, in params, out params.
124 f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t)
126 fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
129 funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6]
131 // Split argument lists on comma.
132 in := parseParamList(inps)
133 out := parseParamList(outps)
135 inps = strings.Join(in, ", ")
136 outps = strings.Join(out, ", ")
138 // Try in vain to keep people from editing this file.
139 // The theory is that they jump into the middle of the file
140 // without reading the header.
141 text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
153 // System call pointer variable name.
154 sysvarname := fmt.Sprintf("proc%s", sysname)
156 strconvfunc := "BytePtrFromString"
157 strconvtype := "*byte"
159 sysname = strings.ToLower(sysname) // All libc functions are lowercase.
161 // Runtime import of function to allow cross-platform builds.
162 dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname)
163 // Link symbol to proc address variable.
164 linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname)
165 // Library proc address variable.
166 vars = append(vars, sysvarname)
168 // Go function header.
169 outlist := strings.Join(out, ", ")
171 outlist = fmt.Sprintf(" (%s)", outlist)
176 text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist)
178 // Check if err return available
180 for _, param := range out {
181 p := parseParam(param)
182 if p.Type == "error" {
188 // Prepare arguments to Syscall.
191 for _, param := range in {
192 p := parseParam(param)
193 if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
194 args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
195 } else if p.Type == "string" && errvar != "" {
196 text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
197 text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name)
198 text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
199 args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
201 } else if p.Type == "string" {
202 fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
203 text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
204 text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name)
205 args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
207 } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil {
208 // Convert slice into pointer, length.
209 // Have to be careful not to take address of &a[0] if len == 0:
210 // pass nil in that case.
211 text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1])
212 text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name)
213 args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
215 } else if p.Type == "int64" && endianness != "" {
216 if endianness == "big-endian" {
217 args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
219 args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
221 } else if p.Type == "bool" {
222 text += fmt.Sprintf("\tvar _p%d uint32\n", n)
223 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)
224 args = append(args, fmt.Sprintf("uintptr(_p%d)", n))
227 args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
232 // Determine which form to use; pad args with zeros.
235 asm = "rawSysvicall6"
239 args = append(args, "0")
242 fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path)
247 arglist := strings.Join(args, ", ")
248 call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist)
250 // Assign return values.
252 ret := []string{"_", "_", "_"}
254 for i := 0; i < len(out); i++ {
255 p := parseParam(out[i])
262 reg = fmt.Sprintf("r%d", i)
265 if p.Type == "bool" {
266 reg = fmt.Sprintf("%d != 0", reg)
268 if p.Type == "int64" && endianness != "" {
269 // 64-bit number in r1:r0 or r0:r1.
271 fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path)
274 if endianness == "big-endian" {
275 reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
277 reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
279 ret[i] = fmt.Sprintf("r%d", i)
280 ret[i+1] = fmt.Sprintf("r%d", i+1)
283 body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
286 if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
287 text += fmt.Sprintf("\t%s\n", call)
289 text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
294 text += "\tif e1 != 0 {\n"
295 text += "\t\terr = e1\n"
301 if err := s.Err(); err != nil {
302 fmt.Fprintf(os.Stderr, err.Error())
309 imp = "import \"golang.org/x/sys/unix\"\n"
314 syscallimp = "\"syscall\""
317 vardecls := "\t" + strings.Join(vars, ",\n\t")
318 vardecls += " syscallFunc"
319 fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, syscallimp, imp, dynimports, linknames, vardecls, text)
322 const srcTemplate = `// %s
323 // Code generated by the command above; see README.md. DO NOT EDIT.