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