golang.org/x/sys@v0.9.0/unix/mksyscall_solaris.go (about)

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