github.com/axw/llgo@v0.0.0-20160805011314-95b5fe4dca20/third_party/gofrontend/libgo/go/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  	ExpFunc  []*ExpFunc          // exported functions for this file
    55  	Name     map[string]*Name    // map from Go name to Name
    56  }
    57  
    58  func nameKeys(m map[string]*Name) []string {
    59  	var ks []string
    60  	for k := range m {
    61  		ks = append(ks, k)
    62  	}
    63  	sort.Strings(ks)
    64  	return ks
    65  }
    66  
    67  // A Ref refers to an expression of the form C.xxx in the AST.
    68  type Ref struct {
    69  	Name    *Name
    70  	Expr    *ast.Expr
    71  	Context string // "type", "expr", "call", or "call2"
    72  }
    73  
    74  func (r *Ref) Pos() token.Pos {
    75  	return (*r.Expr).Pos()
    76  }
    77  
    78  // A Name collects information about C.xxx.
    79  type Name struct {
    80  	Go       string // name used in Go referring to package C
    81  	Mangle   string // name used in generated Go
    82  	C        string // name used in C
    83  	Define   string // #define expansion
    84  	Kind     string // "const", "type", "var", "fpvar", "func", "not-type"
    85  	Type     *Type  // the type of xxx
    86  	FuncType *FuncType
    87  	AddError bool
    88  	Const    string // constant definition
    89  }
    90  
    91  // IsVar reports whether Kind is either "var" or "fpvar"
    92  func (n *Name) IsVar() bool {
    93  	return n.Kind == "var" || n.Kind == "fpvar"
    94  }
    95  
    96  // A ExpFunc is an exported function, callable from C.
    97  // Such functions are identified in the Go input file
    98  // by doc comments containing the line //export ExpName
    99  type ExpFunc struct {
   100  	Func    *ast.FuncDecl
   101  	ExpName string // name to use from C
   102  	Doc     string
   103  }
   104  
   105  // A TypeRepr contains the string representation of a type.
   106  type TypeRepr struct {
   107  	Repr       string
   108  	FormatArgs []interface{}
   109  }
   110  
   111  // A Type collects information about a type in both the C and Go worlds.
   112  type Type struct {
   113  	Size       int64
   114  	Align      int64
   115  	C          *TypeRepr
   116  	Go         ast.Expr
   117  	EnumValues map[string]int64
   118  	Typedef    string
   119  }
   120  
   121  // A FuncType collects information about a function type in both the C and Go worlds.
   122  type FuncType struct {
   123  	Params []*Type
   124  	Result *Type
   125  	Go     *ast.FuncType
   126  }
   127  
   128  func usage() {
   129  	fmt.Fprint(os.Stderr, "usage: cgo -- [compiler options] file.go ...\n")
   130  	flag.PrintDefaults()
   131  	os.Exit(2)
   132  }
   133  
   134  var ptrSizeMap = map[string]int64{
   135  	"386":     4,
   136  	"alpha":   8,
   137  	"amd64":   8,
   138  	"arm":     4,
   139  	"arm64":   8,
   140  	"m68k":    4,
   141  	"mipso32": 4,
   142  	"mipsn32": 4,
   143  	"mipso64": 8,
   144  	"mipsn64": 8,
   145  	"ppc":     4,
   146  	"ppc64":   8,
   147  	"ppc64le": 8,
   148  	"s390":    4,
   149  	"s390x":   8,
   150  	"sparc":   4,
   151  	"sparc64": 8,
   152  }
   153  
   154  var intSizeMap = map[string]int64{
   155  	"386":     4,
   156  	"alpha":   8,
   157  	"amd64":   8,
   158  	"arm":     4,
   159  	"arm64":   8,
   160  	"m68k":    4,
   161  	"mipso32": 4,
   162  	"mipsn32": 4,
   163  	"mipso64": 8,
   164  	"mipsn64": 8,
   165  	"ppc":     4,
   166  	"ppc64":   8,
   167  	"ppc64le": 8,
   168  	"s390":    4,
   169  	"s390x":   8,
   170  	"sparc":   4,
   171  	"sparc64": 8,
   172  }
   173  
   174  var cPrefix string
   175  
   176  var fset = token.NewFileSet()
   177  
   178  var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
   179  var dynout = flag.String("dynout", "", "write -dynimport output to this file")
   180  var dynpackage = flag.String("dynpackage", "main", "set Go package for -dynimport output")
   181  var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in -dynimport mode")
   182  
   183  // This flag is for bootstrapping a new Go implementation,
   184  // to generate Go types that match the data layout and
   185  // constant values used in the host's C libraries and system calls.
   186  var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
   187  
   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  	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  		f, err := os.Open(input)
   261  		if err != nil {
   262  			fatalf("%s", err)
   263  		}
   264  		io.Copy(h, f)
   265  		f.Close()
   266  	}
   267  	cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
   268  
   269  	fs := make([]*File, len(goFiles))
   270  	for i, input := range goFiles {
   271  		f := new(File)
   272  		f.ReadGo(input)
   273  		f.DiscardCgoDirectives()
   274  		fs[i] = f
   275  	}
   276  
   277  	if *objDir == "" {
   278  		// make sure that _obj directory exists, so that we can write
   279  		// all the output files there.
   280  		os.Mkdir("_obj", 0777)
   281  		*objDir = "_obj"
   282  	}
   283  	*objDir += string(filepath.Separator)
   284  
   285  	for i, input := range goFiles {
   286  		f := fs[i]
   287  		p.Translate(f)
   288  		for _, cref := range f.Ref {
   289  			switch cref.Context {
   290  			case "call", "call2":
   291  				if cref.Name.Kind != "type" {
   292  					break
   293  				}
   294  				*cref.Expr = cref.Name.Type.Go
   295  			}
   296  		}
   297  		if nerrors > 0 {
   298  			os.Exit(2)
   299  		}
   300  		pkg := f.Package
   301  		if dir := os.Getenv("CGOPKGPATH"); dir != "" {
   302  			pkg = filepath.Join(dir, pkg)
   303  		}
   304  		p.PackagePath = pkg
   305  		p.Record(f)
   306  		if *godefs {
   307  			os.Stdout.WriteString(p.godefs(f, input))
   308  		} else {
   309  			p.writeOutput(f, input)
   310  		}
   311  	}
   312  
   313  	if !*godefs {
   314  		p.writeDefs()
   315  	}
   316  	if nerrors > 0 {
   317  		os.Exit(2)
   318  	}
   319  }
   320  
   321  // newPackage returns a new Package that will invoke
   322  // gcc with the additional arguments specified in args.
   323  func newPackage(args []string) *Package {
   324  	goarch = runtime.GOARCH
   325  	if s := os.Getenv("GOARCH"); s != "" {
   326  		goarch = s
   327  	}
   328  	goos = runtime.GOOS
   329  	if s := os.Getenv("GOOS"); s != "" {
   330  		goos = s
   331  	}
   332  	ptrSize := ptrSizeMap[goarch]
   333  	if ptrSize == 0 {
   334  		fatalf("unknown ptrSize for $GOARCH %q", goarch)
   335  	}
   336  	intSize := intSizeMap[goarch]
   337  	if intSize == 0 {
   338  		fatalf("unknown intSize for $GOARCH %q", goarch)
   339  	}
   340  
   341  	// Reset locale variables so gcc emits English errors [sic].
   342  	os.Setenv("LANG", "en_US.UTF-8")
   343  	os.Setenv("LC_ALL", "C")
   344  
   345  	p := &Package{
   346  		PtrSize:  ptrSize,
   347  		IntSize:  intSize,
   348  		CgoFlags: make(map[string][]string),
   349  		Written:  make(map[string]bool),
   350  	}
   351  	p.addToFlag("CFLAGS", args)
   352  	return p
   353  }
   354  
   355  // Record what needs to be recorded about f.
   356  func (p *Package) Record(f *File) {
   357  	if p.PackageName == "" {
   358  		p.PackageName = f.Package
   359  	} else if p.PackageName != f.Package {
   360  		error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
   361  	}
   362  
   363  	if p.Name == nil {
   364  		p.Name = f.Name
   365  	} else {
   366  		for k, v := range f.Name {
   367  			if p.Name[k] == nil {
   368  				p.Name[k] = v
   369  			} else if !reflect.DeepEqual(p.Name[k], v) {
   370  				error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
   371  			}
   372  		}
   373  	}
   374  
   375  	if f.ExpFunc != nil {
   376  		p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
   377  		p.Preamble += "\n" + f.Preamble
   378  	}
   379  	p.Decl = append(p.Decl, f.AST.Decls...)
   380  }