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