github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/cmd/cgo/main.go (about)

     1  // Copyright 2009 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  // Cgo; see gmp.go for an overview.
     6  
     7  // TODO(rsc):
     8  //	Emit correct line number annotations.
     9  //	Make gc understand the annotations.
    10  
    11  package main
    12  
    13  import (
    14  	"crypto/md5"
    15  	"flag"
    16  	"fmt"
    17  	"go/ast"
    18  	"go/printer"
    19  	"go/token"
    20  	"io"
    21  	"os"
    22  	"path/filepath"
    23  	"reflect"
    24  	"runtime"
    25  	"sort"
    26  	"strings"
    27  )
    28  
    29  // A Package collects information about the package we're going to write.
    30  type Package struct {
    31  	PackageName string // name of package
    32  	PackagePath string
    33  	PtrSize     int64
    34  	IntSize     int64
    35  	GccOptions  []string
    36  	GccIsClang  bool
    37  	CgoFlags    map[string][]string // #cgo flags (CFLAGS, LDFLAGS)
    38  	Written     map[string]bool
    39  	Name        map[string]*Name // accumulated Name from Files
    40  	ExpFunc     []*ExpFunc       // accumulated ExpFunc from Files
    41  	Decl        []ast.Decl
    42  	GoFiles     []string // list of Go files
    43  	GccFiles    []string // list of gcc output files
    44  	Preamble    string   // collected preamble for _cgo_export.h
    45  }
    46  
    47  // A File collects information about a single Go input file.
    48  type File struct {
    49  	AST      *ast.File           // parsed AST
    50  	Comments []*ast.CommentGroup // comments from file
    51  	Package  string              // Package name
    52  	Preamble string              // C preamble (doc comment on import "C")
    53  	Ref      []*Ref              // all references to C.xxx in AST
    54  	Calls    []*Call             // all calls to C.xxx in AST
    55  	ExpFunc  []*ExpFunc          // exported functions for this file
    56  	Name     map[string]*Name    // map from Go name to Name
    57  }
    58  
    59  func nameKeys(m map[string]*Name) []string {
    60  	var ks []string
    61  	for k := range m {
    62  		ks = append(ks, k)
    63  	}
    64  	sort.Strings(ks)
    65  	return ks
    66  }
    67  
    68  // A Call refers to a call of a C.xxx function in the AST.
    69  type Call struct {
    70  	Call     *ast.CallExpr
    71  	Deferred bool
    72  }
    73  
    74  // A Ref refers to an expression of the form C.xxx in the AST.
    75  type Ref struct {
    76  	Name    *Name
    77  	Expr    *ast.Expr
    78  	Context string // "type", "expr", "call", or "call2"
    79  }
    80  
    81  func (r *Ref) Pos() token.Pos {
    82  	return (*r.Expr).Pos()
    83  }
    84  
    85  // A Name collects information about C.xxx.
    86  type Name struct {
    87  	Go       string // name used in Go referring to package C
    88  	Mangle   string // name used in generated Go
    89  	C        string // name used in C
    90  	Define   string // #define expansion
    91  	Kind     string // "const", "type", "var", "fpvar", "func", "not-type"
    92  	Type     *Type  // the type of xxx
    93  	FuncType *FuncType
    94  	AddError bool
    95  	Const    string // constant definition
    96  }
    97  
    98  // IsVar reports whether Kind is either "var" or "fpvar"
    99  func (n *Name) IsVar() bool {
   100  	return n.Kind == "var" || n.Kind == "fpvar"
   101  }
   102  
   103  // A ExpFunc is an exported function, callable from C.
   104  // Such functions are identified in the Go input file
   105  // by doc comments containing the line //export ExpName
   106  type ExpFunc struct {
   107  	Func    *ast.FuncDecl
   108  	ExpName string // name to use from C
   109  	Doc     string
   110  }
   111  
   112  // A TypeRepr contains the string representation of a type.
   113  type TypeRepr struct {
   114  	Repr       string
   115  	FormatArgs []interface{}
   116  }
   117  
   118  // A Type collects information about a type in both the C and Go worlds.
   119  type Type struct {
   120  	Size       int64
   121  	Align      int64
   122  	C          *TypeRepr
   123  	Go         ast.Expr
   124  	EnumValues map[string]int64
   125  	Typedef    string
   126  }
   127  
   128  // A FuncType collects information about a function type in both the C and Go worlds.
   129  type FuncType struct {
   130  	Params []*Type
   131  	Result *Type
   132  	Go     *ast.FuncType
   133  }
   134  
   135  func usage() {
   136  	fmt.Fprint(os.Stderr, "usage: cgo -- [compiler options] file.go ...\n")
   137  	flag.PrintDefaults()
   138  	os.Exit(2)
   139  }
   140  
   141  var ptrSizeMap = map[string]int64{
   142  	"386":      4,
   143  	"amd64":    8,
   144  	"arm":      4,
   145  	"arm64":    8,
   146  	"mips":     4,
   147  	"mipsle":   4,
   148  	"mips64":   8,
   149  	"mips64le": 8,
   150  	"ppc64":    8,
   151  	"ppc64le":  8,
   152  	"riscv":    8,
   153  	"s390":     4,
   154  	"s390x":    8,
   155  }
   156  
   157  var intSizeMap = map[string]int64{
   158  	"386":      4,
   159  	"amd64":    8,
   160  	"arm":      4,
   161  	"arm64":    8,
   162  	"mips":     4,
   163  	"mipsle":   4,
   164  	"mips64":   8,
   165  	"mips64le": 8,
   166  	"ppc64":    8,
   167  	"ppc64le":  8,
   168  	"riscv":    8,
   169  	"s390":     4,
   170  	"s390x":    8,
   171  }
   172  
   173  var cPrefix string
   174  
   175  var fset = token.NewFileSet()
   176  
   177  var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
   178  var dynout = flag.String("dynout", "", "write -dynimport output to this file")
   179  var dynpackage = flag.String("dynpackage", "main", "set Go package for -dynimport output")
   180  var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in -dynimport mode")
   181  
   182  // This flag is for bootstrapping a new Go implementation,
   183  // to generate Go types that match the data layout and
   184  // constant values used in the host's C libraries and system calls.
   185  var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
   186  
   187  var srcDir = flag.String("srcdir", "", "source directory")
   188  var objDir = flag.String("objdir", "", "object directory")
   189  var importPath = flag.String("importpath", "", "import path of package being built (for comments in generated files)")
   190  var exportHeader = flag.String("exportheader", "", "where to write export header if any exported functions")
   191  
   192  var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo")
   193  var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo")
   194  var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo")
   195  var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code")
   196  var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code")
   197  var goarch, goos string
   198  
   199  func main() {
   200  	flag.Usage = usage
   201  	flag.Parse()
   202  
   203  	if *dynobj != "" {
   204  		// cgo -dynimport is essentially a separate helper command
   205  		// built into the cgo binary. It scans a gcc-produced executable
   206  		// and dumps information about the imported symbols and the
   207  		// imported libraries. The 'go build' rules for cgo prepare an
   208  		// appropriate executable and then use its import information
   209  		// instead of needing to make the linkers duplicate all the
   210  		// specialized knowledge gcc has about where to look for imported
   211  		// symbols and which ones to use.
   212  		dynimport(*dynobj)
   213  		return
   214  	}
   215  
   216  	if *godefs {
   217  		// Generating definitions pulled from header files,
   218  		// to be checked into Go repositories.
   219  		// Line numbers are just noise.
   220  		conf.Mode &^= printer.SourcePos
   221  	}
   222  
   223  	args := flag.Args()
   224  	if len(args) < 1 {
   225  		usage()
   226  	}
   227  
   228  	// Find first arg that looks like a go file and assume everything before
   229  	// that are options to pass to gcc.
   230  	var i int
   231  	for i = len(args); i > 0; i-- {
   232  		if !strings.HasSuffix(args[i-1], ".go") {
   233  			break
   234  		}
   235  	}
   236  	if i == len(args) {
   237  		usage()
   238  	}
   239  
   240  	goFiles := args[i:]
   241  
   242  	for _, arg := range args[:i] {
   243  		if arg == "-fsanitize=thread" {
   244  			tsanProlog = yesTsanProlog
   245  		}
   246  	}
   247  
   248  	p := newPackage(args[:i])
   249  
   250  	// Record CGO_LDFLAGS from the environment for external linking.
   251  	if ldflags := os.Getenv("CGO_LDFLAGS"); ldflags != "" {
   252  		args, err := splitQuoted(ldflags)
   253  		if err != nil {
   254  			fatalf("bad CGO_LDFLAGS: %q (%s)", ldflags, err)
   255  		}
   256  		p.addToFlag("LDFLAGS", args)
   257  	}
   258  
   259  	// Need a unique prefix for the global C symbols that
   260  	// we use to coordinate between gcc and ourselves.
   261  	// We already put _cgo_ at the beginning, so the main
   262  	// concern is other cgo wrappers for the same functions.
   263  	// Use the beginning of the md5 of the input to disambiguate.
   264  	h := md5.New()
   265  	for _, input := range goFiles {
   266  		if *srcDir != "" {
   267  			input = filepath.Join(*srcDir, input)
   268  		}
   269  		f, err := os.Open(input)
   270  		if err != nil {
   271  			fatalf("%s", err)
   272  		}
   273  		io.Copy(h, f)
   274  		f.Close()
   275  	}
   276  	cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
   277  
   278  	fs := make([]*File, len(goFiles))
   279  	for i, input := range goFiles {
   280  		if *srcDir != "" {
   281  			input = filepath.Join(*srcDir, input)
   282  		}
   283  		f := new(File)
   284  		f.ReadGo(input)
   285  		f.DiscardCgoDirectives()
   286  		fs[i] = f
   287  	}
   288  
   289  	if *objDir == "" {
   290  		// make sure that _obj directory exists, so that we can write
   291  		// all the output files there.
   292  		os.Mkdir("_obj", 0777)
   293  		*objDir = "_obj"
   294  	}
   295  	*objDir += string(filepath.Separator)
   296  
   297  	for i, input := range goFiles {
   298  		f := fs[i]
   299  		p.Translate(f)
   300  		for _, cref := range f.Ref {
   301  			switch cref.Context {
   302  			case "call", "call2":
   303  				if cref.Name.Kind != "type" {
   304  					break
   305  				}
   306  				*cref.Expr = cref.Name.Type.Go
   307  			}
   308  		}
   309  		if nerrors > 0 {
   310  			os.Exit(2)
   311  		}
   312  		p.PackagePath = f.Package
   313  		p.Record(f)
   314  		if *godefs {
   315  			os.Stdout.WriteString(p.godefs(f, input))
   316  		} else {
   317  			p.writeOutput(f, input)
   318  		}
   319  	}
   320  
   321  	if !*godefs {
   322  		p.writeDefs()
   323  	}
   324  	if nerrors > 0 {
   325  		os.Exit(2)
   326  	}
   327  }
   328  
   329  // newPackage returns a new Package that will invoke
   330  // gcc with the additional arguments specified in args.
   331  func newPackage(args []string) *Package {
   332  	goarch = runtime.GOARCH
   333  	if s := os.Getenv("GOARCH"); s != "" {
   334  		goarch = s
   335  	}
   336  	goos = runtime.GOOS
   337  	if s := os.Getenv("GOOS"); s != "" {
   338  		goos = s
   339  	}
   340  	ptrSize := ptrSizeMap[goarch]
   341  	if ptrSize == 0 {
   342  		fatalf("unknown ptrSize for $GOARCH %q", goarch)
   343  	}
   344  	intSize := intSizeMap[goarch]
   345  	if intSize == 0 {
   346  		fatalf("unknown intSize for $GOARCH %q", goarch)
   347  	}
   348  
   349  	// Reset locale variables so gcc emits English errors [sic].
   350  	os.Setenv("LANG", "en_US.UTF-8")
   351  	os.Setenv("LC_ALL", "C")
   352  
   353  	p := &Package{
   354  		PtrSize:  ptrSize,
   355  		IntSize:  intSize,
   356  		CgoFlags: make(map[string][]string),
   357  		Written:  make(map[string]bool),
   358  	}
   359  	p.addToFlag("CFLAGS", args)
   360  	return p
   361  }
   362  
   363  // Record what needs to be recorded about f.
   364  func (p *Package) Record(f *File) {
   365  	if p.PackageName == "" {
   366  		p.PackageName = f.Package
   367  	} else if p.PackageName != f.Package {
   368  		error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
   369  	}
   370  
   371  	if p.Name == nil {
   372  		p.Name = f.Name
   373  	} else {
   374  		for k, v := range f.Name {
   375  			if p.Name[k] == nil {
   376  				p.Name[k] = v
   377  			} else if !reflect.DeepEqual(p.Name[k], v) {
   378  				error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
   379  			}
   380  		}
   381  	}
   382  
   383  	if f.ExpFunc != nil {
   384  		p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
   385  		p.Preamble += "\n" + f.Preamble
   386  	}
   387  	p.Decl = append(p.Decl, f.AST.Decls...)
   388  }