github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/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  	"mips64":   8,
   147  	"mips64le": 8,
   148  	"ppc64":    8,
   149  	"ppc64le":  8,
   150  	"s390":     4,
   151  	"s390x":    8,
   152  }
   153  
   154  var intSizeMap = map[string]int64{
   155  	"386":      4,
   156  	"amd64":    8,
   157  	"arm":      4,
   158  	"arm64":    8,
   159  	"mips64":   8,
   160  	"mips64le": 8,
   161  	"ppc64":    8,
   162  	"ppc64le":  8,
   163  	"s390":     4,
   164  	"s390x":    8,
   165  }
   166  
   167  var cPrefix string
   168  
   169  var fset = token.NewFileSet()
   170  
   171  var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
   172  var dynout = flag.String("dynout", "", "write -dynimport output to this file")
   173  var dynpackage = flag.String("dynpackage", "main", "set Go package for -dynimport output")
   174  var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in -dynimport mode")
   175  
   176  // This flag is for bootstrapping a new Go implementation,
   177  // to generate Go types that match the data layout and
   178  // constant values used in the host's C libraries and system calls.
   179  var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
   180  
   181  var srcDir = flag.String("srcdir", "", "source directory")
   182  var objDir = flag.String("objdir", "", "object directory")
   183  var importPath = flag.String("importpath", "", "import path of package being built (for comments in generated files)")
   184  var exportHeader = flag.String("exportheader", "", "where to write export header if any exported functions")
   185  
   186  var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo")
   187  var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo")
   188  var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo")
   189  var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code")
   190  var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code")
   191  var goarch, goos string
   192  
   193  func main() {
   194  	flag.Usage = usage
   195  	flag.Parse()
   196  
   197  	if *dynobj != "" {
   198  		// cgo -dynimport is essentially a separate helper command
   199  		// built into the cgo binary. It scans a gcc-produced executable
   200  		// and dumps information about the imported symbols and the
   201  		// imported libraries. The 'go build' rules for cgo prepare an
   202  		// appropriate executable and then use its import information
   203  		// instead of needing to make the linkers duplicate all the
   204  		// specialized knowledge gcc has about where to look for imported
   205  		// symbols and which ones to use.
   206  		dynimport(*dynobj)
   207  		return
   208  	}
   209  
   210  	if *godefs {
   211  		// Generating definitions pulled from header files,
   212  		// to be checked into Go repositories.
   213  		// Line numbers are just noise.
   214  		conf.Mode &^= printer.SourcePos
   215  	}
   216  
   217  	args := flag.Args()
   218  	if len(args) < 1 {
   219  		usage()
   220  	}
   221  
   222  	// Find first arg that looks like a go file and assume everything before
   223  	// that are options to pass to gcc.
   224  	var i int
   225  	for i = len(args); i > 0; i-- {
   226  		if !strings.HasSuffix(args[i-1], ".go") {
   227  			break
   228  		}
   229  	}
   230  	if i == len(args) {
   231  		usage()
   232  	}
   233  
   234  	goFiles := args[i:]
   235  
   236  	for _, arg := range args[:i] {
   237  		if arg == "-fsanitize=thread" {
   238  			tsanProlog = yesTsanProlog
   239  		}
   240  	}
   241  
   242  	p := newPackage(args[:i])
   243  
   244  	// Record CGO_LDFLAGS from the environment for external linking.
   245  	if ldflags := os.Getenv("CGO_LDFLAGS"); ldflags != "" {
   246  		args, err := splitQuoted(ldflags)
   247  		if err != nil {
   248  			fatalf("bad CGO_LDFLAGS: %q (%s)", ldflags, err)
   249  		}
   250  		p.addToFlag("LDFLAGS", args)
   251  	}
   252  
   253  	// Need a unique prefix for the global C symbols that
   254  	// we use to coordinate between gcc and ourselves.
   255  	// We already put _cgo_ at the beginning, so the main
   256  	// concern is other cgo wrappers for the same functions.
   257  	// Use the beginning of the md5 of the input to disambiguate.
   258  	h := md5.New()
   259  	for _, input := range goFiles {
   260  		if *srcDir != "" {
   261  			input = filepath.Join(*srcDir, input)
   262  		}
   263  		f, err := os.Open(input)
   264  		if err != nil {
   265  			fatalf("%s", err)
   266  		}
   267  		io.Copy(h, f)
   268  		f.Close()
   269  	}
   270  	cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
   271  
   272  	fs := make([]*File, len(goFiles))
   273  	for i, input := range goFiles {
   274  		if *srcDir != "" {
   275  			input = filepath.Join(*srcDir, input)
   276  		}
   277  		f := new(File)
   278  		f.ReadGo(input)
   279  		f.DiscardCgoDirectives()
   280  		fs[i] = f
   281  	}
   282  
   283  	if *objDir == "" {
   284  		// make sure that _obj directory exists, so that we can write
   285  		// all the output files there.
   286  		os.Mkdir("_obj", 0777)
   287  		*objDir = "_obj"
   288  	}
   289  	*objDir += string(filepath.Separator)
   290  
   291  	for i, input := range goFiles {
   292  		f := fs[i]
   293  		p.Translate(f)
   294  		for _, cref := range f.Ref {
   295  			switch cref.Context {
   296  			case "call", "call2":
   297  				if cref.Name.Kind != "type" {
   298  					break
   299  				}
   300  				*cref.Expr = cref.Name.Type.Go
   301  			}
   302  		}
   303  		if nerrors > 0 {
   304  			os.Exit(2)
   305  		}
   306  		p.PackagePath = f.Package
   307  		p.Record(f)
   308  		if *godefs {
   309  			os.Stdout.WriteString(p.godefs(f, input))
   310  		} else {
   311  			p.writeOutput(f, input)
   312  		}
   313  	}
   314  
   315  	if !*godefs {
   316  		p.writeDefs()
   317  	}
   318  	if nerrors > 0 {
   319  		os.Exit(2)
   320  	}
   321  }
   322  
   323  // newPackage returns a new Package that will invoke
   324  // gcc with the additional arguments specified in args.
   325  func newPackage(args []string) *Package {
   326  	goarch = runtime.GOARCH
   327  	if s := os.Getenv("GOARCH"); s != "" {
   328  		goarch = s
   329  	}
   330  	goos = runtime.GOOS
   331  	if s := os.Getenv("GOOS"); s != "" {
   332  		goos = s
   333  	}
   334  	ptrSize := ptrSizeMap[goarch]
   335  	if ptrSize == 0 {
   336  		fatalf("unknown ptrSize for $GOARCH %q", goarch)
   337  	}
   338  	intSize := intSizeMap[goarch]
   339  	if intSize == 0 {
   340  		fatalf("unknown intSize for $GOARCH %q", goarch)
   341  	}
   342  
   343  	// Reset locale variables so gcc emits English errors [sic].
   344  	os.Setenv("LANG", "en_US.UTF-8")
   345  	os.Setenv("LC_ALL", "C")
   346  
   347  	p := &Package{
   348  		PtrSize:  ptrSize,
   349  		IntSize:  intSize,
   350  		CgoFlags: make(map[string][]string),
   351  		Written:  make(map[string]bool),
   352  	}
   353  	p.addToFlag("CFLAGS", args)
   354  	return p
   355  }
   356  
   357  // Record what needs to be recorded about f.
   358  func (p *Package) Record(f *File) {
   359  	if p.PackageName == "" {
   360  		p.PackageName = f.Package
   361  	} else if p.PackageName != f.Package {
   362  		error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
   363  	}
   364  
   365  	if p.Name == nil {
   366  		p.Name = f.Name
   367  	} else {
   368  		for k, v := range f.Name {
   369  			if p.Name[k] == nil {
   370  				p.Name[k] = v
   371  			} else if !reflect.DeepEqual(p.Name[k], v) {
   372  				error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
   373  			}
   374  		}
   375  	}
   376  
   377  	if f.ExpFunc != nil {
   378  		p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
   379  		p.Preamble += "\n" + f.Preamble
   380  	}
   381  	p.Decl = append(p.Decl, f.AST.Decls...)
   382  }