github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/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 -dynobj output to this file")
   154  var dynpackage = flag.String("dynpackage", "main", "set Go package for dynobj 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 and C headers 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 cdefs = flag.Bool("cdefs", false, "for bootstrap: write C definitions for C file to standard output")
   162  var objDir = flag.String("objdir", "", "object directory")
   163  
   164  var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo")
   165  var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo")
   166  var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo")
   167  var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code")
   168  var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code")
   169  var goarch, goos string
   170  
   171  func main() {
   172  	flag.Usage = usage
   173  	flag.Parse()
   174  
   175  	if *dynobj != "" {
   176  		// cgo -dynimport is essentially a separate helper command
   177  		// built into the cgo binary.  It scans a gcc-produced executable
   178  		// and dumps information about the imported symbols and the
   179  		// imported libraries.  The 'go build' rules for cgo prepare an
   180  		// appropriate executable and then use its import information
   181  		// instead of needing to make the linkers duplicate all the
   182  		// specialized knowledge gcc has about where to look for imported
   183  		// symbols and which ones to use.
   184  		dynimport(*dynobj)
   185  		return
   186  	}
   187  
   188  	if *godefs && *cdefs {
   189  		fmt.Fprintf(os.Stderr, "cgo: cannot use -cdefs and -godefs together\n")
   190  		os.Exit(2)
   191  	}
   192  
   193  	if *godefs || *cdefs {
   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 if *cdefs {
   286  			os.Stdout.WriteString(p.cdefs(f, input))
   287  		} else {
   288  			p.writeOutput(f, input)
   289  		}
   290  	}
   291  
   292  	if !*godefs && !*cdefs {
   293  		p.writeDefs()
   294  	}
   295  	if nerrors > 0 {
   296  		os.Exit(2)
   297  	}
   298  }
   299  
   300  // newPackage returns a new Package that will invoke
   301  // gcc with the additional arguments specified in args.
   302  func newPackage(args []string) *Package {
   303  	goarch = runtime.GOARCH
   304  	if s := os.Getenv("GOARCH"); s != "" {
   305  		goarch = s
   306  	}
   307  	goos = runtime.GOOS
   308  	if s := os.Getenv("GOOS"); s != "" {
   309  		goos = s
   310  	}
   311  	ptrSize := ptrSizeMap[goarch]
   312  	if ptrSize == 0 {
   313  		fatalf("unknown ptrSize for $GOARCH %q", goarch)
   314  	}
   315  	intSize := intSizeMap[goarch]
   316  	if intSize == 0 {
   317  		fatalf("unknown intSize for $GOARCH %q", goarch)
   318  	}
   319  
   320  	// Reset locale variables so gcc emits English errors [sic].
   321  	os.Setenv("LANG", "en_US.UTF-8")
   322  	os.Setenv("LC_ALL", "C")
   323  
   324  	p := &Package{
   325  		PtrSize:  ptrSize,
   326  		IntSize:  intSize,
   327  		CgoFlags: make(map[string][]string),
   328  		Written:  make(map[string]bool),
   329  	}
   330  	p.addToFlag("CFLAGS", args)
   331  	return p
   332  }
   333  
   334  // Record what needs to be recorded about f.
   335  func (p *Package) Record(f *File) {
   336  	if p.PackageName == "" {
   337  		p.PackageName = f.Package
   338  	} else if p.PackageName != f.Package {
   339  		error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
   340  	}
   341  
   342  	if p.Name == nil {
   343  		p.Name = f.Name
   344  	} else {
   345  		for k, v := range f.Name {
   346  			if p.Name[k] == nil {
   347  				p.Name[k] = v
   348  			} else if !reflect.DeepEqual(p.Name[k], v) {
   349  				error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
   350  			}
   351  		}
   352  	}
   353  
   354  	if f.ExpFunc != nil {
   355  		p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
   356  		p.Preamble += "\n" + f.Preamble
   357  	}
   358  	p.Decl = append(p.Decl, f.AST.Decls...)
   359  }