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