...
Run Format

Source file src/cmd/cgo/gcc.go

Documentation: cmd/cgo

     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  // Annotate Ref in Prog with C types by parsing gcc debug output.
     6  // Conversion of debug output to Go types.
     7  
     8  package main
     9  
    10  import (
    11  	"bytes"
    12  	"debug/dwarf"
    13  	"debug/elf"
    14  	"debug/macho"
    15  	"debug/pe"
    16  	"encoding/binary"
    17  	"errors"
    18  	"flag"
    19  	"fmt"
    20  	"go/ast"
    21  	"go/parser"
    22  	"go/token"
    23  	"math"
    24  	"os"
    25  	"strconv"
    26  	"strings"
    27  	"unicode"
    28  	"unicode/utf8"
    29  )
    30  
    31  var debugDefine = flag.Bool("debug-define", false, "print relevant #defines")
    32  var debugGcc = flag.Bool("debug-gcc", false, "print gcc invocations")
    33  
    34  var nameToC = map[string]string{
    35  	"schar":         "signed char",
    36  	"uchar":         "unsigned char",
    37  	"ushort":        "unsigned short",
    38  	"uint":          "unsigned int",
    39  	"ulong":         "unsigned long",
    40  	"longlong":      "long long",
    41  	"ulonglong":     "unsigned long long",
    42  	"complexfloat":  "float _Complex",
    43  	"complexdouble": "double _Complex",
    44  }
    45  
    46  // cname returns the C name to use for C.s.
    47  // The expansions are listed in nameToC and also
    48  // struct_foo becomes "struct foo", and similarly for
    49  // union and enum.
    50  func cname(s string) string {
    51  	if t, ok := nameToC[s]; ok {
    52  		return t
    53  	}
    54  
    55  	if strings.HasPrefix(s, "struct_") {
    56  		return "struct " + s[len("struct_"):]
    57  	}
    58  	if strings.HasPrefix(s, "union_") {
    59  		return "union " + s[len("union_"):]
    60  	}
    61  	if strings.HasPrefix(s, "enum_") {
    62  		return "enum " + s[len("enum_"):]
    63  	}
    64  	if strings.HasPrefix(s, "sizeof_") {
    65  		return "sizeof(" + cname(s[len("sizeof_"):]) + ")"
    66  	}
    67  	return s
    68  }
    69  
    70  // DiscardCgoDirectives processes the import C preamble, and discards
    71  // all #cgo CFLAGS and LDFLAGS directives, so they don't make their
    72  // way into _cgo_export.h.
    73  func (f *File) DiscardCgoDirectives() {
    74  	linesIn := strings.Split(f.Preamble, "\n")
    75  	linesOut := make([]string, 0, len(linesIn))
    76  	for _, line := range linesIn {
    77  		l := strings.TrimSpace(line)
    78  		if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(rune(l[4])) {
    79  			linesOut = append(linesOut, line)
    80  		} else {
    81  			linesOut = append(linesOut, "")
    82  		}
    83  	}
    84  	f.Preamble = strings.Join(linesOut, "\n")
    85  }
    86  
    87  // addToFlag appends args to flag. All flags are later written out onto the
    88  // _cgo_flags file for the build system to use.
    89  func (p *Package) addToFlag(flag string, args []string) {
    90  	p.CgoFlags[flag] = append(p.CgoFlags[flag], args...)
    91  	if flag == "CFLAGS" {
    92  		// We'll also need these when preprocessing for dwarf information.
    93  		p.GccOptions = append(p.GccOptions, args...)
    94  	}
    95  }
    96  
    97  // splitQuoted splits the string s around each instance of one or more consecutive
    98  // white space characters while taking into account quotes and escaping, and
    99  // returns an array of substrings of s or an empty list if s contains only white space.
   100  // Single quotes and double quotes are recognized to prevent splitting within the
   101  // quoted region, and are removed from the resulting substrings. If a quote in s
   102  // isn't closed err will be set and r will have the unclosed argument as the
   103  // last element. The backslash is used for escaping.
   104  //
   105  // For example, the following string:
   106  //
   107  //     `a b:"c d" 'e''f'  "g\""`
   108  //
   109  // Would be parsed as:
   110  //
   111  //     []string{"a", "b:c d", "ef", `g"`}
   112  //
   113  func splitQuoted(s string) (r []string, err error) {
   114  	var args []string
   115  	arg := make([]rune, len(s))
   116  	escaped := false
   117  	quoted := false
   118  	quote := '\x00'
   119  	i := 0
   120  	for _, r := range s {
   121  		switch {
   122  		case escaped:
   123  			escaped = false
   124  		case r == '\\':
   125  			escaped = true
   126  			continue
   127  		case quote != 0:
   128  			if r == quote {
   129  				quote = 0
   130  				continue
   131  			}
   132  		case r == '"' || r == '\'':
   133  			quoted = true
   134  			quote = r
   135  			continue
   136  		case unicode.IsSpace(r):
   137  			if quoted || i > 0 {
   138  				quoted = false
   139  				args = append(args, string(arg[:i]))
   140  				i = 0
   141  			}
   142  			continue
   143  		}
   144  		arg[i] = r
   145  		i++
   146  	}
   147  	if quoted || i > 0 {
   148  		args = append(args, string(arg[:i]))
   149  	}
   150  	if quote != 0 {
   151  		err = errors.New("unclosed quote")
   152  	} else if escaped {
   153  		err = errors.New("unfinished escaping")
   154  	}
   155  	return args, err
   156  }
   157  
   158  // Translate rewrites f.AST, the original Go input, to remove
   159  // references to the imported package C, replacing them with
   160  // references to the equivalent Go types, functions, and variables.
   161  func (p *Package) Translate(f *File) {
   162  	for _, cref := range f.Ref {
   163  		// Convert C.ulong to C.unsigned long, etc.
   164  		cref.Name.C = cname(cref.Name.Go)
   165  	}
   166  	p.loadDefines(f)
   167  	p.typedefs = map[string]bool{}
   168  	p.typedefList = nil
   169  	numTypedefs := -1
   170  	for len(p.typedefs) > numTypedefs {
   171  		numTypedefs = len(p.typedefs)
   172  		// Also ask about any typedefs we've seen so far.
   173  		for _, a := range p.typedefList {
   174  			f.Name[a] = &Name{
   175  				Go: a,
   176  				C:  a,
   177  			}
   178  		}
   179  		needType := p.guessKinds(f)
   180  		if len(needType) > 0 {
   181  			p.loadDWARF(f, needType)
   182  		}
   183  
   184  		// In godefs mode we're OK with the typedefs, which
   185  		// will presumably also be defined in the file, we
   186  		// don't want to resolve them to their base types.
   187  		if *godefs {
   188  			break
   189  		}
   190  	}
   191  	if p.rewriteCalls(f) {
   192  		// Add `import _cgo_unsafe "unsafe"` after the package statement.
   193  		f.Edit.Insert(f.offset(f.AST.Name.End()), "; import _cgo_unsafe \"unsafe\"")
   194  	}
   195  	p.rewriteRef(f)
   196  }
   197  
   198  // loadDefines coerces gcc into spitting out the #defines in use
   199  // in the file f and saves relevant renamings in f.Name[name].Define.
   200  func (p *Package) loadDefines(f *File) {
   201  	var b bytes.Buffer
   202  	b.WriteString(builtinProlog)
   203  	b.WriteString(f.Preamble)
   204  	stdout := p.gccDefines(b.Bytes())
   205  
   206  	for _, line := range strings.Split(stdout, "\n") {
   207  		if len(line) < 9 || line[0:7] != "#define" {
   208  			continue
   209  		}
   210  
   211  		line = strings.TrimSpace(line[8:])
   212  
   213  		var key, val string
   214  		spaceIndex := strings.Index(line, " ")
   215  		tabIndex := strings.Index(line, "\t")
   216  
   217  		if spaceIndex == -1 && tabIndex == -1 {
   218  			continue
   219  		} else if tabIndex == -1 || (spaceIndex != -1 && spaceIndex < tabIndex) {
   220  			key = line[0:spaceIndex]
   221  			val = strings.TrimSpace(line[spaceIndex:])
   222  		} else {
   223  			key = line[0:tabIndex]
   224  			val = strings.TrimSpace(line[tabIndex:])
   225  		}
   226  
   227  		if key == "__clang__" {
   228  			p.GccIsClang = true
   229  		}
   230  
   231  		if n := f.Name[key]; n != nil {
   232  			if *debugDefine {
   233  				fmt.Fprintf(os.Stderr, "#define %s %s\n", key, val)
   234  			}
   235  			n.Define = val
   236  		}
   237  	}
   238  }
   239  
   240  // guessKinds tricks gcc into revealing the kind of each
   241  // name xxx for the references C.xxx in the Go input.
   242  // The kind is either a constant, type, or variable.
   243  func (p *Package) guessKinds(f *File) []*Name {
   244  	// Determine kinds for names we already know about,
   245  	// like #defines or 'struct foo', before bothering with gcc.
   246  	var names, needType []*Name
   247  	optional := map[*Name]bool{}
   248  	for _, key := range nameKeys(f.Name) {
   249  		n := f.Name[key]
   250  		// If we've already found this name as a #define
   251  		// and we can translate it as a constant value, do so.
   252  		if n.Define != "" {
   253  			if i, err := strconv.ParseInt(n.Define, 0, 64); err == nil {
   254  				n.Kind = "iconst"
   255  				// Turn decimal into hex, just for consistency
   256  				// with enum-derived constants. Otherwise
   257  				// in the cgo -godefs output half the constants
   258  				// are in hex and half are in whatever the #define used.
   259  				n.Const = fmt.Sprintf("%#x", i)
   260  			} else if n.Define[0] == '\'' {
   261  				if _, err := parser.ParseExpr(n.Define); err == nil {
   262  					n.Kind = "iconst"
   263  					n.Const = n.Define
   264  				}
   265  			} else if n.Define[0] == '"' {
   266  				if _, err := parser.ParseExpr(n.Define); err == nil {
   267  					n.Kind = "sconst"
   268  					n.Const = n.Define
   269  				}
   270  			}
   271  
   272  			if n.IsConst() {
   273  				continue
   274  			}
   275  		}
   276  
   277  		// If this is a struct, union, or enum type name, no need to guess the kind.
   278  		if strings.HasPrefix(n.C, "struct ") || strings.HasPrefix(n.C, "union ") || strings.HasPrefix(n.C, "enum ") {
   279  			n.Kind = "type"
   280  			needType = append(needType, n)
   281  			continue
   282  		}
   283  
   284  		if goos == "darwin" && strings.HasSuffix(n.C, "Ref") {
   285  			// For FooRef, find out if FooGetTypeID exists.
   286  			s := n.C[:len(n.C)-3] + "GetTypeID"
   287  			n := &Name{Go: s, C: s}
   288  			names = append(names, n)
   289  			optional[n] = true
   290  		}
   291  
   292  		// Otherwise, we'll need to find out from gcc.
   293  		names = append(names, n)
   294  	}
   295  
   296  	// Bypass gcc if there's nothing left to find out.
   297  	if len(names) == 0 {
   298  		return needType
   299  	}
   300  
   301  	// Coerce gcc into telling us whether each name is a type, a value, or undeclared.
   302  	// For names, find out whether they are integer constants.
   303  	// We used to look at specific warning or error messages here, but that tied the
   304  	// behavior too closely to specific versions of the compilers.
   305  	// Instead, arrange that we can infer what we need from only the presence or absence
   306  	// of an error on a specific line.
   307  	//
   308  	// For each name, we generate these lines, where xxx is the index in toSniff plus one.
   309  	//
   310  	//	#line xxx "not-declared"
   311  	//	void __cgo_f_xxx_1(void) { __typeof__(name) *__cgo_undefined__1; }
   312  	//	#line xxx "not-type"
   313  	//	void __cgo_f_xxx_2(void) { name *__cgo_undefined__2; }
   314  	//	#line xxx "not-int-const"
   315  	//	void __cgo_f_xxx_3(void) { enum { __cgo_undefined__3 = (name)*1 }; }
   316  	//	#line xxx "not-num-const"
   317  	//	void __cgo_f_xxx_4(void) { static const double __cgo_undefined__4 = (name); }
   318  	//	#line xxx "not-str-lit"
   319  	//	void __cgo_f_xxx_5(void) { static const char __cgo_undefined__5[] = (name); }
   320  	//
   321  	// If we see an error at not-declared:xxx, the corresponding name is not declared.
   322  	// If we see an error at not-type:xxx, the corresponding name is a type.
   323  	// If we see an error at not-int-const:xxx, the corresponding name is not an integer constant.
   324  	// If we see an error at not-num-const:xxx, the corresponding name is not a number constant.
   325  	// If we see an error at not-str-lit:xxx, the corresponding name is not a string literal.
   326  	//
   327  	// The specific input forms are chosen so that they are valid C syntax regardless of
   328  	// whether name denotes a type or an expression.
   329  
   330  	var b bytes.Buffer
   331  	b.WriteString(builtinProlog)
   332  	b.WriteString(f.Preamble)
   333  
   334  	for i, n := range names {
   335  		fmt.Fprintf(&b, "#line %d \"not-declared\"\n"+
   336  			"void __cgo_f_%d_1(void) { __typeof__(%s) *__cgo_undefined__1; }\n"+
   337  			"#line %d \"not-type\"\n"+
   338  			"void __cgo_f_%d_2(void) { %s *__cgo_undefined__2; }\n"+
   339  			"#line %d \"not-int-const\"\n"+
   340  			"void __cgo_f_%d_3(void) { enum { __cgo_undefined__3 = (%s)*1 }; }\n"+
   341  			"#line %d \"not-num-const\"\n"+
   342  			"void __cgo_f_%d_4(void) { static const double __cgo_undefined__4 = (%s); }\n"+
   343  			"#line %d \"not-str-lit\"\n"+
   344  			"void __cgo_f_%d_5(void) { static const char __cgo_undefined__5[] = (%s); }\n",
   345  			i+1, i+1, n.C,
   346  			i+1, i+1, n.C,
   347  			i+1, i+1, n.C,
   348  			i+1, i+1, n.C,
   349  			i+1, i+1, n.C,
   350  		)
   351  	}
   352  	fmt.Fprintf(&b, "#line 1 \"completed\"\n"+
   353  		"int __cgo__1 = __cgo__2;\n")
   354  
   355  	stderr := p.gccErrors(b.Bytes())
   356  	if stderr == "" {
   357  		fatalf("%s produced no output\non input:\n%s", p.gccBaseCmd()[0], b.Bytes())
   358  	}
   359  
   360  	completed := false
   361  	sniff := make([]int, len(names))
   362  	const (
   363  		notType = 1 << iota
   364  		notIntConst
   365  		notNumConst
   366  		notStrLiteral
   367  		notDeclared
   368  	)
   369  	sawUnmatchedErrors := false
   370  	for _, line := range strings.Split(stderr, "\n") {
   371  		// Ignore warnings and random comments, with one
   372  		// exception: newer GCC versions will sometimes emit
   373  		// an error on a macro #define with a note referring
   374  		// to where the expansion occurs. We care about where
   375  		// the expansion occurs, so in that case treat the note
   376  		// as an error.
   377  		isError := strings.Contains(line, ": error:")
   378  		isErrorNote := strings.Contains(line, ": note:") && sawUnmatchedErrors
   379  		if !isError && !isErrorNote {
   380  			continue
   381  		}
   382  
   383  		c1 := strings.Index(line, ":")
   384  		if c1 < 0 {
   385  			continue
   386  		}
   387  		c2 := strings.Index(line[c1+1:], ":")
   388  		if c2 < 0 {
   389  			continue
   390  		}
   391  		c2 += c1 + 1
   392  
   393  		filename := line[:c1]
   394  		i, _ := strconv.Atoi(line[c1+1 : c2])
   395  		i--
   396  		if i < 0 || i >= len(names) {
   397  			if isError {
   398  				sawUnmatchedErrors = true
   399  			}
   400  			continue
   401  		}
   402  
   403  		switch filename {
   404  		case "completed":
   405  			// Strictly speaking, there is no guarantee that seeing the error at completed:1
   406  			// (at the end of the file) means we've seen all the errors from earlier in the file,
   407  			// but usually it does. Certainly if we don't see the completed:1 error, we did
   408  			// not get all the errors we expected.
   409  			completed = true
   410  
   411  		case "not-declared":
   412  			sniff[i] |= notDeclared
   413  		case "not-type":
   414  			sniff[i] |= notType
   415  		case "not-int-const":
   416  			sniff[i] |= notIntConst
   417  		case "not-num-const":
   418  			sniff[i] |= notNumConst
   419  		case "not-str-lit":
   420  			sniff[i] |= notStrLiteral
   421  		default:
   422  			if isError {
   423  				sawUnmatchedErrors = true
   424  			}
   425  			continue
   426  		}
   427  
   428  		sawUnmatchedErrors = false
   429  	}
   430  
   431  	if !completed {
   432  		fatalf("%s did not produce error at completed:1\non input:\n%s\nfull error output:\n%s", p.gccBaseCmd()[0], b.Bytes(), stderr)
   433  	}
   434  
   435  	for i, n := range names {
   436  		switch sniff[i] {
   437  		default:
   438  			if sniff[i]&notDeclared != 0 && optional[n] {
   439  				// Ignore optional undeclared identifiers.
   440  				// Don't report an error, and skip adding n to the needType array.
   441  				continue
   442  			}
   443  			error_(f.NamePos[n], "could not determine kind of name for C.%s", fixGo(n.Go))
   444  		case notStrLiteral | notType:
   445  			n.Kind = "iconst"
   446  		case notIntConst | notStrLiteral | notType:
   447  			n.Kind = "fconst"
   448  		case notIntConst | notNumConst | notType:
   449  			n.Kind = "sconst"
   450  		case notIntConst | notNumConst | notStrLiteral:
   451  			n.Kind = "type"
   452  		case notIntConst | notNumConst | notStrLiteral | notType:
   453  			n.Kind = "not-type"
   454  		}
   455  		needType = append(needType, n)
   456  	}
   457  	if nerrors > 0 {
   458  		// Check if compiling the preamble by itself causes any errors,
   459  		// because the messages we've printed out so far aren't helpful
   460  		// to users debugging preamble mistakes. See issue 8442.
   461  		preambleErrors := p.gccErrors([]byte(f.Preamble))
   462  		if len(preambleErrors) > 0 {
   463  			error_(token.NoPos, "\n%s errors for preamble:\n%s", p.gccBaseCmd()[0], preambleErrors)
   464  		}
   465  
   466  		fatalf("unresolved names")
   467  	}
   468  
   469  	return needType
   470  }
   471  
   472  // loadDWARF parses the DWARF debug information generated
   473  // by gcc to learn the details of the constants, variables, and types
   474  // being referred to as C.xxx.
   475  func (p *Package) loadDWARF(f *File, names []*Name) {
   476  	// Extract the types from the DWARF section of an object
   477  	// from a well-formed C program. Gcc only generates DWARF info
   478  	// for symbols in the object file, so it is not enough to print the
   479  	// preamble and hope the symbols we care about will be there.
   480  	// Instead, emit
   481  	//	__typeof__(names[i]) *__cgo__i;
   482  	// for each entry in names and then dereference the type we
   483  	// learn for __cgo__i.
   484  	var b bytes.Buffer
   485  	b.WriteString(builtinProlog)
   486  	b.WriteString(f.Preamble)
   487  	b.WriteString("#line 1 \"cgo-dwarf-inference\"\n")
   488  	for i, n := range names {
   489  		fmt.Fprintf(&b, "__typeof__(%s) *__cgo__%d;\n", n.C, i)
   490  		if n.Kind == "iconst" {
   491  			fmt.Fprintf(&b, "enum { __cgo_enum__%d = %s };\n", i, n.C)
   492  		}
   493  	}
   494  
   495  	// We create a data block initialized with the values,
   496  	// so we can read them out of the object file.
   497  	fmt.Fprintf(&b, "long long __cgodebug_ints[] = {\n")
   498  	for _, n := range names {
   499  		if n.Kind == "iconst" {
   500  			fmt.Fprintf(&b, "\t%s,\n", n.C)
   501  		} else {
   502  			fmt.Fprintf(&b, "\t0,\n")
   503  		}
   504  	}
   505  	// for the last entry, we cannot use 0, otherwise
   506  	// in case all __cgodebug_data is zero initialized,
   507  	// LLVM-based gcc will place the it in the __DATA.__common
   508  	// zero-filled section (our debug/macho doesn't support
   509  	// this)
   510  	fmt.Fprintf(&b, "\t1\n")
   511  	fmt.Fprintf(&b, "};\n")
   512  
   513  	// do the same work for floats.
   514  	fmt.Fprintf(&b, "double __cgodebug_floats[] = {\n")
   515  	for _, n := range names {
   516  		if n.Kind == "fconst" {
   517  			fmt.Fprintf(&b, "\t%s,\n", n.C)
   518  		} else {
   519  			fmt.Fprintf(&b, "\t0,\n")
   520  		}
   521  	}
   522  	fmt.Fprintf(&b, "\t1\n")
   523  	fmt.Fprintf(&b, "};\n")
   524  
   525  	// do the same work for strings.
   526  	for i, n := range names {
   527  		if n.Kind == "sconst" {
   528  			fmt.Fprintf(&b, "const char __cgodebug_str__%d[] = %s;\n", i, n.C)
   529  			fmt.Fprintf(&b, "const unsigned long long __cgodebug_strlen__%d = sizeof(%s)-1;\n", i, n.C)
   530  		}
   531  	}
   532  
   533  	d, ints, floats, strs := p.gccDebug(b.Bytes(), len(names))
   534  
   535  	// Scan DWARF info for top-level TagVariable entries with AttrName __cgo__i.
   536  	types := make([]dwarf.Type, len(names))
   537  	r := d.Reader()
   538  	for {
   539  		e, err := r.Next()
   540  		if err != nil {
   541  			fatalf("reading DWARF entry: %s", err)
   542  		}
   543  		if e == nil {
   544  			break
   545  		}
   546  		switch e.Tag {
   547  		case dwarf.TagVariable:
   548  			name, _ := e.Val(dwarf.AttrName).(string)
   549  			typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset)
   550  			if name == "" || typOff == 0 {
   551  				if e.Val(dwarf.AttrSpecification) != nil {
   552  					// Since we are reading all the DWARF,
   553  					// assume we will see the variable elsewhere.
   554  					break
   555  				}
   556  				fatalf("malformed DWARF TagVariable entry")
   557  			}
   558  			if !strings.HasPrefix(name, "__cgo__") {
   559  				break
   560  			}
   561  			typ, err := d.Type(typOff)
   562  			if err != nil {
   563  				fatalf("loading DWARF type: %s", err)
   564  			}
   565  			t, ok := typ.(*dwarf.PtrType)
   566  			if !ok || t == nil {
   567  				fatalf("internal error: %s has non-pointer type", name)
   568  			}
   569  			i, err := strconv.Atoi(name[7:])
   570  			if err != nil {
   571  				fatalf("malformed __cgo__ name: %s", name)
   572  			}
   573  			types[i] = t.Type
   574  			p.recordTypedefs(t.Type)
   575  		}
   576  		if e.Tag != dwarf.TagCompileUnit {
   577  			r.SkipChildren()
   578  		}
   579  	}
   580  
   581  	// Record types and typedef information.
   582  	var conv typeConv
   583  	conv.Init(p.PtrSize, p.IntSize)
   584  	for i, n := range names {
   585  		if strings.HasSuffix(n.Go, "GetTypeID") && types[i].String() == "func() CFTypeID" {
   586  			conv.getTypeIDs[n.Go[:len(n.Go)-9]] = true
   587  		}
   588  	}
   589  	for i, n := range names {
   590  		if types[i] == nil {
   591  			continue
   592  		}
   593  		pos := f.NamePos[n]
   594  		f, fok := types[i].(*dwarf.FuncType)
   595  		if n.Kind != "type" && fok {
   596  			n.Kind = "func"
   597  			n.FuncType = conv.FuncType(f, pos)
   598  		} else {
   599  			n.Type = conv.Type(types[i], pos)
   600  			switch n.Kind {
   601  			case "iconst":
   602  				if i < len(ints) {
   603  					if _, ok := types[i].(*dwarf.UintType); ok {
   604  						n.Const = fmt.Sprintf("%#x", uint64(ints[i]))
   605  					} else {
   606  						n.Const = fmt.Sprintf("%#x", ints[i])
   607  					}
   608  				}
   609  			case "fconst":
   610  				if i >= len(floats) {
   611  					break
   612  				}
   613  				switch base(types[i]).(type) {
   614  				case *dwarf.IntType, *dwarf.UintType:
   615  					// This has an integer type so it's
   616  					// not really a floating point
   617  					// constant. This can happen when the
   618  					// C compiler complains about using
   619  					// the value as an integer constant,
   620  					// but not as a general constant.
   621  					// Treat this as a variable of the
   622  					// appropriate type, not a constant,
   623  					// to get C-style type handling,
   624  					// avoiding the problem that C permits
   625  					// uint64(-1) but Go does not.
   626  					// See issue 26066.
   627  					n.Kind = "var"
   628  				default:
   629  					n.Const = fmt.Sprintf("%f", floats[i])
   630  				}
   631  			case "sconst":
   632  				if i < len(strs) {
   633  					n.Const = fmt.Sprintf("%q", strs[i])
   634  				}
   635  			}
   636  		}
   637  		conv.FinishType(pos)
   638  	}
   639  }
   640  
   641  // recordTypedefs remembers in p.typedefs all the typedefs used in dtypes and its children.
   642  func (p *Package) recordTypedefs(dtype dwarf.Type) {
   643  	p.recordTypedefs1(dtype, map[dwarf.Type]bool{})
   644  }
   645  func (p *Package) recordTypedefs1(dtype dwarf.Type, visited map[dwarf.Type]bool) {
   646  	if dtype == nil {
   647  		return
   648  	}
   649  	if visited[dtype] {
   650  		return
   651  	}
   652  	visited[dtype] = true
   653  	switch dt := dtype.(type) {
   654  	case *dwarf.TypedefType:
   655  		if strings.HasPrefix(dt.Name, "__builtin") {
   656  			// Don't look inside builtin types. There be dragons.
   657  			return
   658  		}
   659  		if !p.typedefs[dt.Name] {
   660  			p.typedefs[dt.Name] = true
   661  			p.typedefList = append(p.typedefList, dt.Name)
   662  			p.recordTypedefs1(dt.Type, visited)
   663  		}
   664  	case *dwarf.PtrType:
   665  		p.recordTypedefs1(dt.Type, visited)
   666  	case *dwarf.ArrayType:
   667  		p.recordTypedefs1(dt.Type, visited)
   668  	case *dwarf.QualType:
   669  		p.recordTypedefs1(dt.Type, visited)
   670  	case *dwarf.FuncType:
   671  		p.recordTypedefs1(dt.ReturnType, visited)
   672  		for _, a := range dt.ParamType {
   673  			p.recordTypedefs1(a, visited)
   674  		}
   675  	case *dwarf.StructType:
   676  		for _, f := range dt.Field {
   677  			p.recordTypedefs1(f.Type, visited)
   678  		}
   679  	}
   680  }
   681  
   682  // mangleName does name mangling to translate names
   683  // from the original Go source files to the names
   684  // used in the final Go files generated by cgo.
   685  func (p *Package) mangleName(n *Name) {
   686  	// When using gccgo variables have to be
   687  	// exported so that they become global symbols
   688  	// that the C code can refer to.
   689  	prefix := "_C"
   690  	if *gccgo && n.IsVar() {
   691  		prefix = "C"
   692  	}
   693  	n.Mangle = prefix + n.Kind + "_" + n.Go
   694  }
   695  
   696  // rewriteCalls rewrites all calls that pass pointers to check that
   697  // they follow the rules for passing pointers between Go and C.
   698  // This returns whether the package needs to import unsafe as _cgo_unsafe.
   699  func (p *Package) rewriteCalls(f *File) bool {
   700  	needsUnsafe := false
   701  	for _, call := range f.Calls {
   702  		// This is a call to C.xxx; set goname to "xxx".
   703  		goname := call.Call.Fun.(*ast.SelectorExpr).Sel.Name
   704  		if goname == "malloc" {
   705  			continue
   706  		}
   707  		name := f.Name[goname]
   708  		if name.Kind != "func" {
   709  			// Probably a type conversion.
   710  			continue
   711  		}
   712  		if p.rewriteCall(f, call, name) {
   713  			needsUnsafe = true
   714  		}
   715  	}
   716  	return needsUnsafe
   717  }
   718  
   719  // rewriteCall rewrites one call to add pointer checks.
   720  // If any pointer checks are required, we rewrite the call into a
   721  // function literal that calls _cgoCheckPointer for each pointer
   722  // argument and then calls the original function.
   723  // This returns whether the package needs to import unsafe as _cgo_unsafe.
   724  func (p *Package) rewriteCall(f *File, call *Call, name *Name) bool {
   725  	// Avoid a crash if the number of arguments is
   726  	// less than the number of parameters.
   727  	// This will be caught when the generated file is compiled.
   728  	if len(call.Call.Args) < len(name.FuncType.Params) {
   729  		return false
   730  	}
   731  
   732  	any := false
   733  	for i, param := range name.FuncType.Params {
   734  		if p.needsPointerCheck(f, param.Go, call.Call.Args[i]) {
   735  			any = true
   736  			break
   737  		}
   738  	}
   739  	if !any {
   740  		return false
   741  	}
   742  
   743  	// We need to rewrite this call.
   744  	//
   745  	// We are going to rewrite C.f(p) to
   746  	//    func (_cgo0 ptype) {
   747  	//            _cgoCheckPointer(_cgo0)
   748  	//            C.f(_cgo0)
   749  	//    }(p)
   750  	// Using a function literal like this lets us do correct
   751  	// argument type checking, and works correctly if the call is
   752  	// deferred.
   753  	needsUnsafe := false
   754  	params := make([]*ast.Field, len(name.FuncType.Params))
   755  	nargs := make([]ast.Expr, len(name.FuncType.Params))
   756  	var stmts []ast.Stmt
   757  	for i, param := range name.FuncType.Params {
   758  		// params is going to become the parameters of the
   759  		// function literal.
   760  		// nargs is going to become the list of arguments made
   761  		// by the call within the function literal.
   762  		// nparam is the parameter of the function literal that
   763  		// corresponds to param.
   764  
   765  		origArg := call.Call.Args[i]
   766  		nparam := ast.NewIdent(fmt.Sprintf("_cgo%d", i))
   767  		nargs[i] = nparam
   768  
   769  		// The Go version of the C type might use unsafe.Pointer,
   770  		// but the file might not import unsafe.
   771  		// Rewrite the Go type if necessary to use _cgo_unsafe.
   772  		ptype := p.rewriteUnsafe(param.Go)
   773  		if ptype != param.Go {
   774  			needsUnsafe = true
   775  		}
   776  
   777  		params[i] = &ast.Field{
   778  			Names: []*ast.Ident{nparam},
   779  			Type:  ptype,
   780  		}
   781  
   782  		if !p.needsPointerCheck(f, param.Go, origArg) {
   783  			continue
   784  		}
   785  
   786  		// Run the cgo pointer checks on nparam.
   787  
   788  		// Change the function literal to call the real function
   789  		// with the parameter passed through _cgoCheckPointer.
   790  		c := &ast.CallExpr{
   791  			Fun: ast.NewIdent("_cgoCheckPointer"),
   792  			Args: []ast.Expr{
   793  				nparam,
   794  			},
   795  		}
   796  
   797  		// Add optional additional arguments for an address
   798  		// expression.
   799  		c.Args = p.checkAddrArgs(f, c.Args, origArg)
   800  
   801  		stmt := &ast.ExprStmt{
   802  			X: c,
   803  		}
   804  		stmts = append(stmts, stmt)
   805  	}
   806  
   807  	const cgoMarker = "__cgo__###__marker__"
   808  	fcall := &ast.CallExpr{
   809  		Fun:  ast.NewIdent(cgoMarker),
   810  		Args: nargs,
   811  	}
   812  	ftype := &ast.FuncType{
   813  		Params: &ast.FieldList{
   814  			List: params,
   815  		},
   816  	}
   817  	if name.FuncType.Result != nil {
   818  		rtype := p.rewriteUnsafe(name.FuncType.Result.Go)
   819  		if rtype != name.FuncType.Result.Go {
   820  			needsUnsafe = true
   821  		}
   822  		ftype.Results = &ast.FieldList{
   823  			List: []*ast.Field{
   824  				&ast.Field{
   825  					Type: rtype,
   826  				},
   827  			},
   828  		}
   829  	}
   830  
   831  	// If this call expects two results, we have to
   832  	// adjust the results of the function we generated.
   833  	for _, ref := range f.Ref {
   834  		if ref.Expr == &call.Call.Fun && ref.Context == ctxCall2 {
   835  			if ftype.Results == nil {
   836  				// An explicit void argument
   837  				// looks odd but it seems to
   838  				// be how cgo has worked historically.
   839  				ftype.Results = &ast.FieldList{
   840  					List: []*ast.Field{
   841  						&ast.Field{
   842  							Type: ast.NewIdent("_Ctype_void"),
   843  						},
   844  					},
   845  				}
   846  			}
   847  			ftype.Results.List = append(ftype.Results.List,
   848  				&ast.Field{
   849  					Type: ast.NewIdent("error"),
   850  				})
   851  		}
   852  	}
   853  
   854  	var fbody ast.Stmt
   855  	if ftype.Results == nil {
   856  		fbody = &ast.ExprStmt{
   857  			X: fcall,
   858  		}
   859  	} else {
   860  		fbody = &ast.ReturnStmt{
   861  			Results: []ast.Expr{fcall},
   862  		}
   863  	}
   864  	lit := &ast.FuncLit{
   865  		Type: ftype,
   866  		Body: &ast.BlockStmt{
   867  			List: append(stmts, fbody),
   868  		},
   869  	}
   870  	text := strings.Replace(gofmt(lit), "\n", ";", -1)
   871  	repl := strings.Split(text, cgoMarker)
   872  	f.Edit.Insert(f.offset(call.Call.Fun.Pos()), repl[0])
   873  	f.Edit.Insert(f.offset(call.Call.Fun.End()), repl[1])
   874  
   875  	return needsUnsafe
   876  }
   877  
   878  // needsPointerCheck returns whether the type t needs a pointer check.
   879  // This is true if t is a pointer and if the value to which it points
   880  // might contain a pointer.
   881  func (p *Package) needsPointerCheck(f *File, t ast.Expr, arg ast.Expr) bool {
   882  	// An untyped nil does not need a pointer check, and when
   883  	// _cgoCheckPointer returns the untyped nil the type assertion we
   884  	// are going to insert will fail.  Easier to just skip nil arguments.
   885  	// TODO: Note that this fails if nil is shadowed.
   886  	if id, ok := arg.(*ast.Ident); ok && id.Name == "nil" {
   887  		return false
   888  	}
   889  
   890  	return p.hasPointer(f, t, true)
   891  }
   892  
   893  // hasPointer is used by needsPointerCheck. If top is true it returns
   894  // whether t is or contains a pointer that might point to a pointer.
   895  // If top is false it returns whether t is or contains a pointer.
   896  // f may be nil.
   897  func (p *Package) hasPointer(f *File, t ast.Expr, top bool) bool {
   898  	switch t := t.(type) {
   899  	case *ast.ArrayType:
   900  		if t.Len == nil {
   901  			if !top {
   902  				return true
   903  			}
   904  			return p.hasPointer(f, t.Elt, false)
   905  		}
   906  		return p.hasPointer(f, t.Elt, top)
   907  	case *ast.StructType:
   908  		for _, field := range t.Fields.List {
   909  			if p.hasPointer(f, field.Type, top) {
   910  				return true
   911  			}
   912  		}
   913  		return false
   914  	case *ast.StarExpr: // Pointer type.
   915  		if !top {
   916  			return true
   917  		}
   918  		// Check whether this is a pointer to a C union (or class)
   919  		// type that contains a pointer.
   920  		if unionWithPointer[t.X] {
   921  			return true
   922  		}
   923  		return p.hasPointer(f, t.X, false)
   924  	case *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
   925  		return true
   926  	case *ast.Ident:
   927  		// TODO: Handle types defined within function.
   928  		for _, d := range p.Decl {
   929  			gd, ok := d.(*ast.GenDecl)
   930  			if !ok || gd.Tok != token.TYPE {
   931  				continue
   932  			}
   933  			for _, spec := range gd.Specs {
   934  				ts, ok := spec.(*ast.TypeSpec)
   935  				if !ok {
   936  					continue
   937  				}
   938  				if ts.Name.Name == t.Name {
   939  					return p.hasPointer(f, ts.Type, top)
   940  				}
   941  			}
   942  		}
   943  		if def := typedef[t.Name]; def != nil {
   944  			return p.hasPointer(f, def.Go, top)
   945  		}
   946  		if t.Name == "string" {
   947  			return !top
   948  		}
   949  		if t.Name == "error" {
   950  			return true
   951  		}
   952  		if goTypes[t.Name] != nil {
   953  			return false
   954  		}
   955  		// We can't figure out the type. Conservative
   956  		// approach is to assume it has a pointer.
   957  		return true
   958  	case *ast.SelectorExpr:
   959  		if l, ok := t.X.(*ast.Ident); !ok || l.Name != "C" {
   960  			// Type defined in a different package.
   961  			// Conservative approach is to assume it has a
   962  			// pointer.
   963  			return true
   964  		}
   965  		if f == nil {
   966  			// Conservative approach: assume pointer.
   967  			return true
   968  		}
   969  		name := f.Name[t.Sel.Name]
   970  		if name != nil && name.Kind == "type" && name.Type != nil && name.Type.Go != nil {
   971  			return p.hasPointer(f, name.Type.Go, top)
   972  		}
   973  		// We can't figure out the type. Conservative
   974  		// approach is to assume it has a pointer.
   975  		return true
   976  	default:
   977  		error_(t.Pos(), "could not understand type %s", gofmt(t))
   978  		return true
   979  	}
   980  }
   981  
   982  // checkAddrArgs tries to add arguments to the call of
   983  // _cgoCheckPointer when the argument is an address expression. We
   984  // pass true to mean that the argument is an address operation of
   985  // something other than a slice index, which means that it's only
   986  // necessary to check the specific element pointed to, not the entire
   987  // object. This is for &s.f, where f is a field in a struct. We can
   988  // pass a slice or array, meaning that we should check the entire
   989  // slice or array but need not check any other part of the object.
   990  // This is for &s.a[i], where we need to check all of a. However, we
   991  // only pass the slice or array if we can refer to it without side
   992  // effects.
   993  func (p *Package) checkAddrArgs(f *File, args []ast.Expr, x ast.Expr) []ast.Expr {
   994  	// Strip type conversions.
   995  	for {
   996  		c, ok := x.(*ast.CallExpr)
   997  		if !ok || len(c.Args) != 1 || !p.isType(c.Fun) {
   998  			break
   999  		}
  1000  		x = c.Args[0]
  1001  	}
  1002  	u, ok := x.(*ast.UnaryExpr)
  1003  	if !ok || u.Op != token.AND {
  1004  		return args
  1005  	}
  1006  	index, ok := u.X.(*ast.IndexExpr)
  1007  	if !ok {
  1008  		// This is the address of something that is not an
  1009  		// index expression. We only need to examine the
  1010  		// single value to which it points.
  1011  		// TODO: what if true is shadowed?
  1012  		return append(args, ast.NewIdent("true"))
  1013  	}
  1014  	if !p.hasSideEffects(f, index.X) {
  1015  		// Examine the entire slice.
  1016  		return append(args, index.X)
  1017  	}
  1018  	// Treat the pointer as unknown.
  1019  	return args
  1020  }
  1021  
  1022  // hasSideEffects returns whether the expression x has any side
  1023  // effects.  x is an expression, not a statement, so the only side
  1024  // effect is a function call.
  1025  func (p *Package) hasSideEffects(f *File, x ast.Expr) bool {
  1026  	found := false
  1027  	f.walk(x, ctxExpr,
  1028  		func(f *File, x interface{}, context astContext) {
  1029  			switch x.(type) {
  1030  			case *ast.CallExpr:
  1031  				found = true
  1032  			}
  1033  		})
  1034  	return found
  1035  }
  1036  
  1037  // isType returns whether the expression is definitely a type.
  1038  // This is conservative--it returns false for an unknown identifier.
  1039  func (p *Package) isType(t ast.Expr) bool {
  1040  	switch t := t.(type) {
  1041  	case *ast.SelectorExpr:
  1042  		id, ok := t.X.(*ast.Ident)
  1043  		if !ok {
  1044  			return false
  1045  		}
  1046  		if id.Name == "unsafe" && t.Sel.Name == "Pointer" {
  1047  			return true
  1048  		}
  1049  		if id.Name == "C" && typedef["_Ctype_"+t.Sel.Name] != nil {
  1050  			return true
  1051  		}
  1052  		return false
  1053  	case *ast.Ident:
  1054  		// TODO: This ignores shadowing.
  1055  		switch t.Name {
  1056  		case "unsafe.Pointer", "bool", "byte",
  1057  			"complex64", "complex128",
  1058  			"error",
  1059  			"float32", "float64",
  1060  			"int", "int8", "int16", "int32", "int64",
  1061  			"rune", "string",
  1062  			"uint", "uint8", "uint16", "uint32", "uint64", "uintptr":
  1063  
  1064  			return true
  1065  		}
  1066  	case *ast.StarExpr:
  1067  		return p.isType(t.X)
  1068  	case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType,
  1069  		*ast.MapType, *ast.ChanType:
  1070  
  1071  		return true
  1072  	}
  1073  	return false
  1074  }
  1075  
  1076  // rewriteUnsafe returns a version of t with references to unsafe.Pointer
  1077  // rewritten to use _cgo_unsafe.Pointer instead.
  1078  func (p *Package) rewriteUnsafe(t ast.Expr) ast.Expr {
  1079  	switch t := t.(type) {
  1080  	case *ast.Ident:
  1081  		// We don't see a SelectorExpr for unsafe.Pointer;
  1082  		// this is created by code in this file.
  1083  		if t.Name == "unsafe.Pointer" {
  1084  			return ast.NewIdent("_cgo_unsafe.Pointer")
  1085  		}
  1086  	case *ast.ArrayType:
  1087  		t1 := p.rewriteUnsafe(t.Elt)
  1088  		if t1 != t.Elt {
  1089  			r := *t
  1090  			r.Elt = t1
  1091  			return &r
  1092  		}
  1093  	case *ast.StructType:
  1094  		changed := false
  1095  		fields := *t.Fields
  1096  		fields.List = nil
  1097  		for _, f := range t.Fields.List {
  1098  			ft := p.rewriteUnsafe(f.Type)
  1099  			if ft == f.Type {
  1100  				fields.List = append(fields.List, f)
  1101  			} else {
  1102  				fn := *f
  1103  				fn.Type = ft
  1104  				fields.List = append(fields.List, &fn)
  1105  				changed = true
  1106  			}
  1107  		}
  1108  		if changed {
  1109  			r := *t
  1110  			r.Fields = &fields
  1111  			return &r
  1112  		}
  1113  	case *ast.StarExpr: // Pointer type.
  1114  		x1 := p.rewriteUnsafe(t.X)
  1115  		if x1 != t.X {
  1116  			r := *t
  1117  			r.X = x1
  1118  			return &r
  1119  		}
  1120  	}
  1121  	return t
  1122  }
  1123  
  1124  // rewriteRef rewrites all the C.xxx references in f.AST to refer to the
  1125  // Go equivalents, now that we have figured out the meaning of all
  1126  // the xxx. In *godefs mode, rewriteRef replaces the names
  1127  // with full definitions instead of mangled names.
  1128  func (p *Package) rewriteRef(f *File) {
  1129  	// Keep a list of all the functions, to remove the ones
  1130  	// only used as expressions and avoid generating bridge
  1131  	// code for them.
  1132  	functions := make(map[string]bool)
  1133  
  1134  	// Assign mangled names.
  1135  	for _, n := range f.Name {
  1136  		if n.Kind == "not-type" {
  1137  			if n.Define == "" {
  1138  				n.Kind = "var"
  1139  			} else {
  1140  				n.Kind = "macro"
  1141  				n.FuncType = &FuncType{
  1142  					Result: n.Type,
  1143  					Go: &ast.FuncType{
  1144  						Results: &ast.FieldList{List: []*ast.Field{{Type: n.Type.Go}}},
  1145  					},
  1146  				}
  1147  			}
  1148  		}
  1149  		if n.Mangle == "" {
  1150  			p.mangleName(n)
  1151  		}
  1152  		if n.Kind == "func" {
  1153  			functions[n.Go] = false
  1154  		}
  1155  	}
  1156  
  1157  	// Now that we have all the name types filled in,
  1158  	// scan through the Refs to identify the ones that
  1159  	// are trying to do a ,err call. Also check that
  1160  	// functions are only used in calls.
  1161  	for _, r := range f.Ref {
  1162  		if r.Name.IsConst() && r.Name.Const == "" {
  1163  			error_(r.Pos(), "unable to find value of constant C.%s", fixGo(r.Name.Go))
  1164  		}
  1165  		var expr ast.Expr = ast.NewIdent(r.Name.Mangle) // default
  1166  		switch r.Context {
  1167  		case ctxCall, ctxCall2:
  1168  			if r.Name.Kind != "func" {
  1169  				if r.Name.Kind == "type" {
  1170  					r.Context = ctxType
  1171  					if r.Name.Type == nil {
  1172  						error_(r.Pos(), "invalid conversion to C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
  1173  						break
  1174  					}
  1175  					expr = r.Name.Type.Go
  1176  					break
  1177  				}
  1178  				error_(r.Pos(), "call of non-function C.%s", fixGo(r.Name.Go))
  1179  				break
  1180  			}
  1181  			functions[r.Name.Go] = true
  1182  			if r.Context == ctxCall2 {
  1183  				if r.Name.Go == "_CMalloc" {
  1184  					error_(r.Pos(), "no two-result form for C.malloc")
  1185  					break
  1186  				}
  1187  				// Invent new Name for the two-result function.
  1188  				n := f.Name["2"+r.Name.Go]
  1189  				if n == nil {
  1190  					n = new(Name)
  1191  					*n = *r.Name
  1192  					n.AddError = true
  1193  					n.Mangle = "_C2func_" + n.Go
  1194  					f.Name["2"+r.Name.Go] = n
  1195  				}
  1196  				expr = ast.NewIdent(n.Mangle)
  1197  				r.Name = n
  1198  				break
  1199  			}
  1200  		case ctxExpr:
  1201  			switch r.Name.Kind {
  1202  			case "func":
  1203  				if builtinDefs[r.Name.C] != "" {
  1204  					error_(r.Pos(), "use of builtin '%s' not in function call", fixGo(r.Name.C))
  1205  				}
  1206  
  1207  				// Function is being used in an expression, to e.g. pass around a C function pointer.
  1208  				// Create a new Name for this Ref which causes the variable to be declared in Go land.
  1209  				fpName := "fp_" + r.Name.Go
  1210  				name := f.Name[fpName]
  1211  				if name == nil {
  1212  					name = &Name{
  1213  						Go:   fpName,
  1214  						C:    r.Name.C,
  1215  						Kind: "fpvar",
  1216  						Type: &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*"), Go: ast.NewIdent("unsafe.Pointer")},
  1217  					}
  1218  					p.mangleName(name)
  1219  					f.Name[fpName] = name
  1220  				}
  1221  				r.Name = name
  1222  				// Rewrite into call to _Cgo_ptr to prevent assignments. The _Cgo_ptr
  1223  				// function is defined in out.go and simply returns its argument. See
  1224  				// issue 7757.
  1225  				expr = &ast.CallExpr{
  1226  					Fun:  &ast.Ident{NamePos: (*r.Expr).Pos(), Name: "_Cgo_ptr"},
  1227  					Args: []ast.Expr{ast.NewIdent(name.Mangle)},
  1228  				}
  1229  			case "type":
  1230  				// Okay - might be new(T)
  1231  				if r.Name.Type == nil {
  1232  					error_(r.Pos(), "expression C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
  1233  					break
  1234  				}
  1235  				expr = r.Name.Type.Go
  1236  			case "var":
  1237  				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
  1238  			case "macro":
  1239  				expr = &ast.CallExpr{Fun: expr}
  1240  			}
  1241  		case ctxSelector:
  1242  			if r.Name.Kind == "var" {
  1243  				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
  1244  			} else {
  1245  				error_(r.Pos(), "only C variables allowed in selector expression %s", fixGo(r.Name.Go))
  1246  			}
  1247  		case ctxType:
  1248  			if r.Name.Kind != "type" {
  1249  				error_(r.Pos(), "expression C.%s used as type", fixGo(r.Name.Go))
  1250  			} else if r.Name.Type == nil {
  1251  				// Use of C.enum_x, C.struct_x or C.union_x without C definition.
  1252  				// GCC won't raise an error when using pointers to such unknown types.
  1253  				error_(r.Pos(), "type C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
  1254  			} else {
  1255  				expr = r.Name.Type.Go
  1256  			}
  1257  		default:
  1258  			if r.Name.Kind == "func" {
  1259  				error_(r.Pos(), "must call C.%s", fixGo(r.Name.Go))
  1260  			}
  1261  		}
  1262  
  1263  		if *godefs {
  1264  			// Substitute definition for mangled type name.
  1265  			if id, ok := expr.(*ast.Ident); ok {
  1266  				if t := typedef[id.Name]; t != nil {
  1267  					expr = t.Go
  1268  				}
  1269  				if id.Name == r.Name.Mangle && r.Name.Const != "" {
  1270  					expr = ast.NewIdent(r.Name.Const)
  1271  				}
  1272  			}
  1273  		}
  1274  
  1275  		// Copy position information from old expr into new expr,
  1276  		// in case expression being replaced is first on line.
  1277  		// See golang.org/issue/6563.
  1278  		pos := (*r.Expr).Pos()
  1279  		switch x := expr.(type) {
  1280  		case *ast.Ident:
  1281  			expr = &ast.Ident{NamePos: pos, Name: x.Name}
  1282  		}
  1283  
  1284  		// Change AST, because some later processing depends on it,
  1285  		// and also because -godefs mode still prints the AST.
  1286  		old := *r.Expr
  1287  		*r.Expr = expr
  1288  
  1289  		// Record source-level edit for cgo output.
  1290  		repl := gofmt(expr)
  1291  		if r.Name.Kind != "type" {
  1292  			repl = "(" + repl + ")"
  1293  		}
  1294  		f.Edit.Replace(f.offset(old.Pos()), f.offset(old.End()), repl)
  1295  	}
  1296  
  1297  	// Remove functions only used as expressions, so their respective
  1298  	// bridge functions are not generated.
  1299  	for name, used := range functions {
  1300  		if !used {
  1301  			delete(f.Name, name)
  1302  		}
  1303  	}
  1304  }
  1305  
  1306  // gccBaseCmd returns the start of the compiler command line.
  1307  // It uses $CC if set, or else $GCC, or else the compiler recorded
  1308  // during the initial build as defaultCC.
  1309  // defaultCC is defined in zdefaultcc.go, written by cmd/dist.
  1310  func (p *Package) gccBaseCmd() []string {
  1311  	// Use $CC if set, since that's what the build uses.
  1312  	if ret := strings.Fields(os.Getenv("CC")); len(ret) > 0 {
  1313  		return ret
  1314  	}
  1315  	// Try $GCC if set, since that's what we used to use.
  1316  	if ret := strings.Fields(os.Getenv("GCC")); len(ret) > 0 {
  1317  		return ret
  1318  	}
  1319  	return strings.Fields(defaultCC(goos, goarch))
  1320  }
  1321  
  1322  // gccMachine returns the gcc -m flag to use, either "-m32", "-m64" or "-marm".
  1323  func (p *Package) gccMachine() []string {
  1324  	switch goarch {
  1325  	case "amd64":
  1326  		return []string{"-m64"}
  1327  	case "386":
  1328  		return []string{"-m32"}
  1329  	case "arm":
  1330  		return []string{"-marm"} // not thumb
  1331  	case "s390":
  1332  		return []string{"-m31"}
  1333  	case "s390x":
  1334  		return []string{"-m64"}
  1335  	case "mips64", "mips64le":
  1336  		return []string{"-mabi=64"}
  1337  	case "mips", "mipsle":
  1338  		return []string{"-mabi=32"}
  1339  	}
  1340  	return nil
  1341  }
  1342  
  1343  func gccTmp() string {
  1344  	return *objDir + "_cgo_.o"
  1345  }
  1346  
  1347  // gccCmd returns the gcc command line to use for compiling
  1348  // the input.
  1349  func (p *Package) gccCmd() []string {
  1350  	c := append(p.gccBaseCmd(),
  1351  		"-w",          // no warnings
  1352  		"-Wno-error",  // warnings are not errors
  1353  		"-o"+gccTmp(), // write object to tmp
  1354  		"-gdwarf-2",   // generate DWARF v2 debugging symbols
  1355  		"-c",          // do not link
  1356  		"-xc",         // input language is C
  1357  	)
  1358  	if p.GccIsClang {
  1359  		c = append(c,
  1360  			"-ferror-limit=0",
  1361  			// Apple clang version 1.7 (tags/Apple/clang-77) (based on LLVM 2.9svn)
  1362  			// doesn't have -Wno-unneeded-internal-declaration, so we need yet another
  1363  			// flag to disable the warning. Yes, really good diagnostics, clang.
  1364  			"-Wno-unknown-warning-option",
  1365  			"-Wno-unneeded-internal-declaration",
  1366  			"-Wno-unused-function",
  1367  			"-Qunused-arguments",
  1368  			// Clang embeds prototypes for some builtin functions,
  1369  			// like malloc and calloc, but all size_t parameters are
  1370  			// incorrectly typed unsigned long. We work around that
  1371  			// by disabling the builtin functions (this is safe as
  1372  			// it won't affect the actual compilation of the C code).
  1373  			// See: https://golang.org/issue/6506.
  1374  			"-fno-builtin",
  1375  		)
  1376  	}
  1377  
  1378  	c = append(c, p.GccOptions...)
  1379  	c = append(c, p.gccMachine()...)
  1380  	c = append(c, "-") //read input from standard input
  1381  	return c
  1382  }
  1383  
  1384  // gccDebug runs gcc -gdwarf-2 over the C program stdin and
  1385  // returns the corresponding DWARF data and, if present, debug data block.
  1386  func (p *Package) gccDebug(stdin []byte, nnames int) (d *dwarf.Data, ints []int64, floats []float64, strs []string) {
  1387  	runGcc(stdin, p.gccCmd())
  1388  
  1389  	isDebugInts := func(s string) bool {
  1390  		// Some systems use leading _ to denote non-assembly symbols.
  1391  		return s == "__cgodebug_ints" || s == "___cgodebug_ints"
  1392  	}
  1393  	isDebugFloats := func(s string) bool {
  1394  		// Some systems use leading _ to denote non-assembly symbols.
  1395  		return s == "__cgodebug_floats" || s == "___cgodebug_floats"
  1396  	}
  1397  	indexOfDebugStr := func(s string) int {
  1398  		// Some systems use leading _ to denote non-assembly symbols.
  1399  		if strings.HasPrefix(s, "___") {
  1400  			s = s[1:]
  1401  		}
  1402  		if strings.HasPrefix(s, "__cgodebug_str__") {
  1403  			if n, err := strconv.Atoi(s[len("__cgodebug_str__"):]); err == nil {
  1404  				return n
  1405  			}
  1406  		}
  1407  		return -1
  1408  	}
  1409  	indexOfDebugStrlen := func(s string) int {
  1410  		// Some systems use leading _ to denote non-assembly symbols.
  1411  		if strings.HasPrefix(s, "___") {
  1412  			s = s[1:]
  1413  		}
  1414  		if strings.HasPrefix(s, "__cgodebug_strlen__") {
  1415  			if n, err := strconv.Atoi(s[len("__cgodebug_strlen__"):]); err == nil {
  1416  				return n
  1417  			}
  1418  		}
  1419  		return -1
  1420  	}
  1421  
  1422  	strs = make([]string, nnames)
  1423  
  1424  	strdata := make(map[int]string, nnames)
  1425  	strlens := make(map[int]int, nnames)
  1426  
  1427  	buildStrings := func() {
  1428  		for n, strlen := range strlens {
  1429  			data := strdata[n]
  1430  			if len(data) <= strlen {
  1431  				fatalf("invalid string literal")
  1432  			}
  1433  			strs[n] = data[:strlen]
  1434  		}
  1435  	}
  1436  
  1437  	if f, err := macho.Open(gccTmp()); err == nil {
  1438  		defer f.Close()
  1439  		d, err := f.DWARF()
  1440  		if err != nil {
  1441  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1442  		}
  1443  		bo := f.ByteOrder
  1444  		if f.Symtab != nil {
  1445  			for i := range f.Symtab.Syms {
  1446  				s := &f.Symtab.Syms[i]
  1447  				switch {
  1448  				case isDebugInts(s.Name):
  1449  					// Found it. Now find data section.
  1450  					if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
  1451  						sect := f.Sections[i]
  1452  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1453  							if sdat, err := sect.Data(); err == nil {
  1454  								data := sdat[s.Value-sect.Addr:]
  1455  								ints = make([]int64, len(data)/8)
  1456  								for i := range ints {
  1457  									ints[i] = int64(bo.Uint64(data[i*8:]))
  1458  								}
  1459  							}
  1460  						}
  1461  					}
  1462  				case isDebugFloats(s.Name):
  1463  					// Found it. Now find data section.
  1464  					if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
  1465  						sect := f.Sections[i]
  1466  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1467  							if sdat, err := sect.Data(); err == nil {
  1468  								data := sdat[s.Value-sect.Addr:]
  1469  								floats = make([]float64, len(data)/8)
  1470  								for i := range floats {
  1471  									floats[i] = math.Float64frombits(bo.Uint64(data[i*8:]))
  1472  								}
  1473  							}
  1474  						}
  1475  					}
  1476  				default:
  1477  					if n := indexOfDebugStr(s.Name); n != -1 {
  1478  						// Found it. Now find data section.
  1479  						if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
  1480  							sect := f.Sections[i]
  1481  							if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1482  								if sdat, err := sect.Data(); err == nil {
  1483  									data := sdat[s.Value-sect.Addr:]
  1484  									strdata[n] = string(data)
  1485  								}
  1486  							}
  1487  						}
  1488  						break
  1489  					}
  1490  					if n := indexOfDebugStrlen(s.Name); n != -1 {
  1491  						// Found it. Now find data section.
  1492  						if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
  1493  							sect := f.Sections[i]
  1494  							if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1495  								if sdat, err := sect.Data(); err == nil {
  1496  									data := sdat[s.Value-sect.Addr:]
  1497  									strlen := bo.Uint64(data[:8])
  1498  									if strlen > (1<<(uint(p.IntSize*8)-1) - 1) { // greater than MaxInt?
  1499  										fatalf("string literal too big")
  1500  									}
  1501  									strlens[n] = int(strlen)
  1502  								}
  1503  							}
  1504  						}
  1505  						break
  1506  					}
  1507  				}
  1508  			}
  1509  
  1510  			buildStrings()
  1511  		}
  1512  		return d, ints, floats, strs
  1513  	}
  1514  
  1515  	if f, err := elf.Open(gccTmp()); err == nil {
  1516  		defer f.Close()
  1517  		d, err := f.DWARF()
  1518  		if err != nil {
  1519  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1520  		}
  1521  		bo := f.ByteOrder
  1522  		symtab, err := f.Symbols()
  1523  		if err == nil {
  1524  			for i := range symtab {
  1525  				s := &symtab[i]
  1526  				switch {
  1527  				case isDebugInts(s.Name):
  1528  					// Found it. Now find data section.
  1529  					if i := int(s.Section); 0 <= i && i < len(f.Sections) {
  1530  						sect := f.Sections[i]
  1531  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1532  							if sdat, err := sect.Data(); err == nil {
  1533  								data := sdat[s.Value-sect.Addr:]
  1534  								ints = make([]int64, len(data)/8)
  1535  								for i := range ints {
  1536  									ints[i] = int64(bo.Uint64(data[i*8:]))
  1537  								}
  1538  							}
  1539  						}
  1540  					}
  1541  				case isDebugFloats(s.Name):
  1542  					// Found it. Now find data section.
  1543  					if i := int(s.Section); 0 <= i && i < len(f.Sections) {
  1544  						sect := f.Sections[i]
  1545  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1546  							if sdat, err := sect.Data(); err == nil {
  1547  								data := sdat[s.Value-sect.Addr:]
  1548  								floats = make([]float64, len(data)/8)
  1549  								for i := range floats {
  1550  									floats[i] = math.Float64frombits(bo.Uint64(data[i*8:]))
  1551  								}
  1552  							}
  1553  						}
  1554  					}
  1555  				default:
  1556  					if n := indexOfDebugStr(s.Name); n != -1 {
  1557  						// Found it. Now find data section.
  1558  						if i := int(s.Section); 0 <= i && i < len(f.Sections) {
  1559  							sect := f.Sections[i]
  1560  							if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1561  								if sdat, err := sect.Data(); err == nil {
  1562  									data := sdat[s.Value-sect.Addr:]
  1563  									strdata[n] = string(data)
  1564  								}
  1565  							}
  1566  						}
  1567  						break
  1568  					}
  1569  					if n := indexOfDebugStrlen(s.Name); n != -1 {
  1570  						// Found it. Now find data section.
  1571  						if i := int(s.Section); 0 <= i && i < len(f.Sections) {
  1572  							sect := f.Sections[i]
  1573  							if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1574  								if sdat, err := sect.Data(); err == nil {
  1575  									data := sdat[s.Value-sect.Addr:]
  1576  									strlen := bo.Uint64(data[:8])
  1577  									if strlen > (1<<(uint(p.IntSize*8)-1) - 1) { // greater than MaxInt?
  1578  										fatalf("string literal too big")
  1579  									}
  1580  									strlens[n] = int(strlen)
  1581  								}
  1582  							}
  1583  						}
  1584  						break
  1585  					}
  1586  				}
  1587  			}
  1588  
  1589  			buildStrings()
  1590  		}
  1591  		return d, ints, floats, strs
  1592  	}
  1593  
  1594  	if f, err := pe.Open(gccTmp()); err == nil {
  1595  		defer f.Close()
  1596  		d, err := f.DWARF()
  1597  		if err != nil {
  1598  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1599  		}
  1600  		bo := binary.LittleEndian
  1601  		for _, s := range f.Symbols {
  1602  			switch {
  1603  			case isDebugInts(s.Name):
  1604  				if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
  1605  					sect := f.Sections[i]
  1606  					if s.Value < sect.Size {
  1607  						if sdat, err := sect.Data(); err == nil {
  1608  							data := sdat[s.Value:]
  1609  							ints = make([]int64, len(data)/8)
  1610  							for i := range ints {
  1611  								ints[i] = int64(bo.Uint64(data[i*8:]))
  1612  							}
  1613  						}
  1614  					}
  1615  				}
  1616  			case isDebugFloats(s.Name):
  1617  				if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
  1618  					sect := f.Sections[i]
  1619  					if s.Value < sect.Size {
  1620  						if sdat, err := sect.Data(); err == nil {
  1621  							data := sdat[s.Value:]
  1622  							floats = make([]float64, len(data)/8)
  1623  							for i := range floats {
  1624  								floats[i] = math.Float64frombits(bo.Uint64(data[i*8:]))
  1625  							}
  1626  						}
  1627  					}
  1628  				}
  1629  			default:
  1630  				if n := indexOfDebugStr(s.Name); n != -1 {
  1631  					if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
  1632  						sect := f.Sections[i]
  1633  						if s.Value < sect.Size {
  1634  							if sdat, err := sect.Data(); err == nil {
  1635  								data := sdat[s.Value:]
  1636  								strdata[n] = string(data)
  1637  							}
  1638  						}
  1639  					}
  1640  					break
  1641  				}
  1642  				if n := indexOfDebugStrlen(s.Name); n != -1 {
  1643  					if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
  1644  						sect := f.Sections[i]
  1645  						if s.Value < sect.Size {
  1646  							if sdat, err := sect.Data(); err == nil {
  1647  								data := sdat[s.Value:]
  1648  								strlen := bo.Uint64(data[:8])
  1649  								if strlen > (1<<(uint(p.IntSize*8)-1) - 1) { // greater than MaxInt?
  1650  									fatalf("string literal too big")
  1651  								}
  1652  								strlens[n] = int(strlen)
  1653  							}
  1654  						}
  1655  					}
  1656  					break
  1657  				}
  1658  			}
  1659  		}
  1660  
  1661  		buildStrings()
  1662  
  1663  		return d, ints, floats, strs
  1664  	}
  1665  
  1666  	fatalf("cannot parse gcc output %s as ELF, Mach-O, PE object", gccTmp())
  1667  	panic("not reached")
  1668  }
  1669  
  1670  // gccDefines runs gcc -E -dM -xc - over the C program stdin
  1671  // and returns the corresponding standard output, which is the
  1672  // #defines that gcc encountered while processing the input
  1673  // and its included files.
  1674  func (p *Package) gccDefines(stdin []byte) string {
  1675  	base := append(p.gccBaseCmd(), "-E", "-dM", "-xc")
  1676  	base = append(base, p.gccMachine()...)
  1677  	stdout, _ := runGcc(stdin, append(append(base, p.GccOptions...), "-"))
  1678  	return stdout
  1679  }
  1680  
  1681  // gccErrors runs gcc over the C program stdin and returns
  1682  // the errors that gcc prints. That is, this function expects
  1683  // gcc to fail.
  1684  func (p *Package) gccErrors(stdin []byte) string {
  1685  	// TODO(rsc): require failure
  1686  	args := p.gccCmd()
  1687  
  1688  	// Optimization options can confuse the error messages; remove them.
  1689  	nargs := make([]string, 0, len(args))
  1690  	for _, arg := range args {
  1691  		if !strings.HasPrefix(arg, "-O") {
  1692  			nargs = append(nargs, arg)
  1693  		}
  1694  	}
  1695  
  1696  	if *debugGcc {
  1697  		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(nargs, " "))
  1698  		os.Stderr.Write(stdin)
  1699  		fmt.Fprint(os.Stderr, "EOF\n")
  1700  	}
  1701  	stdout, stderr, _ := run(stdin, nargs)
  1702  	if *debugGcc {
  1703  		os.Stderr.Write(stdout)
  1704  		os.Stderr.Write(stderr)
  1705  	}
  1706  	return string(stderr)
  1707  }
  1708  
  1709  // runGcc runs the gcc command line args with stdin on standard input.
  1710  // If the command exits with a non-zero exit status, runGcc prints
  1711  // details about what was run and exits.
  1712  // Otherwise runGcc returns the data written to standard output and standard error.
  1713  // Note that for some of the uses we expect useful data back
  1714  // on standard error, but for those uses gcc must still exit 0.
  1715  func runGcc(stdin []byte, args []string) (string, string) {
  1716  	if *debugGcc {
  1717  		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " "))
  1718  		os.Stderr.Write(stdin)
  1719  		fmt.Fprint(os.Stderr, "EOF\n")
  1720  	}
  1721  	stdout, stderr, ok := run(stdin, args)
  1722  	if *debugGcc {
  1723  		os.Stderr.Write(stdout)
  1724  		os.Stderr.Write(stderr)
  1725  	}
  1726  	if !ok {
  1727  		os.Stderr.Write(stderr)
  1728  		os.Exit(2)
  1729  	}
  1730  	return string(stdout), string(stderr)
  1731  }
  1732  
  1733  // A typeConv is a translator from dwarf types to Go types
  1734  // with equivalent memory layout.
  1735  type typeConv struct {
  1736  	// Cache of already-translated or in-progress types.
  1737  	m map[dwarf.Type]*Type
  1738  
  1739  	// Map from types to incomplete pointers to those types.
  1740  	ptrs map[dwarf.Type][]*Type
  1741  	// Keys of ptrs in insertion order (deterministic worklist)
  1742  	// ptrKeys contains exactly the keys in ptrs.
  1743  	ptrKeys []dwarf.Type
  1744  
  1745  	// Type names X for which there exists an XGetTypeID function with type func() CFTypeID.
  1746  	getTypeIDs map[string]bool
  1747  
  1748  	// Predeclared types.
  1749  	bool                                   ast.Expr
  1750  	byte                                   ast.Expr // denotes padding
  1751  	int8, int16, int32, int64              ast.Expr
  1752  	uint8, uint16, uint32, uint64, uintptr ast.Expr
  1753  	float32, float64                       ast.Expr
  1754  	complex64, complex128                  ast.Expr
  1755  	void                                   ast.Expr
  1756  	string                                 ast.Expr
  1757  	goVoid                                 ast.Expr // _Ctype_void, denotes C's void
  1758  	goVoidPtr                              ast.Expr // unsafe.Pointer or *byte
  1759  
  1760  	ptrSize int64
  1761  	intSize int64
  1762  }
  1763  
  1764  var tagGen int
  1765  var typedef = make(map[string]*Type)
  1766  var goIdent = make(map[string]*ast.Ident)
  1767  
  1768  // unionWithPointer is true for a Go type that represents a C union (or class)
  1769  // that may contain a pointer. This is used for cgo pointer checking.
  1770  var unionWithPointer = make(map[ast.Expr]bool)
  1771  
  1772  func (c *typeConv) Init(ptrSize, intSize int64) {
  1773  	c.ptrSize = ptrSize
  1774  	c.intSize = intSize
  1775  	c.m = make(map[dwarf.Type]*Type)
  1776  	c.ptrs = make(map[dwarf.Type][]*Type)
  1777  	c.getTypeIDs = make(map[string]bool)
  1778  	c.bool = c.Ident("bool")
  1779  	c.byte = c.Ident("byte")
  1780  	c.int8 = c.Ident("int8")
  1781  	c.int16 = c.Ident("int16")
  1782  	c.int32 = c.Ident("int32")
  1783  	c.int64 = c.Ident("int64")
  1784  	c.uint8 = c.Ident("uint8")
  1785  	c.uint16 = c.Ident("uint16")
  1786  	c.uint32 = c.Ident("uint32")
  1787  	c.uint64 = c.Ident("uint64")
  1788  	c.uintptr = c.Ident("uintptr")
  1789  	c.float32 = c.Ident("float32")
  1790  	c.float64 = c.Ident("float64")
  1791  	c.complex64 = c.Ident("complex64")
  1792  	c.complex128 = c.Ident("complex128")
  1793  	c.void = c.Ident("void")
  1794  	c.string = c.Ident("string")
  1795  	c.goVoid = c.Ident("_Ctype_void")
  1796  
  1797  	// Normally cgo translates void* to unsafe.Pointer,
  1798  	// but for historical reasons -godefs uses *byte instead.
  1799  	if *godefs {
  1800  		c.goVoidPtr = &ast.StarExpr{X: c.byte}
  1801  	} else {
  1802  		c.goVoidPtr = c.Ident("unsafe.Pointer")
  1803  	}
  1804  }
  1805  
  1806  // base strips away qualifiers and typedefs to get the underlying type
  1807  func base(dt dwarf.Type) dwarf.Type {
  1808  	for {
  1809  		if d, ok := dt.(*dwarf.QualType); ok {
  1810  			dt = d.Type
  1811  			continue
  1812  		}
  1813  		if d, ok := dt.(*dwarf.TypedefType); ok {
  1814  			dt = d.Type
  1815  			continue
  1816  		}
  1817  		break
  1818  	}
  1819  	return dt
  1820  }
  1821  
  1822  // unqual strips away qualifiers from a DWARF type.
  1823  // In general we don't care about top-level qualifiers.
  1824  func unqual(dt dwarf.Type) dwarf.Type {
  1825  	for {
  1826  		if d, ok := dt.(*dwarf.QualType); ok {
  1827  			dt = d.Type
  1828  		} else {
  1829  			break
  1830  		}
  1831  	}
  1832  	return dt
  1833  }
  1834  
  1835  // Map from dwarf text names to aliases we use in package "C".
  1836  var dwarfToName = map[string]string{
  1837  	"long int":               "long",
  1838  	"long unsigned int":      "ulong",
  1839  	"unsigned int":           "uint",
  1840  	"short unsigned int":     "ushort",
  1841  	"unsigned short":         "ushort", // Used by Clang; issue 13129.
  1842  	"short int":              "short",
  1843  	"long long int":          "longlong",
  1844  	"long long unsigned int": "ulonglong",
  1845  	"signed char":            "schar",
  1846  	"unsigned char":          "uchar",
  1847  }
  1848  
  1849  const signedDelta = 64
  1850  
  1851  // String returns the current type representation. Format arguments
  1852  // are assembled within this method so that any changes in mutable
  1853  // values are taken into account.
  1854  func (tr *TypeRepr) String() string {
  1855  	if len(tr.Repr) == 0 {
  1856  		return ""
  1857  	}
  1858  	if len(tr.FormatArgs) == 0 {
  1859  		return tr.Repr
  1860  	}
  1861  	return fmt.Sprintf(tr.Repr, tr.FormatArgs...)
  1862  }
  1863  
  1864  // Empty reports whether the result of String would be "".
  1865  func (tr *TypeRepr) Empty() bool {
  1866  	return len(tr.Repr) == 0
  1867  }
  1868  
  1869  // Set modifies the type representation.
  1870  // If fargs are provided, repr is used as a format for fmt.Sprintf.
  1871  // Otherwise, repr is used unprocessed as the type representation.
  1872  func (tr *TypeRepr) Set(repr string, fargs ...interface{}) {
  1873  	tr.Repr = repr
  1874  	tr.FormatArgs = fargs
  1875  }
  1876  
  1877  // FinishType completes any outstanding type mapping work.
  1878  // In particular, it resolves incomplete pointer types.
  1879  func (c *typeConv) FinishType(pos token.Pos) {
  1880  	// Completing one pointer type might produce more to complete.
  1881  	// Keep looping until they're all done.
  1882  	for len(c.ptrKeys) > 0 {
  1883  		dtype := c.ptrKeys[0]
  1884  		c.ptrKeys = c.ptrKeys[1:]
  1885  		ptrs := c.ptrs[dtype]
  1886  		delete(c.ptrs, dtype)
  1887  
  1888  		// Note Type might invalidate c.ptrs[dtype].
  1889  		t := c.Type(dtype, pos)
  1890  		for _, ptr := range ptrs {
  1891  			ptr.Go.(*ast.StarExpr).X = t.Go
  1892  			ptr.C.Set("%s*", t.C)
  1893  		}
  1894  	}
  1895  }
  1896  
  1897  // Type returns a *Type with the same memory layout as
  1898  // dtype when used as the type of a variable or a struct field.
  1899  func (c *typeConv) Type(dtype dwarf.Type, pos token.Pos) *Type {
  1900  	if t, ok := c.m[dtype]; ok {
  1901  		if t.Go == nil {
  1902  			fatalf("%s: type conversion loop at %s", lineno(pos), dtype)
  1903  		}
  1904  		return t
  1905  	}
  1906  
  1907  	t := new(Type)
  1908  	t.Size = dtype.Size() // note: wrong for array of pointers, corrected below
  1909  	t.Align = -1
  1910  	t.C = &TypeRepr{Repr: dtype.Common().Name}
  1911  	c.m[dtype] = t
  1912  
  1913  	switch dt := dtype.(type) {
  1914  	default:
  1915  		fatalf("%s: unexpected type: %s", lineno(pos), dtype)
  1916  
  1917  	case *dwarf.AddrType:
  1918  		if t.Size != c.ptrSize {
  1919  			fatalf("%s: unexpected: %d-byte address type - %s", lineno(pos), t.Size, dtype)
  1920  		}
  1921  		t.Go = c.uintptr
  1922  		t.Align = t.Size
  1923  
  1924  	case *dwarf.ArrayType:
  1925  		if dt.StrideBitSize > 0 {
  1926  			// Cannot represent bit-sized elements in Go.
  1927  			t.Go = c.Opaque(t.Size)
  1928  			break
  1929  		}
  1930  		count := dt.Count
  1931  		if count == -1 {
  1932  			// Indicates flexible array member, which Go doesn't support.
  1933  			// Translate to zero-length array instead.
  1934  			count = 0
  1935  		}
  1936  		sub := c.Type(dt.Type, pos)
  1937  		t.Align = sub.Align
  1938  		t.Go = &ast.ArrayType{
  1939  			Len: c.intExpr(count),
  1940  			Elt: sub.Go,
  1941  		}
  1942  		// Recalculate t.Size now that we know sub.Size.
  1943  		t.Size = count * sub.Size
  1944  		t.C.Set("__typeof__(%s[%d])", sub.C, dt.Count)
  1945  
  1946  	case *dwarf.BoolType:
  1947  		t.Go = c.bool
  1948  		t.Align = 1
  1949  
  1950  	case *dwarf.CharType:
  1951  		if t.Size != 1 {
  1952  			fatalf("%s: unexpected: %d-byte char type - %s", lineno(pos), t.Size, dtype)
  1953  		}
  1954  		t.Go = c.int8
  1955  		t.Align = 1
  1956  
  1957  	case *dwarf.EnumType:
  1958  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1959  			t.Align = c.ptrSize
  1960  		}
  1961  		t.C.Set("enum " + dt.EnumName)
  1962  		signed := 0
  1963  		t.EnumValues = make(map[string]int64)
  1964  		for _, ev := range dt.Val {
  1965  			t.EnumValues[ev.Name] = ev.Val
  1966  			if ev.Val < 0 {
  1967  				signed = signedDelta
  1968  			}
  1969  		}
  1970  		switch t.Size + int64(signed) {
  1971  		default:
  1972  			fatalf("%s: unexpected: %d-byte enum type - %s", lineno(pos), t.Size, dtype)
  1973  		case 1:
  1974  			t.Go = c.uint8
  1975  		case 2:
  1976  			t.Go = c.uint16
  1977  		case 4:
  1978  			t.Go = c.uint32
  1979  		case 8:
  1980  			t.Go = c.uint64
  1981  		case 1 + signedDelta:
  1982  			t.Go = c.int8
  1983  		case 2 + signedDelta:
  1984  			t.Go = c.int16
  1985  		case 4 + signedDelta:
  1986  			t.Go = c.int32
  1987  		case 8 + signedDelta:
  1988  			t.Go = c.int64
  1989  		}
  1990  
  1991  	case *dwarf.FloatType:
  1992  		switch t.Size {
  1993  		default:
  1994  			fatalf("%s: unexpected: %d-byte float type - %s", lineno(pos), t.Size, dtype)
  1995  		case 4:
  1996  			t.Go = c.float32
  1997  		case 8:
  1998  			t.Go = c.float64
  1999  		}
  2000  		if t.Align = t.Size; t.Align >= c.ptrSize {
  2001  			t.Align = c.ptrSize
  2002  		}
  2003  
  2004  	case *dwarf.ComplexType:
  2005  		switch t.Size {
  2006  		default:
  2007  			fatalf("%s: unexpected: %d-byte complex type - %s", lineno(pos), t.Size, dtype)
  2008  		case 8:
  2009  			t.Go = c.complex64
  2010  		case 16:
  2011  			t.Go = c.complex128
  2012  		}
  2013  		if t.Align = t.Size / 2; t.Align >= c.ptrSize {
  2014  			t.Align = c.ptrSize
  2015  		}
  2016  
  2017  	case *dwarf.FuncType:
  2018  		// No attempt at translation: would enable calls
  2019  		// directly between worlds, but we need to moderate those.
  2020  		t.Go = c.uintptr
  2021  		t.Align = c.ptrSize
  2022  
  2023  	case *dwarf.IntType:
  2024  		if dt.BitSize > 0 {
  2025  			fatalf("%s: unexpected: %d-bit int type - %s", lineno(pos), dt.BitSize, dtype)
  2026  		}
  2027  		switch t.Size {
  2028  		default:
  2029  			fatalf("%s: unexpected: %d-byte int type - %s", lineno(pos), t.Size, dtype)
  2030  		case 1:
  2031  			t.Go = c.int8
  2032  		case 2:
  2033  			t.Go = c.int16
  2034  		case 4:
  2035  			t.Go = c.int32
  2036  		case 8:
  2037  			t.Go = c.int64
  2038  		case 16:
  2039  			t.Go = &ast.ArrayType{
  2040  				Len: c.intExpr(t.Size),
  2041  				Elt: c.uint8,
  2042  			}
  2043  		}
  2044  		if t.Align = t.Size; t.Align >= c.ptrSize {
  2045  			t.Align = c.ptrSize
  2046  		}
  2047  
  2048  	case *dwarf.PtrType:
  2049  		// Clang doesn't emit DW_AT_byte_size for pointer types.
  2050  		if t.Size != c.ptrSize && t.Size != -1 {
  2051  			fatalf("%s: unexpected: %d-byte pointer type - %s", lineno(pos), t.Size, dtype)
  2052  		}
  2053  		t.Size = c.ptrSize
  2054  		t.Align = c.ptrSize
  2055  
  2056  		if _, ok := base(dt.Type).(*dwarf.VoidType); ok {
  2057  			t.Go = c.goVoidPtr
  2058  			t.C.Set("void*")
  2059  			dq := dt.Type
  2060  			for {
  2061  				if d, ok := dq.(*dwarf.QualType); ok {
  2062  					t.C.Set(d.Qual + " " + t.C.String())
  2063  					dq = d.Type
  2064  				} else {
  2065  					break
  2066  				}
  2067  			}
  2068  			break
  2069  		}
  2070  
  2071  		// Placeholder initialization; completed in FinishType.
  2072  		t.Go = &ast.StarExpr{}
  2073  		t.C.Set("<incomplete>*")
  2074  		if _, ok := c.ptrs[dt.Type]; !ok {
  2075  			c.ptrKeys = append(c.ptrKeys, dt.Type)
  2076  		}
  2077  		c.ptrs[dt.Type] = append(c.ptrs[dt.Type], t)
  2078  
  2079  	case *dwarf.QualType:
  2080  		t1 := c.Type(dt.Type, pos)
  2081  		t.Size = t1.Size
  2082  		t.Align = t1.Align
  2083  		t.Go = t1.Go
  2084  		if unionWithPointer[t1.Go] {
  2085  			unionWithPointer[t.Go] = true
  2086  		}
  2087  		t.EnumValues = nil
  2088  		t.Typedef = ""
  2089  		t.C.Set("%s "+dt.Qual, t1.C)
  2090  		return t
  2091  
  2092  	case *dwarf.StructType:
  2093  		// Convert to Go struct, being careful about alignment.
  2094  		// Have to give it a name to simulate C "struct foo" references.
  2095  		tag := dt.StructName
  2096  		if dt.ByteSize < 0 && tag == "" { // opaque unnamed struct - should not be possible
  2097  			break
  2098  		}
  2099  		if tag == "" {
  2100  			tag = "__" + strconv.Itoa(tagGen)
  2101  			tagGen++
  2102  		} else if t.C.Empty() {
  2103  			t.C.Set(dt.Kind + " " + tag)
  2104  		}
  2105  		name := c.Ident("_Ctype_" + dt.Kind + "_" + tag)
  2106  		t.Go = name // publish before recursive calls
  2107  		goIdent[name.Name] = name
  2108  		if dt.ByteSize < 0 {
  2109  			// Size calculation in c.Struct/c.Opaque will die with size=-1 (unknown),
  2110  			// so execute the basic things that the struct case would do
  2111  			// other than try to determine a Go representation.
  2112  			tt := *t
  2113  			tt.C = &TypeRepr{"%s %s", []interface{}{dt.Kind, tag}}
  2114  			tt.Go = c.Ident("struct{}")
  2115  			typedef[name.Name] = &tt
  2116  			break
  2117  		}
  2118  		switch dt.Kind {
  2119  		case "class", "union":
  2120  			t.Go = c.Opaque(t.Size)
  2121  			if c.dwarfHasPointer(dt, pos) {
  2122  				unionWithPointer[t.Go] = true
  2123  			}
  2124  			if t.C.Empty() {
  2125  				t.C.Set("__typeof__(unsigned char[%d])", t.Size)
  2126  			}
  2127  			t.Align = 1 // TODO: should probably base this on field alignment.
  2128  			typedef[name.Name] = t
  2129  		case "struct":
  2130  			g, csyntax, align := c.Struct(dt, pos)
  2131  			if t.C.Empty() {
  2132  				t.C.Set(csyntax)
  2133  			}
  2134  			t.Align = align
  2135  			tt := *t
  2136  			if tag != "" {
  2137  				tt.C = &TypeRepr{"struct %s", []interface{}{tag}}
  2138  			}
  2139  			tt.Go = g
  2140  			typedef[name.Name] = &tt
  2141  		}
  2142  
  2143  	case *dwarf.TypedefType:
  2144  		// Record typedef for printing.
  2145  		if dt.Name == "_GoString_" {
  2146  			// Special C name for Go string type.
  2147  			// Knows string layout used by compilers: pointer plus length,
  2148  			// which rounds up to 2 pointers after alignment.
  2149  			t.Go = c.string
  2150  			t.Size = c.ptrSize * 2
  2151  			t.Align = c.ptrSize
  2152  			break
  2153  		}
  2154  		if dt.Name == "_GoBytes_" {
  2155  			// Special C name for Go []byte type.
  2156  			// Knows slice layout used by compilers: pointer, length, cap.
  2157  			t.Go = c.Ident("[]byte")
  2158  			t.Size = c.ptrSize + 4 + 4
  2159  			t.Align = c.ptrSize
  2160  			break
  2161  		}
  2162  		name := c.Ident("_Ctype_" + dt.Name)
  2163  		goIdent[name.Name] = name
  2164  		sub := c.Type(dt.Type, pos)
  2165  		if c.badPointerTypedef(dt) {
  2166  			// Treat this typedef as a uintptr.
  2167  			s := *sub
  2168  			s.Go = c.uintptr
  2169  			sub = &s
  2170  			// Make sure we update any previously computed type.
  2171  			if oldType := typedef[name.Name]; oldType != nil {
  2172  				oldType.Go = sub.Go
  2173  			}
  2174  		}
  2175  		t.Go = name
  2176  		if unionWithPointer[sub.Go] {
  2177  			unionWithPointer[t.Go] = true
  2178  		}
  2179  		t.Size = sub.Size
  2180  		t.Align = sub.Align
  2181  		oldType := typedef[name.Name]
  2182  		if oldType == nil {
  2183  			tt := *t
  2184  			tt.Go = sub.Go
  2185  			typedef[name.Name] = &tt
  2186  		}
  2187  
  2188  		// If sub.Go.Name is "_Ctype_struct_foo" or "_Ctype_union_foo" or "_Ctype_class_foo",
  2189  		// use that as the Go form for this typedef too, so that the typedef will be interchangeable
  2190  		// with the base type.
  2191  		// In -godefs mode, do this for all typedefs.
  2192  		if isStructUnionClass(sub.Go) || *godefs {
  2193  			t.Go = sub.Go
  2194  
  2195  			if isStructUnionClass(sub.Go) {
  2196  				// Use the typedef name for C code.
  2197  				typedef[sub.Go.(*ast.Ident).Name].C = t.C
  2198  			}
  2199  
  2200  			// If we've seen this typedef before, and it
  2201  			// was an anonymous struct/union/class before
  2202  			// too, use the old definition.
  2203  			// TODO: it would be safer to only do this if
  2204  			// we verify that the types are the same.
  2205  			if oldType != nil && isStructUnionClass(oldType.Go) {
  2206  				t.Go = oldType.Go
  2207  			}
  2208  		}
  2209  
  2210  	case *dwarf.UcharType:
  2211  		if t.Size != 1 {
  2212  			fatalf("%s: unexpected: %d-byte uchar type - %s", lineno(pos), t.Size, dtype)
  2213  		}
  2214  		t.Go = c.uint8
  2215  		t.Align = 1
  2216  
  2217  	case *dwarf.UintType:
  2218  		if dt.BitSize > 0 {
  2219  			fatalf("%s: unexpected: %d-bit uint type - %s", lineno(pos), dt.BitSize, dtype)
  2220  		}
  2221  		switch t.Size {
  2222  		default:
  2223  			fatalf("%s: unexpected: %d-byte uint type - %s", lineno(pos), t.Size, dtype)
  2224  		case 1:
  2225  			t.Go = c.uint8
  2226  		case 2:
  2227  			t.Go = c.uint16
  2228  		case 4:
  2229  			t.Go = c.uint32
  2230  		case 8:
  2231  			t.Go = c.uint64
  2232  		case 16:
  2233  			t.Go = &ast.ArrayType{
  2234  				Len: c.intExpr(t.Size),
  2235  				Elt: c.uint8,
  2236  			}
  2237  		}
  2238  		if t.Align = t.Size; t.Align >= c.ptrSize {
  2239  			t.Align = c.ptrSize
  2240  		}
  2241  
  2242  	case *dwarf.VoidType:
  2243  		t.Go = c.goVoid
  2244  		t.C.Set("void")
  2245  		t.Align = 1
  2246  	}
  2247  
  2248  	switch dtype.(type) {
  2249  	case *dwarf.AddrType, *dwarf.BoolType, *dwarf.CharType, *dwarf.ComplexType, *dwarf.IntType, *dwarf.FloatType, *dwarf.UcharType, *dwarf.UintType:
  2250  		s := dtype.Common().Name
  2251  		if s != "" {
  2252  			if ss, ok := dwarfToName[s]; ok {
  2253  				s = ss
  2254  			}
  2255  			s = strings.Replace(s, " ", "", -1)
  2256  			name := c.Ident("_Ctype_" + s)
  2257  			tt := *t
  2258  			typedef[name.Name] = &tt
  2259  			if !*godefs {
  2260  				t.Go = name
  2261  			}
  2262  		}
  2263  	}
  2264  
  2265  	if t.Size < 0 {
  2266  		// Unsized types are [0]byte, unless they're typedefs of other types
  2267  		// or structs with tags.
  2268  		// if so, use the name we've already defined.
  2269  		t.Size = 0
  2270  		switch dt := dtype.(type) {
  2271  		case *dwarf.TypedefType:
  2272  			// ok
  2273  		case *dwarf.StructType:
  2274  			if dt.StructName != "" {
  2275  				break
  2276  			}
  2277  			t.Go = c.Opaque(0)
  2278  		default:
  2279  			t.Go = c.Opaque(0)
  2280  		}
  2281  		if t.C.Empty() {
  2282  			t.C.Set("void")
  2283  		}
  2284  	}
  2285  
  2286  	if t.C.Empty() {
  2287  		fatalf("%s: internal error: did not create C name for %s", lineno(pos), dtype)
  2288  	}
  2289  
  2290  	return t
  2291  }
  2292  
  2293  // isStructUnionClass reports whether the type described by the Go syntax x
  2294  // is a struct, union, or class with a tag.
  2295  func isStructUnionClass(x ast.Expr) bool {
  2296  	id, ok := x.(*ast.Ident)
  2297  	if !ok {
  2298  		return false
  2299  	}
  2300  	name := id.Name
  2301  	return strings.HasPrefix(name, "_Ctype_struct_") ||
  2302  		strings.HasPrefix(name, "_Ctype_union_") ||
  2303  		strings.HasPrefix(name, "_Ctype_class_")
  2304  }
  2305  
  2306  // FuncArg returns a Go type with the same memory layout as
  2307  // dtype when used as the type of a C function argument.
  2308  func (c *typeConv) FuncArg(dtype dwarf.Type, pos token.Pos) *Type {
  2309  	t := c.Type(unqual(dtype), pos)
  2310  	switch dt := dtype.(type) {
  2311  	case *dwarf.ArrayType:
  2312  		// Arrays are passed implicitly as pointers in C.
  2313  		// In Go, we must be explicit.
  2314  		tr := &TypeRepr{}
  2315  		tr.Set("%s*", t.C)
  2316  		return &Type{
  2317  			Size:  c.ptrSize,
  2318  			Align: c.ptrSize,
  2319  			Go:    &ast.StarExpr{X: t.Go},
  2320  			C:     tr,
  2321  		}
  2322  	case *dwarf.TypedefType:
  2323  		// C has much more relaxed rules than Go for
  2324  		// implicit type conversions. When the parameter
  2325  		// is type T defined as *X, simulate a little of the
  2326  		// laxness of C by making the argument *X instead of T.
  2327  		if ptr, ok := base(dt.Type).(*dwarf.PtrType); ok {
  2328  			// Unless the typedef happens to point to void* since
  2329  			// Go has special rules around using unsafe.Pointer.
  2330  			if _, void := base(ptr.Type).(*dwarf.VoidType); void {
  2331  				break
  2332  			}
  2333  			// ...or the typedef is one in which we expect bad pointers.
  2334  			// It will be a uintptr instead of *X.
  2335  			if c.baseBadPointerTypedef(dt) {
  2336  				break
  2337  			}
  2338  
  2339  			t = c.Type(ptr, pos)
  2340  			if t == nil {
  2341  				return nil
  2342  			}
  2343  
  2344  			// For a struct/union/class, remember the C spelling,
  2345  			// in case it has __attribute__((unavailable)).
  2346  			// See issue 2888.
  2347  			if isStructUnionClass(t.Go) {
  2348  				t.Typedef = dt.Name
  2349  			}
  2350  		}
  2351  	}
  2352  	return t
  2353  }
  2354  
  2355  // FuncType returns the Go type analogous to dtype.
  2356  // There is no guarantee about matching memory layout.
  2357  func (c *typeConv) FuncType(dtype *dwarf.FuncType, pos token.Pos) *FuncType {
  2358  	p := make([]*Type, len(dtype.ParamType))
  2359  	gp := make([]*ast.Field, len(dtype.ParamType))
  2360  	for i, f := range dtype.ParamType {
  2361  		// gcc's DWARF generator outputs a single DotDotDotType parameter for
  2362  		// function pointers that specify no parameters (e.g. void
  2363  		// (*__cgo_0)()).  Treat this special case as void. This case is
  2364  		// invalid according to ISO C anyway (i.e. void (*__cgo_1)(...) is not
  2365  		// legal).
  2366  		if _, ok := f.(*dwarf.DotDotDotType); ok && i == 0 {
  2367  			p, gp = nil, nil
  2368  			break
  2369  		}
  2370  		p[i] = c.FuncArg(f, pos)
  2371  		gp[i] = &ast.Field{Type: p[i].Go}
  2372  	}
  2373  	var r *Type
  2374  	var gr []*ast.Field
  2375  	if _, ok := base(dtype.ReturnType).(*dwarf.VoidType); ok {
  2376  		gr = []*ast.Field{{Type: c.goVoid}}
  2377  	} else if dtype.ReturnType != nil {
  2378  		r = c.Type(unqual(dtype.ReturnType), pos)
  2379  		gr = []*ast.Field{{Type: r.Go}}
  2380  	}
  2381  	return &FuncType{
  2382  		Params: p,
  2383  		Result: r,
  2384  		Go: &ast.FuncType{
  2385  			Params:  &ast.FieldList{List: gp},
  2386  			Results: &ast.FieldList{List: gr},
  2387  		},
  2388  	}
  2389  }
  2390  
  2391  // Identifier
  2392  func (c *typeConv) Ident(s string) *ast.Ident {
  2393  	return ast.NewIdent(s)
  2394  }
  2395  
  2396  // Opaque type of n bytes.
  2397  func (c *typeConv) Opaque(n int64) ast.Expr {
  2398  	return &ast.ArrayType{
  2399  		Len: c.intExpr(n),
  2400  		Elt: c.byte,
  2401  	}
  2402  }
  2403  
  2404  // Expr for integer n.
  2405  func (c *typeConv) intExpr(n int64) ast.Expr {
  2406  	return &ast.BasicLit{
  2407  		Kind:  token.INT,
  2408  		Value: strconv.FormatInt(n, 10),
  2409  	}
  2410  }
  2411  
  2412  // Add padding of given size to fld.
  2413  func (c *typeConv) pad(fld []*ast.Field, sizes []int64, size int64) ([]*ast.Field, []int64) {
  2414  	n := len(fld)
  2415  	fld = fld[0 : n+1]
  2416  	fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)}
  2417  	sizes = sizes[0 : n+1]
  2418  	sizes[n] = size
  2419  	return fld, sizes
  2420  }
  2421  
  2422  // Struct conversion: return Go and (gc) C syntax for type.
  2423  func (c *typeConv) Struct(dt *dwarf.StructType, pos token.Pos) (expr *ast.StructType, csyntax string, align int64) {
  2424  	// Minimum alignment for a struct is 1 byte.
  2425  	align = 1
  2426  
  2427  	var buf bytes.Buffer
  2428  	buf.WriteString("struct {")
  2429  	fld := make([]*ast.Field, 0, 2*len(dt.Field)+1) // enough for padding around every field
  2430  	sizes := make([]int64, 0, 2*len(dt.Field)+1)
  2431  	off := int64(0)
  2432  
  2433  	// Rename struct fields that happen to be named Go keywords into
  2434  	// _{keyword}.  Create a map from C ident -> Go ident. The Go ident will
  2435  	// be mangled. Any existing identifier that already has the same name on
  2436  	// the C-side will cause the Go-mangled version to be prefixed with _.
  2437  	// (e.g. in a struct with fields '_type' and 'type', the latter would be
  2438  	// rendered as '__type' in Go).
  2439  	ident := make(map[string]string)
  2440  	used := make(map[string]bool)
  2441  	for _, f := range dt.Field {
  2442  		ident[f.Name] = f.Name
  2443  		used[f.Name] = true
  2444  	}
  2445  
  2446  	if !*godefs {
  2447  		for cid, goid := range ident {
  2448  			if token.Lookup(goid).IsKeyword() {
  2449  				// Avoid keyword
  2450  				goid = "_" + goid
  2451  
  2452  				// Also avoid existing fields
  2453  				for _, exist := used[goid]; exist; _, exist = used[goid] {
  2454  					goid = "_" + goid
  2455  				}
  2456  
  2457  				used[goid] = true
  2458  				ident[cid] = goid
  2459  			}
  2460  		}
  2461  	}
  2462  
  2463  	anon := 0
  2464  	for _, f := range dt.Field {
  2465  		if f.ByteOffset > off {
  2466  			fld, sizes = c.pad(fld, sizes, f.ByteOffset-off)
  2467  			off = f.ByteOffset
  2468  		}
  2469  
  2470  		name := f.Name
  2471  		ft := f.Type
  2472  
  2473  		// In godefs mode, if this field is a C11
  2474  		// anonymous union then treat the first field in the
  2475  		// union as the field in the struct. This handles
  2476  		// cases like the glibc <sys/resource.h> file; see
  2477  		// issue 6677.
  2478  		if *godefs {
  2479  			if st, ok := f.Type.(*dwarf.StructType); ok && name == "" && st.Kind == "union" && len(st.Field) > 0 && !used[st.Field[0].Name] {
  2480  				name = st.Field[0].Name
  2481  				ident[name] = name
  2482  				ft = st.Field[0].Type
  2483  			}
  2484  		}
  2485  
  2486  		// TODO: Handle fields that are anonymous structs by
  2487  		// promoting the fields of the inner struct.
  2488  
  2489  		t := c.Type(ft, pos)
  2490  		tgo := t.Go
  2491  		size := t.Size
  2492  		talign := t.Align
  2493  		if f.BitSize > 0 {
  2494  			switch f.BitSize {
  2495  			case 8, 16, 32, 64:
  2496  			default:
  2497  				continue
  2498  			}
  2499  			size = f.BitSize / 8
  2500  			name := tgo.(*ast.Ident).String()
  2501  			if strings.HasPrefix(name, "int") {
  2502  				name = "int"
  2503  			} else {
  2504  				name = "uint"
  2505  			}
  2506  			tgo = ast.NewIdent(name + fmt.Sprint(f.BitSize))
  2507  			talign = size
  2508  		}
  2509  
  2510  		if talign > 0 && f.ByteOffset%talign != 0 {
  2511  			// Drop misaligned fields, the same way we drop integer bit fields.
  2512  			// The goal is to make available what can be made available.
  2513  			// Otherwise one bad and unneeded field in an otherwise okay struct
  2514  			// makes the whole program not compile. Much of the time these
  2515  			// structs are in system headers that cannot be corrected.
  2516  			continue
  2517  		}
  2518  		n := len(fld)
  2519  		fld = fld[0 : n+1]
  2520  		if name == "" {
  2521  			name = fmt.Sprintf("anon%d", anon)
  2522  			anon++
  2523  			ident[name] = name
  2524  		}
  2525  		fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[name])}, Type: tgo}
  2526  		sizes = sizes[0 : n+1]
  2527  		sizes[n] = size
  2528  		off += size
  2529  		buf.WriteString(t.C.String())
  2530  		buf.WriteString(" ")
  2531  		buf.WriteString(name)
  2532  		buf.WriteString("; ")
  2533  		if talign > align {
  2534  			align = talign
  2535  		}
  2536  	}
  2537  	if off < dt.ByteSize {
  2538  		fld, sizes = c.pad(fld, sizes, dt.ByteSize-off)
  2539  		off = dt.ByteSize
  2540  	}
  2541  
  2542  	// If the last field in a non-zero-sized struct is zero-sized
  2543  	// the compiler is going to pad it by one (see issue 9401).
  2544  	// We can't permit that, because then the size of the Go
  2545  	// struct will not be the same as the size of the C struct.
  2546  	// Our only option in such a case is to remove the field,
  2547  	// which means that it cannot be referenced from Go.
  2548  	for off > 0 && sizes[len(sizes)-1] == 0 {
  2549  		n := len(sizes)
  2550  		fld = fld[0 : n-1]
  2551  		sizes = sizes[0 : n-1]
  2552  	}
  2553  
  2554  	if off != dt.ByteSize {
  2555  		fatalf("%s: struct size calculation error off=%d bytesize=%d", lineno(pos), off, dt.ByteSize)
  2556  	}
  2557  	buf.WriteString("}")
  2558  	csyntax = buf.String()
  2559  
  2560  	if *godefs {
  2561  		godefsFields(fld)
  2562  	}
  2563  	expr = &ast.StructType{Fields: &ast.FieldList{List: fld}}
  2564  	return
  2565  }
  2566  
  2567  // dwarfHasPointer returns whether the DWARF type dt contains a pointer.
  2568  func (c *typeConv) dwarfHasPointer(dt dwarf.Type, pos token.Pos) bool {
  2569  	switch dt := dt.(type) {
  2570  	default:
  2571  		fatalf("%s: unexpected type: %s", lineno(pos), dt)
  2572  		return false
  2573  
  2574  	case *dwarf.AddrType, *dwarf.BoolType, *dwarf.CharType, *dwarf.EnumType,
  2575  		*dwarf.FloatType, *dwarf.ComplexType, *dwarf.FuncType,
  2576  		*dwarf.IntType, *dwarf.UcharType, *dwarf.UintType, *dwarf.VoidType:
  2577  
  2578  		return false
  2579  
  2580  	case *dwarf.ArrayType:
  2581  		return c.dwarfHasPointer(dt.Type, pos)
  2582  
  2583  	case *dwarf.PtrType:
  2584  		return true
  2585  
  2586  	case *dwarf.QualType:
  2587  		return c.dwarfHasPointer(dt.Type, pos)
  2588  
  2589  	case *dwarf.StructType:
  2590  		for _, f := range dt.Field {
  2591  			if c.dwarfHasPointer(f.Type, pos) {
  2592  				return true
  2593  			}
  2594  		}
  2595  		return false
  2596  
  2597  	case *dwarf.TypedefType:
  2598  		if dt.Name == "_GoString_" || dt.Name == "_GoBytes_" {
  2599  			return true
  2600  		}
  2601  		return c.dwarfHasPointer(dt.Type, pos)
  2602  	}
  2603  }
  2604  
  2605  func upper(s string) string {
  2606  	if s == "" {
  2607  		return ""
  2608  	}
  2609  	r, size := utf8.DecodeRuneInString(s)
  2610  	if r == '_' {
  2611  		return "X" + s
  2612  	}
  2613  	return string(unicode.ToUpper(r)) + s[size:]
  2614  }
  2615  
  2616  // godefsFields rewrites field names for use in Go or C definitions.
  2617  // It strips leading common prefixes (like tv_ in tv_sec, tv_usec)
  2618  // converts names to upper case, and rewrites _ into Pad_godefs_n,
  2619  // so that all fields are exported.
  2620  func godefsFields(fld []*ast.Field) {
  2621  	prefix := fieldPrefix(fld)
  2622  	npad := 0
  2623  	for _, f := range fld {
  2624  		for _, n := range f.Names {
  2625  			if n.Name != prefix {
  2626  				n.Name = strings.TrimPrefix(n.Name, prefix)
  2627  			}
  2628  			if n.Name == "_" {
  2629  				// Use exported name instead.
  2630  				n.Name = "Pad_cgo_" + strconv.Itoa(npad)
  2631  				npad++
  2632  			}
  2633  			n.Name = upper(n.Name)
  2634  		}
  2635  	}
  2636  }
  2637  
  2638  // fieldPrefix returns the prefix that should be removed from all the
  2639  // field names when generating the C or Go code. For generated
  2640  // C, we leave the names as is (tv_sec, tv_usec), since that's what
  2641  // people are used to seeing in C.  For generated Go code, such as
  2642  // package syscall's data structures, we drop a common prefix
  2643  // (so sec, usec, which will get turned into Sec, Usec for exporting).
  2644  func fieldPrefix(fld []*ast.Field) string {
  2645  	prefix := ""
  2646  	for _, f := range fld {
  2647  		for _, n := range f.Names {
  2648  			// Ignore field names that don't have the prefix we're
  2649  			// looking for. It is common in C headers to have fields
  2650  			// named, say, _pad in an otherwise prefixed header.
  2651  			// If the struct has 3 fields tv_sec, tv_usec, _pad1, then we
  2652  			// still want to remove the tv_ prefix.
  2653  			// The check for "orig_" here handles orig_eax in the
  2654  			// x86 ptrace register sets, which otherwise have all fields
  2655  			// with reg_ prefixes.
  2656  			if strings.HasPrefix(n.Name, "orig_") || strings.HasPrefix(n.Name, "_") {
  2657  				continue
  2658  			}
  2659  			i := strings.Index(n.Name, "_")
  2660  			if i < 0 {
  2661  				continue
  2662  			}
  2663  			if prefix == "" {
  2664  				prefix = n.Name[:i+1]
  2665  			} else if prefix != n.Name[:i+1] {
  2666  				return ""
  2667  			}
  2668  		}
  2669  	}
  2670  	return prefix
  2671  }
  2672  
  2673  // badPointerTypedef reports whether t is a C typedef that should not be considered a pointer in Go.
  2674  // A typedef is bad if C code sometimes stores non-pointers in this type.
  2675  // TODO: Currently our best solution is to find these manually and list them as
  2676  // they come up. A better solution is desired.
  2677  func (c *typeConv) badPointerTypedef(dt *dwarf.TypedefType) bool {
  2678  	if c.badCFType(dt) {
  2679  		return true
  2680  	}
  2681  	if c.badJNI(dt) {
  2682  		return true
  2683  	}
  2684  	return false
  2685  }
  2686  
  2687  // baseBadPointerTypedef reports whether the base of a chain of typedefs is a bad typedef
  2688  // as badPointerTypedef reports.
  2689  func (c *typeConv) baseBadPointerTypedef(dt *dwarf.TypedefType) bool {
  2690  	for {
  2691  		if t, ok := dt.Type.(*dwarf.TypedefType); ok {
  2692  			dt = t
  2693  			continue
  2694  		}
  2695  		break
  2696  	}
  2697  	return c.badPointerTypedef(dt)
  2698  }
  2699  
  2700  func (c *typeConv) badCFType(dt *dwarf.TypedefType) bool {
  2701  	// The real bad types are CFNumberRef and CFDateRef.
  2702  	// Sometimes non-pointers are stored in these types.
  2703  	// CFTypeRef is a supertype of those, so it can have bad pointers in it as well.
  2704  	// We return true for the other *Ref types just so casting between them is easier.
  2705  	// We identify the correct set of types as those ending in Ref and for which
  2706  	// there exists a corresponding GetTypeID function.
  2707  	// See comment below for details about the bad pointers.
  2708  	if goos != "darwin" {
  2709  		return false
  2710  	}
  2711  	s := dt.Name
  2712  	if !strings.HasSuffix(s, "Ref") {
  2713  		return false
  2714  	}
  2715  	s = s[:len(s)-3]
  2716  	if s == "CFType" {
  2717  		return true
  2718  	}
  2719  	if c.getTypeIDs[s] {
  2720  		return true
  2721  	}
  2722  	if i := strings.Index(s, "Mutable"); i >= 0 && c.getTypeIDs[s[:i]+s[i+7:]] {
  2723  		// Mutable and immutable variants share a type ID.
  2724  		return true
  2725  	}
  2726  	return false
  2727  }
  2728  
  2729  // Comment from Darwin's CFInternal.h
  2730  /*
  2731  // Tagged pointer support
  2732  // Low-bit set means tagged object, next 3 bits (currently)
  2733  // define the tagged object class, next 4 bits are for type
  2734  // information for the specific tagged object class.  Thus,
  2735  // the low byte is for type info, and the rest of a pointer
  2736  // (32 or 64-bit) is for payload, whatever the tagged class.
  2737  //
  2738  // Note that the specific integers used to identify the
  2739  // specific tagged classes can and will change from release
  2740  // to release (that's why this stuff is in CF*Internal*.h),
  2741  // as can the definition of type info vs payload above.
  2742  //
  2743  #if __LP64__
  2744  #define CF_IS_TAGGED_OBJ(PTR)	((uintptr_t)(PTR) & 0x1)
  2745  #define CF_TAGGED_OBJ_TYPE(PTR)	((uintptr_t)(PTR) & 0xF)
  2746  #else
  2747  #define CF_IS_TAGGED_OBJ(PTR)	0
  2748  #define CF_TAGGED_OBJ_TYPE(PTR)	0
  2749  #endif
  2750  
  2751  enum {
  2752      kCFTaggedObjectID_Invalid = 0,
  2753      kCFTaggedObjectID_Atom = (0 << 1) + 1,
  2754      kCFTaggedObjectID_Undefined3 = (1 << 1) + 1,
  2755      kCFTaggedObjectID_Undefined2 = (2 << 1) + 1,
  2756      kCFTaggedObjectID_Integer = (3 << 1) + 1,
  2757      kCFTaggedObjectID_DateTS = (4 << 1) + 1,
  2758      kCFTaggedObjectID_ManagedObjectID = (5 << 1) + 1, // Core Data
  2759      kCFTaggedObjectID_Date = (6 << 1) + 1,
  2760      kCFTaggedObjectID_Undefined7 = (7 << 1) + 1,
  2761  };
  2762  */
  2763  
  2764  func (c *typeConv) badJNI(dt *dwarf.TypedefType) bool {
  2765  	// In Dalvik and ART, the jobject type in the JNI interface of the JVM has the
  2766  	// property that it is sometimes (always?) a small integer instead of a real pointer.
  2767  	// Note: although only the android JVMs are bad in this respect, we declare the JNI types
  2768  	// bad regardless of platform, so the same Go code compiles on both android and non-android.
  2769  	if parent, ok := jniTypes[dt.Name]; ok {
  2770  		// Try to make sure we're talking about a JNI type, not just some random user's
  2771  		// type that happens to use the same name.
  2772  		// C doesn't have the notion of a package, so it's hard to be certain.
  2773  
  2774  		// Walk up to jobject, checking each typedef on the way.
  2775  		w := dt
  2776  		for parent != "" {
  2777  			t, ok := w.Type.(*dwarf.TypedefType)
  2778  			if !ok || t.Name != parent {
  2779  				return false
  2780  			}
  2781  			w = t
  2782  			parent, ok = jniTypes[w.Name]
  2783  			if !ok {
  2784  				return false
  2785  			}
  2786  		}
  2787  
  2788  		// Check that the typedef is either:
  2789  		// 1:
  2790  		//     	struct _jobject;
  2791  		//     	typedef struct _jobject *jobject;
  2792  		// 2: (in NDK16 in C++)
  2793  		//     	class _jobject {};
  2794  		//     	typedef _jobject* jobject;
  2795  		// 3: (in NDK16 in C)
  2796  		//     	typedef void* jobject;
  2797  		if ptr, ok := w.Type.(*dwarf.PtrType); ok {
  2798  			switch v := ptr.Type.(type) {
  2799  			case *dwarf.VoidType:
  2800  				return true
  2801  			case *dwarf.StructType:
  2802  				if v.StructName == "_jobject" && len(v.Field) == 0 {
  2803  					switch v.Kind {
  2804  					case "struct":
  2805  						if v.Incomplete {
  2806  							return true
  2807  						}
  2808  					case "class":
  2809  						if !v.Incomplete {
  2810  							return true
  2811  						}
  2812  					}
  2813  				}
  2814  			}
  2815  		}
  2816  	}
  2817  	return false
  2818  }
  2819  
  2820  // jniTypes maps from JNI types that we want to be uintptrs, to the underlying type to which
  2821  // they are mapped. The base "jobject" maps to the empty string.
  2822  var jniTypes = map[string]string{
  2823  	"jobject":       "",
  2824  	"jclass":        "jobject",
  2825  	"jthrowable":    "jobject",
  2826  	"jstring":       "jobject",
  2827  	"jarray":        "jobject",
  2828  	"jbooleanArray": "jarray",
  2829  	"jbyteArray":    "jarray",
  2830  	"jcharArray":    "jarray",
  2831  	"jshortArray":   "jarray",
  2832  	"jintArray":     "jarray",
  2833  	"jlongArray":    "jarray",
  2834  	"jfloatArray":   "jarray",
  2835  	"jdoubleArray":  "jarray",
  2836  	"jobjectArray":  "jarray",
  2837  	"jweak":         "jobject",
  2838  }
  2839  

View as plain text