main.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. // Cgo; see gmp.go for an overview.
  5. // TODO(rsc):
  6. // Emit correct line number annotations.
  7. // Make 6g understand the annotations.
  8. package main
  9. import (
  10. "crypto/md5"
  11. "flag"
  12. "fmt"
  13. "go/ast"
  14. "go/printer"
  15. "go/token"
  16. "io"
  17. "os"
  18. "path/filepath"
  19. "reflect"
  20. "runtime"
  21. "sort"
  22. "strings"
  23. )
  24. // A Package collects information about the package we're going to write.
  25. type Package struct {
  26. PackageName string // name of package
  27. PackagePath string
  28. PtrSize int64
  29. IntSize int64
  30. GccOptions []string
  31. CgoFlags map[string][]string // #cgo flags (CFLAGS, LDFLAGS)
  32. Written map[string]bool
  33. Name map[string]*Name // accumulated Name from Files
  34. ExpFunc []*ExpFunc // accumulated ExpFunc from Files
  35. Decl []ast.Decl
  36. GoFiles []string // list of Go files
  37. GccFiles []string // list of gcc output files
  38. Preamble string // collected preamble for _cgo_export.h
  39. }
  40. // A File collects information about a single Go input file.
  41. type File struct {
  42. AST *ast.File // parsed AST
  43. Comments []*ast.CommentGroup // comments from file
  44. Package string // Package name
  45. Preamble string // C preamble (doc comment on import "C")
  46. Ref []*Ref // all references to C.xxx in AST
  47. ExpFunc []*ExpFunc // exported functions for this file
  48. Name map[string]*Name // map from Go name to Name
  49. }
  50. func nameKeys(m map[string]*Name) []string {
  51. var ks []string
  52. for k := range m {
  53. ks = append(ks, k)
  54. }
  55. sort.Strings(ks)
  56. return ks
  57. }
  58. // A Ref refers to an expression of the form C.xxx in the AST.
  59. type Ref struct {
  60. Name *Name
  61. Expr *ast.Expr
  62. Context string // "type", "expr", "call", or "call2"
  63. }
  64. func (r *Ref) Pos() token.Pos {
  65. return (*r.Expr).Pos()
  66. }
  67. // A Name collects information about C.xxx.
  68. type Name struct {
  69. Go string // name used in Go referring to package C
  70. Mangle string // name used in generated Go
  71. C string // name used in C
  72. Define string // #define expansion
  73. Kind string // "const", "type", "var", "fpvar", "func", "not-type"
  74. Type *Type // the type of xxx
  75. FuncType *FuncType
  76. AddError bool
  77. Const string // constant definition
  78. }
  79. // IsVar returns true if Kind is either "var" or "fpvar"
  80. func (n *Name) IsVar() bool {
  81. return n.Kind == "var" || n.Kind == "fpvar"
  82. }
  83. // A ExpFunc is an exported function, callable from C.
  84. // Such functions are identified in the Go input file
  85. // by doc comments containing the line //export ExpName
  86. type ExpFunc struct {
  87. Func *ast.FuncDecl
  88. ExpName string // name to use from C
  89. }
  90. // A TypeRepr contains the string representation of a type.
  91. type TypeRepr struct {
  92. Repr string
  93. FormatArgs []interface{}
  94. }
  95. // A Type collects information about a type in both the C and Go worlds.
  96. type Type struct {
  97. Size int64
  98. Align int64
  99. C *TypeRepr
  100. Go ast.Expr
  101. EnumValues map[string]int64
  102. Typedef string
  103. }
  104. // A FuncType collects information about a function type in both the C and Go worlds.
  105. type FuncType struct {
  106. Params []*Type
  107. Result *Type
  108. Go *ast.FuncType
  109. }
  110. func usage() {
  111. fmt.Fprint(os.Stderr, "usage: cgo -- [compiler options] file.go ...\n")
  112. flag.PrintDefaults()
  113. os.Exit(2)
  114. }
  115. var ptrSizeMap = map[string]int64{
  116. "386": 4,
  117. "alpha": 8,
  118. "amd64": 8,
  119. "arm": 4,
  120. "arm64": 8,
  121. "m68k": 4,
  122. "mipso32": 4,
  123. "mipsn32": 4,
  124. "mipso64": 8,
  125. "mipsn64": 8,
  126. "ppc": 4,
  127. "ppc64": 8,
  128. "ppc64le": 8,
  129. "s390": 4,
  130. "s390x": 8,
  131. "sparc": 4,
  132. "sparc64": 8,
  133. }
  134. var intSizeMap = 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. var cPrefix string
  154. var fset = token.NewFileSet()
  155. var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
  156. var dynout = flag.String("dynout", "", "write -dynobj output to this file")
  157. var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in dynimport mode")
  158. // These flags are for bootstrapping a new Go implementation,
  159. // to generate Go and C headers that match the data layout and
  160. // constant values used in the host's C libraries and system calls.
  161. var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
  162. var cdefs = flag.Bool("cdefs", false, "for bootstrap: write C definitions for C file to standard output")
  163. var objDir = flag.String("objdir", "", "object directory")
  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. func main() {
  171. flag.Usage = usage
  172. flag.Parse()
  173. if *dynobj != "" {
  174. // cgo -dynimport is essentially a separate helper command
  175. // built into the cgo binary. It scans a gcc-produced executable
  176. // and dumps information about the imported symbols and the
  177. // imported libraries. The 'go build' rules for cgo prepare an
  178. // appropriate executable and then use its import information
  179. // instead of needing to make the linkers duplicate all the
  180. // specialized knowledge gcc has about where to look for imported
  181. // symbols and which ones to use.
  182. dynimport(*dynobj)
  183. return
  184. }
  185. if *godefs && *cdefs {
  186. fmt.Fprintf(os.Stderr, "cgo: cannot use -cdefs and -godefs together\n")
  187. os.Exit(2)
  188. }
  189. if *godefs || *cdefs {
  190. // Generating definitions pulled from header files,
  191. // to be checked into Go repositories.
  192. // Line numbers are just noise.
  193. conf.Mode &^= printer.SourcePos
  194. }
  195. args := flag.Args()
  196. if len(args) < 1 {
  197. usage()
  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. goFiles := args[i:]
  211. p := newPackage(args[:i])
  212. // Record CGO_LDFLAGS from the environment for external linking.
  213. if ldflags := os.Getenv("CGO_LDFLAGS"); ldflags != "" {
  214. args, err := splitQuoted(ldflags)
  215. if err != nil {
  216. fatalf("bad CGO_LDFLAGS: %q (%s)", ldflags, err)
  217. }
  218. p.addToFlag("LDFLAGS", args)
  219. }
  220. // Need a unique prefix for the global C symbols that
  221. // we use to coordinate between gcc and ourselves.
  222. // We already put _cgo_ at the beginning, so the main
  223. // concern is other cgo wrappers for the same functions.
  224. // Use the beginning of the md5 of the input to disambiguate.
  225. h := md5.New()
  226. for _, input := range goFiles {
  227. f, err := os.Open(input)
  228. if err != nil {
  229. fatalf("%s", err)
  230. }
  231. io.Copy(h, f)
  232. f.Close()
  233. }
  234. cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
  235. fs := make([]*File, len(goFiles))
  236. for i, input := range goFiles {
  237. f := new(File)
  238. f.ReadGo(input)
  239. f.DiscardCgoDirectives()
  240. fs[i] = f
  241. }
  242. if *objDir == "" {
  243. // make sure that _obj directory exists, so that we can write
  244. // all the output files there.
  245. os.Mkdir("_obj", 0777)
  246. *objDir = "_obj"
  247. }
  248. *objDir += string(filepath.Separator)
  249. for i, input := range goFiles {
  250. f := fs[i]
  251. p.Translate(f)
  252. for _, cref := range f.Ref {
  253. switch cref.Context {
  254. case "call", "call2":
  255. if cref.Name.Kind != "type" {
  256. break
  257. }
  258. *cref.Expr = cref.Name.Type.Go
  259. }
  260. }
  261. if nerrors > 0 {
  262. os.Exit(2)
  263. }
  264. pkg := f.Package
  265. if dir := os.Getenv("CGOPKGPATH"); dir != "" {
  266. pkg = filepath.Join(dir, pkg)
  267. }
  268. p.PackagePath = pkg
  269. p.Record(f)
  270. if *godefs {
  271. os.Stdout.WriteString(p.godefs(f, input))
  272. } else if *cdefs {
  273. os.Stdout.WriteString(p.cdefs(f, input))
  274. } else {
  275. p.writeOutput(f, input)
  276. }
  277. }
  278. if !*godefs && !*cdefs {
  279. p.writeDefs()
  280. }
  281. if nerrors > 0 {
  282. os.Exit(2)
  283. }
  284. }
  285. // newPackage returns a new Package that will invoke
  286. // gcc with the additional arguments specified in args.
  287. func newPackage(args []string) *Package {
  288. goarch = runtime.GOARCH
  289. if s := os.Getenv("GOARCH"); s != "" {
  290. goarch = s
  291. }
  292. goos = runtime.GOOS
  293. if s := os.Getenv("GOOS"); s != "" {
  294. goos = s
  295. }
  296. ptrSize := ptrSizeMap[goarch]
  297. if ptrSize == 0 {
  298. fatalf("unknown ptrSize for $GOARCH %q", goarch)
  299. }
  300. intSize := intSizeMap[goarch]
  301. if intSize == 0 {
  302. fatalf("unknown intSize for $GOARCH %q", goarch)
  303. }
  304. // Reset locale variables so gcc emits English errors [sic].
  305. os.Setenv("LANG", "en_US.UTF-8")
  306. os.Setenv("LC_ALL", "C")
  307. p := &Package{
  308. PtrSize: ptrSize,
  309. IntSize: intSize,
  310. CgoFlags: make(map[string][]string),
  311. Written: make(map[string]bool),
  312. }
  313. p.addToFlag("CFLAGS", args)
  314. return p
  315. }
  316. // Record what needs to be recorded about f.
  317. func (p *Package) Record(f *File) {
  318. if p.PackageName == "" {
  319. p.PackageName = f.Package
  320. } else if p.PackageName != f.Package {
  321. error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
  322. }
  323. if p.Name == nil {
  324. p.Name = f.Name
  325. } else {
  326. for k, v := range f.Name {
  327. if p.Name[k] == nil {
  328. p.Name[k] = v
  329. } else if !reflect.DeepEqual(p.Name[k], v) {
  330. error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
  331. }
  332. }
  333. }
  334. if f.ExpFunc != nil {
  335. p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
  336. p.Preamble += "\n" + f.Preamble
  337. }
  338. p.Decl = append(p.Decl, f.AST.Decls...)
  339. }