github.com/prattmic/llgo-embedded@v0.0.0-20150820070356-41cfecea0e1e/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 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 "alpha": 8, 135 "amd64": 8, 136 "arm": 4, 137 "arm64": 8, 138 "m68k": 4, 139 "mipso32": 4, 140 "mipsn32": 4, 141 "mipso64": 8, 142 "mipsn64": 8, 143 "ppc": 4, 144 "ppc64": 8, 145 "ppc64le": 8, 146 "s390": 4, 147 "s390x": 8, 148 "sparc": 4, 149 "sparc64": 8, 150 } 151 152 var intSizeMap = map[string]int64{ 153 "386": 4, 154 "alpha": 8, 155 "amd64": 8, 156 "arm": 4, 157 "arm64": 8, 158 "m68k": 4, 159 "mipso32": 4, 160 "mipsn32": 4, 161 "mipso64": 8, 162 "mipsn64": 8, 163 "ppc": 4, 164 "ppc64": 8, 165 "ppc64le": 8, 166 "s390": 4, 167 "s390x": 8, 168 "sparc": 4, 169 "sparc64": 8, 170 } 171 172 var cPrefix string 173 174 var fset = token.NewFileSet() 175 176 var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file") 177 var dynout = flag.String("dynout", "", "write -dynobj output to this file") 178 var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in dynimport mode") 179 180 // These flags are for bootstrapping a new Go implementation, 181 // to generate Go and C headers 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 var cdefs = flag.Bool("cdefs", false, "for bootstrap: write C definitions for C file to standard output") 185 var objDir = flag.String("objdir", "", "object directory") 186 187 var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo") 188 var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo") 189 var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo") 190 var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code") 191 var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code") 192 var goarch, goos string 193 194 func main() { 195 flag.Usage = usage 196 flag.Parse() 197 198 if *dynobj != "" { 199 // cgo -dynimport is essentially a separate helper command 200 // built into the cgo binary. It scans a gcc-produced executable 201 // and dumps information about the imported symbols and the 202 // imported libraries. The 'go build' rules for cgo prepare an 203 // appropriate executable and then use its import information 204 // instead of needing to make the linkers duplicate all the 205 // specialized knowledge gcc has about where to look for imported 206 // symbols and which ones to use. 207 dynimport(*dynobj) 208 return 209 } 210 211 if *godefs && *cdefs { 212 fmt.Fprintf(os.Stderr, "cgo: cannot use -cdefs and -godefs together\n") 213 os.Exit(2) 214 } 215 216 if *godefs || *cdefs { 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 if *cdefs { 309 os.Stdout.WriteString(p.cdefs(f, input)) 310 } else { 311 p.writeOutput(f, input) 312 } 313 } 314 315 if !*godefs && !*cdefs { 316 p.writeDefs() 317 } 318 if nerrors > 0 { 319 os.Exit(2) 320 } 321 } 322 323 // newPackage returns a new Package that will invoke 324 // gcc with the additional arguments specified in args. 325 func newPackage(args []string) *Package { 326 goarch = runtime.GOARCH 327 if s := os.Getenv("GOARCH"); s != "" { 328 goarch = s 329 } 330 goos = runtime.GOOS 331 if s := os.Getenv("GOOS"); s != "" { 332 goos = s 333 } 334 ptrSize := ptrSizeMap[goarch] 335 if ptrSize == 0 { 336 fatalf("unknown ptrSize for $GOARCH %q", goarch) 337 } 338 intSize := intSizeMap[goarch] 339 if intSize == 0 { 340 fatalf("unknown intSize for $GOARCH %q", goarch) 341 } 342 343 // Reset locale variables so gcc emits English errors [sic]. 344 os.Setenv("LANG", "en_US.UTF-8") 345 os.Setenv("LC_ALL", "C") 346 347 p := &Package{ 348 PtrSize: ptrSize, 349 IntSize: intSize, 350 CgoFlags: make(map[string][]string), 351 Written: make(map[string]bool), 352 } 353 p.addToFlag("CFLAGS", args) 354 return p 355 } 356 357 // Record what needs to be recorded about f. 358 func (p *Package) Record(f *File) { 359 if p.PackageName == "" { 360 p.PackageName = f.Package 361 } else if p.PackageName != f.Package { 362 error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package) 363 } 364 365 if p.Name == nil { 366 p.Name = f.Name 367 } else { 368 for k, v := range f.Name { 369 if p.Name[k] == nil { 370 p.Name[k] = v 371 } else if !reflect.DeepEqual(p.Name[k], v) { 372 error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k)) 373 } 374 } 375 } 376 377 if f.ExpFunc != nil { 378 p.ExpFunc = append(p.ExpFunc, f.ExpFunc...) 379 p.Preamble += "\n" + f.Preamble 380 } 381 p.Decl = append(p.Decl, f.AST.Decls...) 382 }