github.com/aloncn/graphics-go@v0.0.1/src/cmd/cgo/gcc.go (about)

     1  // Copyright 2009 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // 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  	"os"
    24  	"strconv"
    25  	"strings"
    26  	"unicode"
    27  	"unicode/utf8"
    28  )
    29  
    30  var debugDefine = flag.Bool("debug-define", false, "print relevant #defines")
    31  var debugGcc = flag.Bool("debug-gcc", false, "print gcc invocations")
    32  
    33  var nameToC = map[string]string{
    34  	"schar":         "signed char",
    35  	"uchar":         "unsigned char",
    36  	"ushort":        "unsigned short",
    37  	"uint":          "unsigned int",
    38  	"ulong":         "unsigned long",
    39  	"longlong":      "long long",
    40  	"ulonglong":     "unsigned long long",
    41  	"complexfloat":  "float _Complex",
    42  	"complexdouble": "double _Complex",
    43  }
    44  
    45  // cname returns the C name to use for C.s.
    46  // The expansions are listed in nameToC and also
    47  // struct_foo becomes "struct foo", and similarly for
    48  // union and enum.
    49  func cname(s string) string {
    50  	if t, ok := nameToC[s]; ok {
    51  		return t
    52  	}
    53  
    54  	if strings.HasPrefix(s, "struct_") {
    55  		return "struct " + s[len("struct_"):]
    56  	}
    57  	if strings.HasPrefix(s, "union_") {
    58  		return "union " + s[len("union_"):]
    59  	}
    60  	if strings.HasPrefix(s, "enum_") {
    61  		return "enum " + s[len("enum_"):]
    62  	}
    63  	if strings.HasPrefix(s, "sizeof_") {
    64  		return "sizeof(" + cname(s[len("sizeof_"):]) + ")"
    65  	}
    66  	return s
    67  }
    68  
    69  // DiscardCgoDirectives processes the import C preamble, and discards
    70  // all #cgo CFLAGS and LDFLAGS directives, so they don't make their
    71  // way into _cgo_export.h.
    72  func (f *File) DiscardCgoDirectives() {
    73  	linesIn := strings.Split(f.Preamble, "\n")
    74  	linesOut := make([]string, 0, len(linesIn))
    75  	for _, line := range linesIn {
    76  		l := strings.TrimSpace(line)
    77  		if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(rune(l[4])) {
    78  			linesOut = append(linesOut, line)
    79  		} else {
    80  			linesOut = append(linesOut, "")
    81  		}
    82  	}
    83  	f.Preamble = strings.Join(linesOut, "\n")
    84  }
    85  
    86  // addToFlag appends args to flag.  All flags are later written out onto the
    87  // _cgo_flags file for the build system to use.
    88  func (p *Package) addToFlag(flag string, args []string) {
    89  	p.CgoFlags[flag] = append(p.CgoFlags[flag], args...)
    90  	if flag == "CFLAGS" {
    91  		// We'll also need these when preprocessing for dwarf information.
    92  		p.GccOptions = append(p.GccOptions, args...)
    93  	}
    94  }
    95  
    96  // splitQuoted splits the string s around each instance of one or more consecutive
    97  // white space characters while taking into account quotes and escaping, and
    98  // returns an array of substrings of s or an empty list if s contains only white space.
    99  // Single quotes and double quotes are recognized to prevent splitting within the
   100  // quoted region, and are removed from the resulting substrings. If a quote in s
   101  // isn't closed err will be set and r will have the unclosed argument as the
   102  // last element.  The backslash is used for escaping.
   103  //
   104  // For example, the following string:
   105  //
   106  //     `a b:"c d" 'e''f'  "g\""`
   107  //
   108  // Would be parsed as:
   109  //
   110  //     []string{"a", "b:c d", "ef", `g"`}
   111  //
   112  func splitQuoted(s string) (r []string, err error) {
   113  	var args []string
   114  	arg := make([]rune, len(s))
   115  	escaped := false
   116  	quoted := false
   117  	quote := '\x00'
   118  	i := 0
   119  	for _, r := range s {
   120  		switch {
   121  		case escaped:
   122  			escaped = false
   123  		case r == '\\':
   124  			escaped = true
   125  			continue
   126  		case quote != 0:
   127  			if r == quote {
   128  				quote = 0
   129  				continue
   130  			}
   131  		case r == '"' || r == '\'':
   132  			quoted = true
   133  			quote = r
   134  			continue
   135  		case unicode.IsSpace(r):
   136  			if quoted || i > 0 {
   137  				quoted = false
   138  				args = append(args, string(arg[:i]))
   139  				i = 0
   140  			}
   141  			continue
   142  		}
   143  		arg[i] = r
   144  		i++
   145  	}
   146  	if quoted || i > 0 {
   147  		args = append(args, string(arg[:i]))
   148  	}
   149  	if quote != 0 {
   150  		err = errors.New("unclosed quote")
   151  	} else if escaped {
   152  		err = errors.New("unfinished escaping")
   153  	}
   154  	return args, err
   155  }
   156  
   157  // Translate rewrites f.AST, the original Go input, to remove
   158  // references to the imported package C, replacing them with
   159  // references to the equivalent Go types, functions, and variables.
   160  func (p *Package) Translate(f *File) {
   161  	for _, cref := range f.Ref {
   162  		// Convert C.ulong to C.unsigned long, etc.
   163  		cref.Name.C = cname(cref.Name.Go)
   164  	}
   165  	p.loadDefines(f)
   166  	needType := p.guessKinds(f)
   167  	if len(needType) > 0 {
   168  		p.loadDWARF(f, needType)
   169  	}
   170  	p.rewriteCalls(f)
   171  	p.rewriteRef(f)
   172  }
   173  
   174  // loadDefines coerces gcc into spitting out the #defines in use
   175  // in the file f and saves relevant renamings in f.Name[name].Define.
   176  func (p *Package) loadDefines(f *File) {
   177  	var b bytes.Buffer
   178  	b.WriteString(f.Preamble)
   179  	b.WriteString(builtinProlog)
   180  	stdout := p.gccDefines(b.Bytes())
   181  
   182  	for _, line := range strings.Split(stdout, "\n") {
   183  		if len(line) < 9 || line[0:7] != "#define" {
   184  			continue
   185  		}
   186  
   187  		line = strings.TrimSpace(line[8:])
   188  
   189  		var key, val string
   190  		spaceIndex := strings.Index(line, " ")
   191  		tabIndex := strings.Index(line, "\t")
   192  
   193  		if spaceIndex == -1 && tabIndex == -1 {
   194  			continue
   195  		} else if tabIndex == -1 || (spaceIndex != -1 && spaceIndex < tabIndex) {
   196  			key = line[0:spaceIndex]
   197  			val = strings.TrimSpace(line[spaceIndex:])
   198  		} else {
   199  			key = line[0:tabIndex]
   200  			val = strings.TrimSpace(line[tabIndex:])
   201  		}
   202  
   203  		if key == "__clang__" {
   204  			p.GccIsClang = true
   205  		}
   206  
   207  		if n := f.Name[key]; n != nil {
   208  			if *debugDefine {
   209  				fmt.Fprintf(os.Stderr, "#define %s %s\n", key, val)
   210  			}
   211  			n.Define = val
   212  		}
   213  	}
   214  }
   215  
   216  // guessKinds tricks gcc into revealing the kind of each
   217  // name xxx for the references C.xxx in the Go input.
   218  // The kind is either a constant, type, or variable.
   219  func (p *Package) guessKinds(f *File) []*Name {
   220  	// Determine kinds for names we already know about,
   221  	// like #defines or 'struct foo', before bothering with gcc.
   222  	var names, needType []*Name
   223  	for _, key := range nameKeys(f.Name) {
   224  		n := f.Name[key]
   225  		// If we've already found this name as a #define
   226  		// and we can translate it as a constant value, do so.
   227  		if n.Define != "" {
   228  			isConst := false
   229  			if _, err := strconv.Atoi(n.Define); err == nil {
   230  				isConst = true
   231  			} else if n.Define[0] == '"' || n.Define[0] == '\'' {
   232  				if _, err := parser.ParseExpr(n.Define); err == nil {
   233  					isConst = true
   234  				}
   235  			}
   236  			if isConst {
   237  				n.Kind = "const"
   238  				// Turn decimal into hex, just for consistency
   239  				// with enum-derived constants.  Otherwise
   240  				// in the cgo -godefs output half the constants
   241  				// are in hex and half are in whatever the #define used.
   242  				i, err := strconv.ParseInt(n.Define, 0, 64)
   243  				if err == nil {
   244  					n.Const = fmt.Sprintf("%#x", i)
   245  				} else {
   246  					n.Const = n.Define
   247  				}
   248  				continue
   249  			}
   250  
   251  			if isName(n.Define) {
   252  				n.C = n.Define
   253  			}
   254  		}
   255  
   256  		needType = append(needType, n)
   257  
   258  		// If this is a struct, union, or enum type name, no need to guess the kind.
   259  		if strings.HasPrefix(n.C, "struct ") || strings.HasPrefix(n.C, "union ") || strings.HasPrefix(n.C, "enum ") {
   260  			n.Kind = "type"
   261  			continue
   262  		}
   263  
   264  		// Otherwise, we'll need to find out from gcc.
   265  		names = append(names, n)
   266  	}
   267  
   268  	// Bypass gcc if there's nothing left to find out.
   269  	if len(names) == 0 {
   270  		return needType
   271  	}
   272  
   273  	// Coerce gcc into telling us whether each name is a type, a value, or undeclared.
   274  	// For names, find out whether they are integer constants.
   275  	// We used to look at specific warning or error messages here, but that tied the
   276  	// behavior too closely to specific versions of the compilers.
   277  	// Instead, arrange that we can infer what we need from only the presence or absence
   278  	// of an error on a specific line.
   279  	//
   280  	// For each name, we generate these lines, where xxx is the index in toSniff plus one.
   281  	//
   282  	//	#line xxx "not-declared"
   283  	//	void __cgo_f_xxx_1(void) { __typeof__(name) *__cgo_undefined__; }
   284  	//	#line xxx "not-type"
   285  	//	void __cgo_f_xxx_2(void) { name *__cgo_undefined__; }
   286  	//	#line xxx "not-const"
   287  	//	void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (name)*1 }; }
   288  	//
   289  	// If we see an error at not-declared:xxx, the corresponding name is not declared.
   290  	// If we see an error at not-type:xxx, the corresponding name is a type.
   291  	// If we see an error at not-const:xxx, the corresponding name is not an integer constant.
   292  	// If we see no errors, we assume the name is an expression but not a constant
   293  	// (so a variable or a function).
   294  	//
   295  	// The specific input forms are chosen so that they are valid C syntax regardless of
   296  	// whether name denotes a type or an expression.
   297  
   298  	var b bytes.Buffer
   299  	b.WriteString(f.Preamble)
   300  	b.WriteString(builtinProlog)
   301  
   302  	for i, n := range names {
   303  		fmt.Fprintf(&b, "#line %d \"not-declared\"\n"+
   304  			"void __cgo_f_%d_1(void) { __typeof__(%s) *__cgo_undefined__; }\n"+
   305  			"#line %d \"not-type\"\n"+
   306  			"void __cgo_f_%d_2(void) { %s *__cgo_undefined__; }\n"+
   307  			"#line %d \"not-const\"\n"+
   308  			"void __cgo_f_%d_3(void) { enum { __cgo__undefined__ = (%s)*1 }; }\n",
   309  			i+1, i+1, n.C,
   310  			i+1, i+1, n.C,
   311  			i+1, i+1, n.C)
   312  	}
   313  	fmt.Fprintf(&b, "#line 1 \"completed\"\n"+
   314  		"int __cgo__1 = __cgo__2;\n")
   315  
   316  	stderr := p.gccErrors(b.Bytes())
   317  	if stderr == "" {
   318  		fatalf("%s produced no output\non input:\n%s", p.gccBaseCmd()[0], b.Bytes())
   319  	}
   320  
   321  	completed := false
   322  	sniff := make([]int, len(names))
   323  	const (
   324  		notType = 1 << iota
   325  		notConst
   326  		notDeclared
   327  	)
   328  	for _, line := range strings.Split(stderr, "\n") {
   329  		if !strings.Contains(line, ": error:") {
   330  			// we only care about errors.
   331  			// we tried to turn off warnings on the command line, but one never knows.
   332  			continue
   333  		}
   334  
   335  		c1 := strings.Index(line, ":")
   336  		if c1 < 0 {
   337  			continue
   338  		}
   339  		c2 := strings.Index(line[c1+1:], ":")
   340  		if c2 < 0 {
   341  			continue
   342  		}
   343  		c2 += c1 + 1
   344  
   345  		filename := line[:c1]
   346  		i, _ := strconv.Atoi(line[c1+1 : c2])
   347  		i--
   348  		if i < 0 || i >= len(names) {
   349  			continue
   350  		}
   351  
   352  		switch filename {
   353  		case "completed":
   354  			// Strictly speaking, there is no guarantee that seeing the error at completed:1
   355  			// (at the end of the file) means we've seen all the errors from earlier in the file,
   356  			// but usually it does. Certainly if we don't see the completed:1 error, we did
   357  			// not get all the errors we expected.
   358  			completed = true
   359  
   360  		case "not-declared":
   361  			sniff[i] |= notDeclared
   362  		case "not-type":
   363  			sniff[i] |= notType
   364  		case "not-const":
   365  			sniff[i] |= notConst
   366  		}
   367  	}
   368  
   369  	if !completed {
   370  		fatalf("%s did not produce error at completed:1\non input:\n%s\nfull error output:\n%s", p.gccBaseCmd()[0], b.Bytes(), stderr)
   371  	}
   372  
   373  	for i, n := range names {
   374  		switch sniff[i] {
   375  		default:
   376  			error_(token.NoPos, "could not determine kind of name for C.%s", fixGo(n.Go))
   377  		case notType:
   378  			n.Kind = "const"
   379  		case notConst:
   380  			n.Kind = "type"
   381  		case notConst | notType:
   382  			n.Kind = "not-type"
   383  		}
   384  	}
   385  	if nerrors > 0 {
   386  		// Check if compiling the preamble by itself causes any errors,
   387  		// because the messages we've printed out so far aren't helpful
   388  		// to users debugging preamble mistakes.  See issue 8442.
   389  		preambleErrors := p.gccErrors([]byte(f.Preamble))
   390  		if len(preambleErrors) > 0 {
   391  			error_(token.NoPos, "\n%s errors for preamble:\n%s", p.gccBaseCmd()[0], preambleErrors)
   392  		}
   393  
   394  		fatalf("unresolved names")
   395  	}
   396  
   397  	needType = append(needType, names...)
   398  	return needType
   399  }
   400  
   401  // loadDWARF parses the DWARF debug information generated
   402  // by gcc to learn the details of the constants, variables, and types
   403  // being referred to as C.xxx.
   404  func (p *Package) loadDWARF(f *File, names []*Name) {
   405  	// Extract the types from the DWARF section of an object
   406  	// from a well-formed C program.  Gcc only generates DWARF info
   407  	// for symbols in the object file, so it is not enough to print the
   408  	// preamble and hope the symbols we care about will be there.
   409  	// Instead, emit
   410  	//	__typeof__(names[i]) *__cgo__i;
   411  	// for each entry in names and then dereference the type we
   412  	// learn for __cgo__i.
   413  	var b bytes.Buffer
   414  	b.WriteString(f.Preamble)
   415  	b.WriteString(builtinProlog)
   416  	for i, n := range names {
   417  		fmt.Fprintf(&b, "__typeof__(%s) *__cgo__%d;\n", n.C, i)
   418  		if n.Kind == "const" {
   419  			fmt.Fprintf(&b, "enum { __cgo_enum__%d = %s };\n", i, n.C)
   420  		}
   421  	}
   422  
   423  	// Apple's LLVM-based gcc does not include the enumeration
   424  	// names and values in its DWARF debug output.  In case we're
   425  	// using such a gcc, create a data block initialized with the values.
   426  	// We can read them out of the object file.
   427  	fmt.Fprintf(&b, "long long __cgodebug_data[] = {\n")
   428  	for _, n := range names {
   429  		if n.Kind == "const" {
   430  			fmt.Fprintf(&b, "\t%s,\n", n.C)
   431  		} else {
   432  			fmt.Fprintf(&b, "\t0,\n")
   433  		}
   434  	}
   435  	// for the last entry, we can not use 0, otherwise
   436  	// in case all __cgodebug_data is zero initialized,
   437  	// LLVM-based gcc will place the it in the __DATA.__common
   438  	// zero-filled section (our debug/macho doesn't support
   439  	// this)
   440  	fmt.Fprintf(&b, "\t1\n")
   441  	fmt.Fprintf(&b, "};\n")
   442  
   443  	d, bo, debugData := p.gccDebug(b.Bytes())
   444  	enumVal := make([]int64, len(debugData)/8)
   445  	for i := range enumVal {
   446  		enumVal[i] = int64(bo.Uint64(debugData[i*8:]))
   447  	}
   448  
   449  	// Scan DWARF info for top-level TagVariable entries with AttrName __cgo__i.
   450  	types := make([]dwarf.Type, len(names))
   451  	enums := make([]dwarf.Offset, len(names))
   452  	nameToIndex := make(map[*Name]int)
   453  	for i, n := range names {
   454  		nameToIndex[n] = i
   455  	}
   456  	nameToRef := make(map[*Name]*Ref)
   457  	for _, ref := range f.Ref {
   458  		nameToRef[ref.Name] = ref
   459  	}
   460  	r := d.Reader()
   461  	for {
   462  		e, err := r.Next()
   463  		if err != nil {
   464  			fatalf("reading DWARF entry: %s", err)
   465  		}
   466  		if e == nil {
   467  			break
   468  		}
   469  		switch e.Tag {
   470  		case dwarf.TagEnumerationType:
   471  			offset := e.Offset
   472  			for {
   473  				e, err := r.Next()
   474  				if err != nil {
   475  					fatalf("reading DWARF entry: %s", err)
   476  				}
   477  				if e.Tag == 0 {
   478  					break
   479  				}
   480  				if e.Tag == dwarf.TagEnumerator {
   481  					entryName := e.Val(dwarf.AttrName).(string)
   482  					if strings.HasPrefix(entryName, "__cgo_enum__") {
   483  						n, _ := strconv.Atoi(entryName[len("__cgo_enum__"):])
   484  						if 0 <= n && n < len(names) {
   485  							enums[n] = offset
   486  						}
   487  					}
   488  				}
   489  			}
   490  		case dwarf.TagVariable:
   491  			name, _ := e.Val(dwarf.AttrName).(string)
   492  			typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset)
   493  			if name == "" || typOff == 0 {
   494  				if e.Val(dwarf.AttrSpecification) != nil {
   495  					// Since we are reading all the DWARF,
   496  					// assume we will see the variable elsewhere.
   497  					break
   498  				}
   499  				fatalf("malformed DWARF TagVariable entry")
   500  			}
   501  			if !strings.HasPrefix(name, "__cgo__") {
   502  				break
   503  			}
   504  			typ, err := d.Type(typOff)
   505  			if err != nil {
   506  				fatalf("loading DWARF type: %s", err)
   507  			}
   508  			t, ok := typ.(*dwarf.PtrType)
   509  			if !ok || t == nil {
   510  				fatalf("internal error: %s has non-pointer type", name)
   511  			}
   512  			i, err := strconv.Atoi(name[7:])
   513  			if err != nil {
   514  				fatalf("malformed __cgo__ name: %s", name)
   515  			}
   516  			if enums[i] != 0 {
   517  				t, err := d.Type(enums[i])
   518  				if err != nil {
   519  					fatalf("loading DWARF type: %s", err)
   520  				}
   521  				types[i] = t
   522  			} else {
   523  				types[i] = t.Type
   524  			}
   525  		}
   526  		if e.Tag != dwarf.TagCompileUnit {
   527  			r.SkipChildren()
   528  		}
   529  	}
   530  
   531  	// Record types and typedef information.
   532  	var conv typeConv
   533  	conv.Init(p.PtrSize, p.IntSize)
   534  	for i, n := range names {
   535  		if types[i] == nil {
   536  			continue
   537  		}
   538  		pos := token.NoPos
   539  		if ref, ok := nameToRef[n]; ok {
   540  			pos = ref.Pos()
   541  		}
   542  		f, fok := types[i].(*dwarf.FuncType)
   543  		if n.Kind != "type" && fok {
   544  			n.Kind = "func"
   545  			n.FuncType = conv.FuncType(f, pos)
   546  		} else {
   547  			n.Type = conv.Type(types[i], pos)
   548  			if enums[i] != 0 && n.Type.EnumValues != nil {
   549  				k := fmt.Sprintf("__cgo_enum__%d", i)
   550  				n.Kind = "const"
   551  				n.Const = fmt.Sprintf("%#x", n.Type.EnumValues[k])
   552  				// Remove injected enum to ensure the value will deep-compare
   553  				// equally in future loads of the same constant.
   554  				delete(n.Type.EnumValues, k)
   555  			}
   556  			// Prefer debug data over DWARF debug output, if we have it.
   557  			if n.Kind == "const" && i < len(enumVal) {
   558  				n.Const = fmt.Sprintf("%#x", enumVal[i])
   559  			}
   560  		}
   561  		conv.FinishType(pos)
   562  	}
   563  }
   564  
   565  // mangleName does name mangling to translate names
   566  // from the original Go source files to the names
   567  // used in the final Go files generated by cgo.
   568  func (p *Package) mangleName(n *Name) {
   569  	// When using gccgo variables have to be
   570  	// exported so that they become global symbols
   571  	// that the C code can refer to.
   572  	prefix := "_C"
   573  	if *gccgo && n.IsVar() {
   574  		prefix = "C"
   575  	}
   576  	n.Mangle = prefix + n.Kind + "_" + n.Go
   577  }
   578  
   579  // rewriteCalls rewrites all calls that pass pointers to check that
   580  // they follow the rules for passing pointers between Go and C.
   581  func (p *Package) rewriteCalls(f *File) {
   582  	for _, call := range f.Calls {
   583  		// This is a call to C.xxx; set goname to "xxx".
   584  		goname := call.Fun.(*ast.SelectorExpr).Sel.Name
   585  		if goname == "malloc" {
   586  			continue
   587  		}
   588  		name := f.Name[goname]
   589  		if name.Kind != "func" {
   590  			// Probably a type conversion.
   591  			continue
   592  		}
   593  		p.rewriteCall(f, call, name)
   594  	}
   595  }
   596  
   597  // rewriteCall rewrites one call to add pointer checks.  We replace
   598  // each pointer argument x with _cgoCheckPointer(x).(T).
   599  func (p *Package) rewriteCall(f *File, call *ast.CallExpr, name *Name) {
   600  	for i, param := range name.FuncType.Params {
   601  		if len(call.Args) <= i {
   602  			// Avoid a crash; this will be caught when the
   603  			// generated file is compiled.
   604  			return
   605  		}
   606  
   607  		// An untyped nil does not need a pointer check, and
   608  		// when _cgoCheckPointer returns the untyped nil the
   609  		// type assertion we are going to insert will fail.
   610  		// Easier to just skip nil arguments.
   611  		// TODO: Note that this fails if nil is shadowed.
   612  		if id, ok := call.Args[i].(*ast.Ident); ok && id.Name == "nil" {
   613  			continue
   614  		}
   615  
   616  		if !p.needsPointerCheck(f, param.Go) {
   617  			continue
   618  		}
   619  
   620  		c := &ast.CallExpr{
   621  			Fun: ast.NewIdent("_cgoCheckPointer"),
   622  			Args: []ast.Expr{
   623  				call.Args[i],
   624  			},
   625  		}
   626  
   627  		// Add optional additional arguments for an address
   628  		// expression.
   629  		c.Args = p.checkAddrArgs(f, c.Args, call.Args[i])
   630  
   631  		// _cgoCheckPointer returns interface{}.
   632  		// We need to type assert that to the type we want.
   633  		// If the Go version of this C type uses
   634  		// unsafe.Pointer, we can't use a type assertion,
   635  		// because the Go file might not import unsafe.
   636  		// Instead we use a local variant of _cgoCheckPointer.
   637  
   638  		var arg ast.Expr
   639  		if n := p.unsafeCheckPointerName(param.Go); n != "" {
   640  			c.Fun = ast.NewIdent(n)
   641  			arg = c
   642  		} else {
   643  			// In order for the type assertion to succeed,
   644  			// we need it to match the actual type of the
   645  			// argument.  The only type we have is the
   646  			// type of the function parameter.  We know
   647  			// that the argument type must be assignable
   648  			// to the function parameter type, or the code
   649  			// would not compile, but there is nothing
   650  			// requiring that the types be exactly the
   651  			// same.  Add a type conversion to the
   652  			// argument so that the type assertion will
   653  			// succeed.
   654  			c.Args[0] = &ast.CallExpr{
   655  				Fun: param.Go,
   656  				Args: []ast.Expr{
   657  					c.Args[0],
   658  				},
   659  			}
   660  
   661  			arg = &ast.TypeAssertExpr{
   662  				X:    c,
   663  				Type: param.Go,
   664  			}
   665  		}
   666  
   667  		call.Args[i] = arg
   668  	}
   669  }
   670  
   671  // needsPointerCheck returns whether the type t needs a pointer check.
   672  // This is true if t is a pointer and if the value to which it points
   673  // might contain a pointer.
   674  func (p *Package) needsPointerCheck(f *File, t ast.Expr) bool {
   675  	return p.hasPointer(f, t, true)
   676  }
   677  
   678  // hasPointer is used by needsPointerCheck.  If top is true it returns
   679  // whether t is or contains a pointer that might point to a pointer.
   680  // If top is false it returns whether t is or contains a pointer.
   681  // f may be nil.
   682  func (p *Package) hasPointer(f *File, t ast.Expr, top bool) bool {
   683  	switch t := t.(type) {
   684  	case *ast.ArrayType:
   685  		if t.Len == nil {
   686  			if !top {
   687  				return true
   688  			}
   689  			return p.hasPointer(f, t.Elt, false)
   690  		}
   691  		return p.hasPointer(f, t.Elt, top)
   692  	case *ast.StructType:
   693  		for _, field := range t.Fields.List {
   694  			if p.hasPointer(f, field.Type, top) {
   695  				return true
   696  			}
   697  		}
   698  		return false
   699  	case *ast.StarExpr: // Pointer type.
   700  		if !top {
   701  			return true
   702  		}
   703  		return p.hasPointer(f, t.X, false)
   704  	case *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
   705  		return true
   706  	case *ast.Ident:
   707  		// TODO: Handle types defined within function.
   708  		for _, d := range p.Decl {
   709  			gd, ok := d.(*ast.GenDecl)
   710  			if !ok || gd.Tok != token.TYPE {
   711  				continue
   712  			}
   713  			for _, spec := range gd.Specs {
   714  				ts, ok := spec.(*ast.TypeSpec)
   715  				if !ok {
   716  					continue
   717  				}
   718  				if ts.Name.Name == t.Name {
   719  					return p.hasPointer(f, ts.Type, top)
   720  				}
   721  			}
   722  		}
   723  		if def := typedef[t.Name]; def != nil {
   724  			return p.hasPointer(f, def.Go, top)
   725  		}
   726  		if t.Name == "string" {
   727  			return !top
   728  		}
   729  		if t.Name == "error" {
   730  			return true
   731  		}
   732  		if goTypes[t.Name] != nil {
   733  			return false
   734  		}
   735  		// We can't figure out the type.  Conservative
   736  		// approach is to assume it has a pointer.
   737  		return true
   738  	case *ast.SelectorExpr:
   739  		if l, ok := t.X.(*ast.Ident); !ok || l.Name != "C" {
   740  			// Type defined in a different package.
   741  			// Conservative approach is to assume it has a
   742  			// pointer.
   743  			return true
   744  		}
   745  		if f == nil {
   746  			// Conservative approach: assume pointer.
   747  			return true
   748  		}
   749  		name := f.Name[t.Sel.Name]
   750  		if name != nil && name.Kind == "type" && name.Type != nil && name.Type.Go != nil {
   751  			return p.hasPointer(f, name.Type.Go, top)
   752  		}
   753  		// We can't figure out the type.  Conservative
   754  		// approach is to assume it has a pointer.
   755  		return true
   756  	default:
   757  		error_(t.Pos(), "could not understand type %s", gofmt(t))
   758  		return true
   759  	}
   760  }
   761  
   762  // checkAddrArgs tries to add arguments to the call of
   763  // _cgoCheckPointer when the argument is an address expression.  We
   764  // pass true to mean that the argument is an address operation of
   765  // something other than a slice index, which means that it's only
   766  // necessary to check the specific element pointed to, not the entire
   767  // object.  This is for &s.f, where f is a field in a struct.  We can
   768  // pass a slice or array, meaning that we should check the entire
   769  // slice or array but need not check any other part of the object.
   770  // This is for &s.a[i], where we need to check all of a.  However, we
   771  // only pass the slice or array if we can refer to it without side
   772  // effects.
   773  func (p *Package) checkAddrArgs(f *File, args []ast.Expr, x ast.Expr) []ast.Expr {
   774  	// Strip type conversions.
   775  	for {
   776  		c, ok := x.(*ast.CallExpr)
   777  		if !ok || len(c.Args) != 1 || !p.isType(c.Fun) {
   778  			break
   779  		}
   780  		x = c.Args[0]
   781  	}
   782  	u, ok := x.(*ast.UnaryExpr)
   783  	if !ok || u.Op != token.AND {
   784  		return args
   785  	}
   786  	index, ok := u.X.(*ast.IndexExpr)
   787  	if !ok {
   788  		// This is the address of something that is not an
   789  		// index expression.  We only need to examine the
   790  		// single value to which it points.
   791  		// TODO: what if true is shadowed?
   792  		return append(args, ast.NewIdent("true"))
   793  	}
   794  	if !p.hasSideEffects(f, index.X) {
   795  		// Examine the entire slice.
   796  		return append(args, index.X)
   797  	}
   798  	// Treat the pointer as unknown.
   799  	return args
   800  }
   801  
   802  // hasSideEffects returns whether the expression x has any side
   803  // effects.  x is an expression, not a statement, so the only side
   804  // effect is a function call.
   805  func (p *Package) hasSideEffects(f *File, x ast.Expr) bool {
   806  	found := false
   807  	f.walk(x, "expr",
   808  		func(f *File, x interface{}, context string) {
   809  			switch x.(type) {
   810  			case *ast.CallExpr:
   811  				found = true
   812  			}
   813  		})
   814  	return found
   815  }
   816  
   817  // isType returns whether the expression is definitely a type.
   818  // This is conservative--it returns false for an unknown identifier.
   819  func (p *Package) isType(t ast.Expr) bool {
   820  	switch t := t.(type) {
   821  	case *ast.SelectorExpr:
   822  		id, ok := t.X.(*ast.Ident)
   823  		if !ok {
   824  			return false
   825  		}
   826  		if id.Name == "unsafe" && t.Sel.Name == "Pointer" {
   827  			return true
   828  		}
   829  		if id.Name == "C" && typedef["_Ctype_"+t.Sel.Name] != nil {
   830  			return true
   831  		}
   832  		return false
   833  	case *ast.Ident:
   834  		// TODO: This ignores shadowing.
   835  		switch t.Name {
   836  		case "unsafe.Pointer", "bool", "byte",
   837  			"complex64", "complex128",
   838  			"error",
   839  			"float32", "float64",
   840  			"int", "int8", "int16", "int32", "int64",
   841  			"rune", "string",
   842  			"uint", "uint8", "uint16", "uint32", "uint64", "uintptr":
   843  
   844  			return true
   845  		}
   846  	case *ast.StarExpr:
   847  		return p.isType(t.X)
   848  	case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType,
   849  		*ast.MapType, *ast.ChanType:
   850  
   851  		return true
   852  	}
   853  	return false
   854  }
   855  
   856  // unsafeCheckPointerName is given the Go version of a C type.  If the
   857  // type uses unsafe.Pointer, we arrange to build a version of
   858  // _cgoCheckPointer that returns that type.  This avoids using a type
   859  // assertion to unsafe.Pointer in our copy of user code.  We return
   860  // the name of the _cgoCheckPointer function we are going to build, or
   861  // the empty string if the type does not use unsafe.Pointer.
   862  func (p *Package) unsafeCheckPointerName(t ast.Expr) string {
   863  	if !p.hasUnsafePointer(t) {
   864  		return ""
   865  	}
   866  	var buf bytes.Buffer
   867  	conf.Fprint(&buf, fset, t)
   868  	s := buf.String()
   869  	for i, t := range p.CgoChecks {
   870  		if s == t {
   871  			return p.unsafeCheckPointerNameIndex(i)
   872  		}
   873  	}
   874  	p.CgoChecks = append(p.CgoChecks, s)
   875  	return p.unsafeCheckPointerNameIndex(len(p.CgoChecks) - 1)
   876  }
   877  
   878  // hasUnsafePointer returns whether the Go type t uses unsafe.Pointer.
   879  // t is the Go version of a C type, so we don't need to handle every case.
   880  // We only care about direct references, not references via typedefs.
   881  func (p *Package) hasUnsafePointer(t ast.Expr) bool {
   882  	switch t := t.(type) {
   883  	case *ast.Ident:
   884  		// We don't see a SelectorExpr for unsafe.Pointer;
   885  		// this is created by code in this file.
   886  		return t.Name == "unsafe.Pointer"
   887  	case *ast.ArrayType:
   888  		return p.hasUnsafePointer(t.Elt)
   889  	case *ast.StructType:
   890  		for _, f := range t.Fields.List {
   891  			if p.hasUnsafePointer(f.Type) {
   892  				return true
   893  			}
   894  		}
   895  	case *ast.StarExpr: // Pointer type.
   896  		return p.hasUnsafePointer(t.X)
   897  	}
   898  	return false
   899  }
   900  
   901  // unsafeCheckPointerNameIndex returns the name to use for a
   902  // _cgoCheckPointer variant based on the index in the CgoChecks slice.
   903  func (p *Package) unsafeCheckPointerNameIndex(i int) string {
   904  	return fmt.Sprintf("_cgoCheckPointer%d", i)
   905  }
   906  
   907  // rewriteRef rewrites all the C.xxx references in f.AST to refer to the
   908  // Go equivalents, now that we have figured out the meaning of all
   909  // the xxx.  In *godefs mode, rewriteRef replaces the names
   910  // with full definitions instead of mangled names.
   911  func (p *Package) rewriteRef(f *File) {
   912  	// Keep a list of all the functions, to remove the ones
   913  	// only used as expressions and avoid generating bridge
   914  	// code for them.
   915  	functions := make(map[string]bool)
   916  
   917  	// Assign mangled names.
   918  	for _, n := range f.Name {
   919  		if n.Kind == "not-type" {
   920  			n.Kind = "var"
   921  		}
   922  		if n.Mangle == "" {
   923  			p.mangleName(n)
   924  		}
   925  		if n.Kind == "func" {
   926  			functions[n.Go] = false
   927  		}
   928  	}
   929  
   930  	// Now that we have all the name types filled in,
   931  	// scan through the Refs to identify the ones that
   932  	// are trying to do a ,err call.  Also check that
   933  	// functions are only used in calls.
   934  	for _, r := range f.Ref {
   935  		if r.Name.Kind == "const" && r.Name.Const == "" {
   936  			error_(r.Pos(), "unable to find value of constant C.%s", fixGo(r.Name.Go))
   937  		}
   938  		var expr ast.Expr = ast.NewIdent(r.Name.Mangle) // default
   939  		switch r.Context {
   940  		case "call", "call2":
   941  			if r.Name.Kind != "func" {
   942  				if r.Name.Kind == "type" {
   943  					r.Context = "type"
   944  					if r.Name.Type == nil {
   945  						error_(r.Pos(), "invalid conversion to C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
   946  						break
   947  					}
   948  					expr = r.Name.Type.Go
   949  					break
   950  				}
   951  				error_(r.Pos(), "call of non-function C.%s", fixGo(r.Name.Go))
   952  				break
   953  			}
   954  			functions[r.Name.Go] = true
   955  			if r.Context == "call2" {
   956  				if r.Name.Go == "_CMalloc" {
   957  					error_(r.Pos(), "no two-result form for C.malloc")
   958  					break
   959  				}
   960  				// Invent new Name for the two-result function.
   961  				n := f.Name["2"+r.Name.Go]
   962  				if n == nil {
   963  					n = new(Name)
   964  					*n = *r.Name
   965  					n.AddError = true
   966  					n.Mangle = "_C2func_" + n.Go
   967  					f.Name["2"+r.Name.Go] = n
   968  				}
   969  				expr = ast.NewIdent(n.Mangle)
   970  				r.Name = n
   971  				break
   972  			}
   973  		case "expr":
   974  			if r.Name.Kind == "func" {
   975  				// Function is being used in an expression, to e.g. pass around a C function pointer.
   976  				// Create a new Name for this Ref which causes the variable to be declared in Go land.
   977  				fpName := "fp_" + r.Name.Go
   978  				name := f.Name[fpName]
   979  				if name == nil {
   980  					name = &Name{
   981  						Go:   fpName,
   982  						C:    r.Name.C,
   983  						Kind: "fpvar",
   984  						Type: &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*"), Go: ast.NewIdent("unsafe.Pointer")},
   985  					}
   986  					p.mangleName(name)
   987  					f.Name[fpName] = name
   988  				}
   989  				r.Name = name
   990  				// Rewrite into call to _Cgo_ptr to prevent assignments.  The _Cgo_ptr
   991  				// function is defined in out.go and simply returns its argument. See
   992  				// issue 7757.
   993  				expr = &ast.CallExpr{
   994  					Fun:  &ast.Ident{NamePos: (*r.Expr).Pos(), Name: "_Cgo_ptr"},
   995  					Args: []ast.Expr{ast.NewIdent(name.Mangle)},
   996  				}
   997  			} else if r.Name.Kind == "type" {
   998  				// Okay - might be new(T)
   999  				if r.Name.Type == nil {
  1000  					error_(r.Pos(), "expression C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
  1001  					break
  1002  				}
  1003  				expr = r.Name.Type.Go
  1004  			} else if r.Name.Kind == "var" {
  1005  				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
  1006  			}
  1007  
  1008  		case "selector":
  1009  			if r.Name.Kind == "var" {
  1010  				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
  1011  			} else {
  1012  				error_(r.Pos(), "only C variables allowed in selector expression", fixGo(r.Name.Go))
  1013  			}
  1014  
  1015  		case "type":
  1016  			if r.Name.Kind != "type" {
  1017  				error_(r.Pos(), "expression C.%s used as type", fixGo(r.Name.Go))
  1018  			} else if r.Name.Type == nil {
  1019  				// Use of C.enum_x, C.struct_x or C.union_x without C definition.
  1020  				// GCC won't raise an error when using pointers to such unknown types.
  1021  				error_(r.Pos(), "type C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
  1022  			} else {
  1023  				expr = r.Name.Type.Go
  1024  			}
  1025  		default:
  1026  			if r.Name.Kind == "func" {
  1027  				error_(r.Pos(), "must call C.%s", fixGo(r.Name.Go))
  1028  			}
  1029  		}
  1030  		if *godefs {
  1031  			// Substitute definition for mangled type name.
  1032  			if id, ok := expr.(*ast.Ident); ok {
  1033  				if t := typedef[id.Name]; t != nil {
  1034  					expr = t.Go
  1035  				}
  1036  				if id.Name == r.Name.Mangle && r.Name.Const != "" {
  1037  					expr = ast.NewIdent(r.Name.Const)
  1038  				}
  1039  			}
  1040  		}
  1041  
  1042  		// Copy position information from old expr into new expr,
  1043  		// in case expression being replaced is first on line.
  1044  		// See golang.org/issue/6563.
  1045  		pos := (*r.Expr).Pos()
  1046  		switch x := expr.(type) {
  1047  		case *ast.Ident:
  1048  			expr = &ast.Ident{NamePos: pos, Name: x.Name}
  1049  		}
  1050  
  1051  		*r.Expr = expr
  1052  	}
  1053  
  1054  	// Remove functions only used as expressions, so their respective
  1055  	// bridge functions are not generated.
  1056  	for name, used := range functions {
  1057  		if !used {
  1058  			delete(f.Name, name)
  1059  		}
  1060  	}
  1061  }
  1062  
  1063  // gccBaseCmd returns the start of the compiler command line.
  1064  // It uses $CC if set, or else $GCC, or else the compiler recorded
  1065  // during the initial build as defaultCC.
  1066  // defaultCC is defined in zdefaultcc.go, written by cmd/dist.
  1067  func (p *Package) gccBaseCmd() []string {
  1068  	// Use $CC if set, since that's what the build uses.
  1069  	if ret := strings.Fields(os.Getenv("CC")); len(ret) > 0 {
  1070  		return ret
  1071  	}
  1072  	// Try $GCC if set, since that's what we used to use.
  1073  	if ret := strings.Fields(os.Getenv("GCC")); len(ret) > 0 {
  1074  		return ret
  1075  	}
  1076  	return strings.Fields(defaultCC)
  1077  }
  1078  
  1079  // gccMachine returns the gcc -m flag to use, either "-m32", "-m64" or "-marm".
  1080  func (p *Package) gccMachine() []string {
  1081  	switch goarch {
  1082  	case "amd64":
  1083  		return []string{"-m64"}
  1084  	case "386":
  1085  		return []string{"-m32"}
  1086  	case "arm":
  1087  		return []string{"-marm"} // not thumb
  1088  	case "s390":
  1089  		return []string{"-m31"}
  1090  	case "s390x":
  1091  		return []string{"-m64"}
  1092  	}
  1093  	return nil
  1094  }
  1095  
  1096  func gccTmp() string {
  1097  	return *objDir + "_cgo_.o"
  1098  }
  1099  
  1100  // gccCmd returns the gcc command line to use for compiling
  1101  // the input.
  1102  func (p *Package) gccCmd() []string {
  1103  	c := append(p.gccBaseCmd(),
  1104  		"-w",          // no warnings
  1105  		"-Wno-error",  // warnings are not errors
  1106  		"-o"+gccTmp(), // write object to tmp
  1107  		"-gdwarf-2",   // generate DWARF v2 debugging symbols
  1108  		"-c",          // do not link
  1109  		"-xc",         // input language is C
  1110  	)
  1111  	if p.GccIsClang {
  1112  		c = append(c,
  1113  			"-ferror-limit=0",
  1114  			// Apple clang version 1.7 (tags/Apple/clang-77) (based on LLVM 2.9svn)
  1115  			// doesn't have -Wno-unneeded-internal-declaration, so we need yet another
  1116  			// flag to disable the warning. Yes, really good diagnostics, clang.
  1117  			"-Wno-unknown-warning-option",
  1118  			"-Wno-unneeded-internal-declaration",
  1119  			"-Wno-unused-function",
  1120  			"-Qunused-arguments",
  1121  			// Clang embeds prototypes for some builtin functions,
  1122  			// like malloc and calloc, but all size_t parameters are
  1123  			// incorrectly typed unsigned long. We work around that
  1124  			// by disabling the builtin functions (this is safe as
  1125  			// it won't affect the actual compilation of the C code).
  1126  			// See: https://golang.org/issue/6506.
  1127  			"-fno-builtin",
  1128  		)
  1129  	}
  1130  
  1131  	c = append(c, p.GccOptions...)
  1132  	c = append(c, p.gccMachine()...)
  1133  	c = append(c, "-") //read input from standard input
  1134  	return c
  1135  }
  1136  
  1137  // gccDebug runs gcc -gdwarf-2 over the C program stdin and
  1138  // returns the corresponding DWARF data and, if present, debug data block.
  1139  func (p *Package) gccDebug(stdin []byte) (*dwarf.Data, binary.ByteOrder, []byte) {
  1140  	runGcc(stdin, p.gccCmd())
  1141  
  1142  	isDebugData := func(s string) bool {
  1143  		// Some systems use leading _ to denote non-assembly symbols.
  1144  		return s == "__cgodebug_data" || s == "___cgodebug_data"
  1145  	}
  1146  
  1147  	if f, err := macho.Open(gccTmp()); err == nil {
  1148  		defer f.Close()
  1149  		d, err := f.DWARF()
  1150  		if err != nil {
  1151  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1152  		}
  1153  		var data []byte
  1154  		if f.Symtab != nil {
  1155  			for i := range f.Symtab.Syms {
  1156  				s := &f.Symtab.Syms[i]
  1157  				if isDebugData(s.Name) {
  1158  					// Found it.  Now find data section.
  1159  					if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
  1160  						sect := f.Sections[i]
  1161  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1162  							if sdat, err := sect.Data(); err == nil {
  1163  								data = sdat[s.Value-sect.Addr:]
  1164  							}
  1165  						}
  1166  					}
  1167  				}
  1168  			}
  1169  		}
  1170  		return d, f.ByteOrder, data
  1171  	}
  1172  
  1173  	if f, err := elf.Open(gccTmp()); err == nil {
  1174  		defer f.Close()
  1175  		d, err := f.DWARF()
  1176  		if err != nil {
  1177  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1178  		}
  1179  		var data []byte
  1180  		symtab, err := f.Symbols()
  1181  		if err == nil {
  1182  			for i := range symtab {
  1183  				s := &symtab[i]
  1184  				if isDebugData(s.Name) {
  1185  					// Found it.  Now find data section.
  1186  					if i := int(s.Section); 0 <= i && i < len(f.Sections) {
  1187  						sect := f.Sections[i]
  1188  						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
  1189  							if sdat, err := sect.Data(); err == nil {
  1190  								data = sdat[s.Value-sect.Addr:]
  1191  							}
  1192  						}
  1193  					}
  1194  				}
  1195  			}
  1196  		}
  1197  		return d, f.ByteOrder, data
  1198  	}
  1199  
  1200  	if f, err := pe.Open(gccTmp()); err == nil {
  1201  		defer f.Close()
  1202  		d, err := f.DWARF()
  1203  		if err != nil {
  1204  			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
  1205  		}
  1206  		var data []byte
  1207  		for _, s := range f.Symbols {
  1208  			if isDebugData(s.Name) {
  1209  				if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
  1210  					sect := f.Sections[i]
  1211  					if s.Value < sect.Size {
  1212  						if sdat, err := sect.Data(); err == nil {
  1213  							data = sdat[s.Value:]
  1214  						}
  1215  					}
  1216  				}
  1217  			}
  1218  		}
  1219  		return d, binary.LittleEndian, data
  1220  	}
  1221  
  1222  	fatalf("cannot parse gcc output %s as ELF, Mach-O, PE object", gccTmp())
  1223  	panic("not reached")
  1224  }
  1225  
  1226  // gccDefines runs gcc -E -dM -xc - over the C program stdin
  1227  // and returns the corresponding standard output, which is the
  1228  // #defines that gcc encountered while processing the input
  1229  // and its included files.
  1230  func (p *Package) gccDefines(stdin []byte) string {
  1231  	base := append(p.gccBaseCmd(), "-E", "-dM", "-xc")
  1232  	base = append(base, p.gccMachine()...)
  1233  	stdout, _ := runGcc(stdin, append(append(base, p.GccOptions...), "-"))
  1234  	return stdout
  1235  }
  1236  
  1237  // gccErrors runs gcc over the C program stdin and returns
  1238  // the errors that gcc prints.  That is, this function expects
  1239  // gcc to fail.
  1240  func (p *Package) gccErrors(stdin []byte) string {
  1241  	// TODO(rsc): require failure
  1242  	args := p.gccCmd()
  1243  
  1244  	if *debugGcc {
  1245  		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " "))
  1246  		os.Stderr.Write(stdin)
  1247  		fmt.Fprint(os.Stderr, "EOF\n")
  1248  	}
  1249  	stdout, stderr, _ := run(stdin, args)
  1250  	if *debugGcc {
  1251  		os.Stderr.Write(stdout)
  1252  		os.Stderr.Write(stderr)
  1253  	}
  1254  	return string(stderr)
  1255  }
  1256  
  1257  // runGcc runs the gcc command line args with stdin on standard input.
  1258  // If the command exits with a non-zero exit status, runGcc prints
  1259  // details about what was run and exits.
  1260  // Otherwise runGcc returns the data written to standard output and standard error.
  1261  // Note that for some of the uses we expect useful data back
  1262  // on standard error, but for those uses gcc must still exit 0.
  1263  func runGcc(stdin []byte, args []string) (string, string) {
  1264  	if *debugGcc {
  1265  		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " "))
  1266  		os.Stderr.Write(stdin)
  1267  		fmt.Fprint(os.Stderr, "EOF\n")
  1268  	}
  1269  	stdout, stderr, ok := run(stdin, args)
  1270  	if *debugGcc {
  1271  		os.Stderr.Write(stdout)
  1272  		os.Stderr.Write(stderr)
  1273  	}
  1274  	if !ok {
  1275  		os.Stderr.Write(stderr)
  1276  		os.Exit(2)
  1277  	}
  1278  	return string(stdout), string(stderr)
  1279  }
  1280  
  1281  // A typeConv is a translator from dwarf types to Go types
  1282  // with equivalent memory layout.
  1283  type typeConv struct {
  1284  	// Cache of already-translated or in-progress types.
  1285  	m       map[dwarf.Type]*Type
  1286  	typedef map[string]ast.Expr
  1287  
  1288  	// Map from types to incomplete pointers to those types.
  1289  	ptrs map[dwarf.Type][]*Type
  1290  	// Keys of ptrs in insertion order (deterministic worklist)
  1291  	ptrKeys []dwarf.Type
  1292  
  1293  	// Predeclared types.
  1294  	bool                                   ast.Expr
  1295  	byte                                   ast.Expr // denotes padding
  1296  	int8, int16, int32, int64              ast.Expr
  1297  	uint8, uint16, uint32, uint64, uintptr ast.Expr
  1298  	float32, float64                       ast.Expr
  1299  	complex64, complex128                  ast.Expr
  1300  	void                                   ast.Expr
  1301  	string                                 ast.Expr
  1302  	goVoid                                 ast.Expr // _Ctype_void, denotes C's void
  1303  	goVoidPtr                              ast.Expr // unsafe.Pointer or *byte
  1304  
  1305  	ptrSize int64
  1306  	intSize int64
  1307  }
  1308  
  1309  var tagGen int
  1310  var typedef = make(map[string]*Type)
  1311  var goIdent = make(map[string]*ast.Ident)
  1312  
  1313  func (c *typeConv) Init(ptrSize, intSize int64) {
  1314  	c.ptrSize = ptrSize
  1315  	c.intSize = intSize
  1316  	c.m = make(map[dwarf.Type]*Type)
  1317  	c.ptrs = make(map[dwarf.Type][]*Type)
  1318  	c.bool = c.Ident("bool")
  1319  	c.byte = c.Ident("byte")
  1320  	c.int8 = c.Ident("int8")
  1321  	c.int16 = c.Ident("int16")
  1322  	c.int32 = c.Ident("int32")
  1323  	c.int64 = c.Ident("int64")
  1324  	c.uint8 = c.Ident("uint8")
  1325  	c.uint16 = c.Ident("uint16")
  1326  	c.uint32 = c.Ident("uint32")
  1327  	c.uint64 = c.Ident("uint64")
  1328  	c.uintptr = c.Ident("uintptr")
  1329  	c.float32 = c.Ident("float32")
  1330  	c.float64 = c.Ident("float64")
  1331  	c.complex64 = c.Ident("complex64")
  1332  	c.complex128 = c.Ident("complex128")
  1333  	c.void = c.Ident("void")
  1334  	c.string = c.Ident("string")
  1335  	c.goVoid = c.Ident("_Ctype_void")
  1336  
  1337  	// Normally cgo translates void* to unsafe.Pointer,
  1338  	// but for historical reasons -godefs uses *byte instead.
  1339  	if *godefs {
  1340  		c.goVoidPtr = &ast.StarExpr{X: c.byte}
  1341  	} else {
  1342  		c.goVoidPtr = c.Ident("unsafe.Pointer")
  1343  	}
  1344  }
  1345  
  1346  // base strips away qualifiers and typedefs to get the underlying type
  1347  func base(dt dwarf.Type) dwarf.Type {
  1348  	for {
  1349  		if d, ok := dt.(*dwarf.QualType); ok {
  1350  			dt = d.Type
  1351  			continue
  1352  		}
  1353  		if d, ok := dt.(*dwarf.TypedefType); ok {
  1354  			dt = d.Type
  1355  			continue
  1356  		}
  1357  		break
  1358  	}
  1359  	return dt
  1360  }
  1361  
  1362  // Map from dwarf text names to aliases we use in package "C".
  1363  var dwarfToName = map[string]string{
  1364  	"long int":               "long",
  1365  	"long unsigned int":      "ulong",
  1366  	"unsigned int":           "uint",
  1367  	"short unsigned int":     "ushort",
  1368  	"unsigned short":         "ushort", // Used by Clang; issue 13129.
  1369  	"short int":              "short",
  1370  	"long long int":          "longlong",
  1371  	"long long unsigned int": "ulonglong",
  1372  	"signed char":            "schar",
  1373  	"unsigned char":          "uchar",
  1374  }
  1375  
  1376  const signedDelta = 64
  1377  
  1378  // String returns the current type representation.  Format arguments
  1379  // are assembled within this method so that any changes in mutable
  1380  // values are taken into account.
  1381  func (tr *TypeRepr) String() string {
  1382  	if len(tr.Repr) == 0 {
  1383  		return ""
  1384  	}
  1385  	if len(tr.FormatArgs) == 0 {
  1386  		return tr.Repr
  1387  	}
  1388  	return fmt.Sprintf(tr.Repr, tr.FormatArgs...)
  1389  }
  1390  
  1391  // Empty reports whether the result of String would be "".
  1392  func (tr *TypeRepr) Empty() bool {
  1393  	return len(tr.Repr) == 0
  1394  }
  1395  
  1396  // Set modifies the type representation.
  1397  // If fargs are provided, repr is used as a format for fmt.Sprintf.
  1398  // Otherwise, repr is used unprocessed as the type representation.
  1399  func (tr *TypeRepr) Set(repr string, fargs ...interface{}) {
  1400  	tr.Repr = repr
  1401  	tr.FormatArgs = fargs
  1402  }
  1403  
  1404  // FinishType completes any outstanding type mapping work.
  1405  // In particular, it resolves incomplete pointer types.
  1406  func (c *typeConv) FinishType(pos token.Pos) {
  1407  	// Completing one pointer type might produce more to complete.
  1408  	// Keep looping until they're all done.
  1409  	for len(c.ptrKeys) > 0 {
  1410  		dtype := c.ptrKeys[0]
  1411  		c.ptrKeys = c.ptrKeys[1:]
  1412  
  1413  		// Note Type might invalidate c.ptrs[dtype].
  1414  		t := c.Type(dtype, pos)
  1415  		for _, ptr := range c.ptrs[dtype] {
  1416  			ptr.Go.(*ast.StarExpr).X = t.Go
  1417  			ptr.C.Set("%s*", t.C)
  1418  		}
  1419  		c.ptrs[dtype] = nil // retain the map key
  1420  	}
  1421  }
  1422  
  1423  // Type returns a *Type with the same memory layout as
  1424  // dtype when used as the type of a variable or a struct field.
  1425  func (c *typeConv) Type(dtype dwarf.Type, pos token.Pos) *Type {
  1426  	if t, ok := c.m[dtype]; ok {
  1427  		if t.Go == nil {
  1428  			fatalf("%s: type conversion loop at %s", lineno(pos), dtype)
  1429  		}
  1430  		return t
  1431  	}
  1432  
  1433  	t := new(Type)
  1434  	t.Size = dtype.Size() // note: wrong for array of pointers, corrected below
  1435  	t.Align = -1
  1436  	t.C = &TypeRepr{Repr: dtype.Common().Name}
  1437  	c.m[dtype] = t
  1438  
  1439  	switch dt := dtype.(type) {
  1440  	default:
  1441  		fatalf("%s: unexpected type: %s", lineno(pos), dtype)
  1442  
  1443  	case *dwarf.AddrType:
  1444  		if t.Size != c.ptrSize {
  1445  			fatalf("%s: unexpected: %d-byte address type - %s", lineno(pos), t.Size, dtype)
  1446  		}
  1447  		t.Go = c.uintptr
  1448  		t.Align = t.Size
  1449  
  1450  	case *dwarf.ArrayType:
  1451  		if dt.StrideBitSize > 0 {
  1452  			// Cannot represent bit-sized elements in Go.
  1453  			t.Go = c.Opaque(t.Size)
  1454  			break
  1455  		}
  1456  		count := dt.Count
  1457  		if count == -1 {
  1458  			// Indicates flexible array member, which Go doesn't support.
  1459  			// Translate to zero-length array instead.
  1460  			count = 0
  1461  		}
  1462  		sub := c.Type(dt.Type, pos)
  1463  		t.Align = sub.Align
  1464  		t.Go = &ast.ArrayType{
  1465  			Len: c.intExpr(count),
  1466  			Elt: sub.Go,
  1467  		}
  1468  		// Recalculate t.Size now that we know sub.Size.
  1469  		t.Size = count * sub.Size
  1470  		t.C.Set("__typeof__(%s[%d])", sub.C, dt.Count)
  1471  
  1472  	case *dwarf.BoolType:
  1473  		t.Go = c.bool
  1474  		t.Align = 1
  1475  
  1476  	case *dwarf.CharType:
  1477  		if t.Size != 1 {
  1478  			fatalf("%s: unexpected: %d-byte char type - %s", lineno(pos), t.Size, dtype)
  1479  		}
  1480  		t.Go = c.int8
  1481  		t.Align = 1
  1482  
  1483  	case *dwarf.EnumType:
  1484  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1485  			t.Align = c.ptrSize
  1486  		}
  1487  		t.C.Set("enum " + dt.EnumName)
  1488  		signed := 0
  1489  		t.EnumValues = make(map[string]int64)
  1490  		for _, ev := range dt.Val {
  1491  			t.EnumValues[ev.Name] = ev.Val
  1492  			if ev.Val < 0 {
  1493  				signed = signedDelta
  1494  			}
  1495  		}
  1496  		switch t.Size + int64(signed) {
  1497  		default:
  1498  			fatalf("%s: unexpected: %d-byte enum type - %s", lineno(pos), t.Size, dtype)
  1499  		case 1:
  1500  			t.Go = c.uint8
  1501  		case 2:
  1502  			t.Go = c.uint16
  1503  		case 4:
  1504  			t.Go = c.uint32
  1505  		case 8:
  1506  			t.Go = c.uint64
  1507  		case 1 + signedDelta:
  1508  			t.Go = c.int8
  1509  		case 2 + signedDelta:
  1510  			t.Go = c.int16
  1511  		case 4 + signedDelta:
  1512  			t.Go = c.int32
  1513  		case 8 + signedDelta:
  1514  			t.Go = c.int64
  1515  		}
  1516  
  1517  	case *dwarf.FloatType:
  1518  		switch t.Size {
  1519  		default:
  1520  			fatalf("%s: unexpected: %d-byte float type - %s", lineno(pos), t.Size, dtype)
  1521  		case 4:
  1522  			t.Go = c.float32
  1523  		case 8:
  1524  			t.Go = c.float64
  1525  		}
  1526  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1527  			t.Align = c.ptrSize
  1528  		}
  1529  
  1530  	case *dwarf.ComplexType:
  1531  		switch t.Size {
  1532  		default:
  1533  			fatalf("%s: unexpected: %d-byte complex type - %s", lineno(pos), t.Size, dtype)
  1534  		case 8:
  1535  			t.Go = c.complex64
  1536  		case 16:
  1537  			t.Go = c.complex128
  1538  		}
  1539  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1540  			t.Align = c.ptrSize
  1541  		}
  1542  
  1543  	case *dwarf.FuncType:
  1544  		// No attempt at translation: would enable calls
  1545  		// directly between worlds, but we need to moderate those.
  1546  		t.Go = c.uintptr
  1547  		t.Align = c.ptrSize
  1548  
  1549  	case *dwarf.IntType:
  1550  		if dt.BitSize > 0 {
  1551  			fatalf("%s: unexpected: %d-bit int type - %s", lineno(pos), dt.BitSize, dtype)
  1552  		}
  1553  		switch t.Size {
  1554  		default:
  1555  			fatalf("%s: unexpected: %d-byte int type - %s", lineno(pos), t.Size, dtype)
  1556  		case 1:
  1557  			t.Go = c.int8
  1558  		case 2:
  1559  			t.Go = c.int16
  1560  		case 4:
  1561  			t.Go = c.int32
  1562  		case 8:
  1563  			t.Go = c.int64
  1564  		case 16:
  1565  			t.Go = &ast.ArrayType{
  1566  				Len: c.intExpr(t.Size),
  1567  				Elt: c.uint8,
  1568  			}
  1569  		}
  1570  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1571  			t.Align = c.ptrSize
  1572  		}
  1573  
  1574  	case *dwarf.PtrType:
  1575  		// Clang doesn't emit DW_AT_byte_size for pointer types.
  1576  		if t.Size != c.ptrSize && t.Size != -1 {
  1577  			fatalf("%s: unexpected: %d-byte pointer type - %s", lineno(pos), t.Size, dtype)
  1578  		}
  1579  		t.Size = c.ptrSize
  1580  		t.Align = c.ptrSize
  1581  
  1582  		if _, ok := base(dt.Type).(*dwarf.VoidType); ok {
  1583  			t.Go = c.goVoidPtr
  1584  			t.C.Set("void*")
  1585  			break
  1586  		}
  1587  
  1588  		// Placeholder initialization; completed in FinishType.
  1589  		t.Go = &ast.StarExpr{}
  1590  		t.C.Set("<incomplete>*")
  1591  		if _, ok := c.ptrs[dt.Type]; !ok {
  1592  			c.ptrKeys = append(c.ptrKeys, dt.Type)
  1593  		}
  1594  		c.ptrs[dt.Type] = append(c.ptrs[dt.Type], t)
  1595  
  1596  	case *dwarf.QualType:
  1597  		// Ignore qualifier.
  1598  		t = c.Type(dt.Type, pos)
  1599  		c.m[dtype] = t
  1600  		return t
  1601  
  1602  	case *dwarf.StructType:
  1603  		// Convert to Go struct, being careful about alignment.
  1604  		// Have to give it a name to simulate C "struct foo" references.
  1605  		tag := dt.StructName
  1606  		if dt.ByteSize < 0 && tag == "" { // opaque unnamed struct - should not be possible
  1607  			break
  1608  		}
  1609  		if tag == "" {
  1610  			tag = "__" + strconv.Itoa(tagGen)
  1611  			tagGen++
  1612  		} else if t.C.Empty() {
  1613  			t.C.Set(dt.Kind + " " + tag)
  1614  		}
  1615  		name := c.Ident("_Ctype_" + dt.Kind + "_" + tag)
  1616  		t.Go = name // publish before recursive calls
  1617  		goIdent[name.Name] = name
  1618  		if dt.ByteSize < 0 {
  1619  			// Size calculation in c.Struct/c.Opaque will die with size=-1 (unknown),
  1620  			// so execute the basic things that the struct case would do
  1621  			// other than try to determine a Go representation.
  1622  			tt := *t
  1623  			tt.C = &TypeRepr{"%s %s", []interface{}{dt.Kind, tag}}
  1624  			tt.Go = c.Ident("struct{}")
  1625  			typedef[name.Name] = &tt
  1626  			break
  1627  		}
  1628  		switch dt.Kind {
  1629  		case "class", "union":
  1630  			t.Go = c.Opaque(t.Size)
  1631  			if t.C.Empty() {
  1632  				t.C.Set("__typeof__(unsigned char[%d])", t.Size)
  1633  			}
  1634  			t.Align = 1 // TODO: should probably base this on field alignment.
  1635  			typedef[name.Name] = t
  1636  		case "struct":
  1637  			g, csyntax, align := c.Struct(dt, pos)
  1638  			if t.C.Empty() {
  1639  				t.C.Set(csyntax)
  1640  			}
  1641  			t.Align = align
  1642  			tt := *t
  1643  			if tag != "" {
  1644  				tt.C = &TypeRepr{"struct %s", []interface{}{tag}}
  1645  			}
  1646  			tt.Go = g
  1647  			typedef[name.Name] = &tt
  1648  		}
  1649  
  1650  	case *dwarf.TypedefType:
  1651  		// Record typedef for printing.
  1652  		if dt.Name == "_GoString_" {
  1653  			// Special C name for Go string type.
  1654  			// Knows string layout used by compilers: pointer plus length,
  1655  			// which rounds up to 2 pointers after alignment.
  1656  			t.Go = c.string
  1657  			t.Size = c.ptrSize * 2
  1658  			t.Align = c.ptrSize
  1659  			break
  1660  		}
  1661  		if dt.Name == "_GoBytes_" {
  1662  			// Special C name for Go []byte type.
  1663  			// Knows slice layout used by compilers: pointer, length, cap.
  1664  			t.Go = c.Ident("[]byte")
  1665  			t.Size = c.ptrSize + 4 + 4
  1666  			t.Align = c.ptrSize
  1667  			break
  1668  		}
  1669  		name := c.Ident("_Ctype_" + dt.Name)
  1670  		goIdent[name.Name] = name
  1671  		sub := c.Type(dt.Type, pos)
  1672  		t.Go = name
  1673  		t.Size = sub.Size
  1674  		t.Align = sub.Align
  1675  		oldType := typedef[name.Name]
  1676  		if oldType == nil {
  1677  			tt := *t
  1678  			tt.Go = sub.Go
  1679  			typedef[name.Name] = &tt
  1680  		}
  1681  
  1682  		// If sub.Go.Name is "_Ctype_struct_foo" or "_Ctype_union_foo" or "_Ctype_class_foo",
  1683  		// use that as the Go form for this typedef too, so that the typedef will be interchangeable
  1684  		// with the base type.
  1685  		// In -godefs mode, do this for all typedefs.
  1686  		if isStructUnionClass(sub.Go) || *godefs {
  1687  			t.Go = sub.Go
  1688  
  1689  			if isStructUnionClass(sub.Go) {
  1690  				// Use the typedef name for C code.
  1691  				typedef[sub.Go.(*ast.Ident).Name].C = t.C
  1692  			}
  1693  
  1694  			// If we've seen this typedef before, and it
  1695  			// was an anonymous struct/union/class before
  1696  			// too, use the old definition.
  1697  			// TODO: it would be safer to only do this if
  1698  			// we verify that the types are the same.
  1699  			if oldType != nil && isStructUnionClass(oldType.Go) {
  1700  				t.Go = oldType.Go
  1701  			}
  1702  		}
  1703  
  1704  	case *dwarf.UcharType:
  1705  		if t.Size != 1 {
  1706  			fatalf("%s: unexpected: %d-byte uchar type - %s", lineno(pos), t.Size, dtype)
  1707  		}
  1708  		t.Go = c.uint8
  1709  		t.Align = 1
  1710  
  1711  	case *dwarf.UintType:
  1712  		if dt.BitSize > 0 {
  1713  			fatalf("%s: unexpected: %d-bit uint type - %s", lineno(pos), dt.BitSize, dtype)
  1714  		}
  1715  		switch t.Size {
  1716  		default:
  1717  			fatalf("%s: unexpected: %d-byte uint type - %s", lineno(pos), t.Size, dtype)
  1718  		case 1:
  1719  			t.Go = c.uint8
  1720  		case 2:
  1721  			t.Go = c.uint16
  1722  		case 4:
  1723  			t.Go = c.uint32
  1724  		case 8:
  1725  			t.Go = c.uint64
  1726  		case 16:
  1727  			t.Go = &ast.ArrayType{
  1728  				Len: c.intExpr(t.Size),
  1729  				Elt: c.uint8,
  1730  			}
  1731  		}
  1732  		if t.Align = t.Size; t.Align >= c.ptrSize {
  1733  			t.Align = c.ptrSize
  1734  		}
  1735  
  1736  	case *dwarf.VoidType:
  1737  		t.Go = c.goVoid
  1738  		t.C.Set("void")
  1739  		t.Align = 1
  1740  	}
  1741  
  1742  	switch dtype.(type) {
  1743  	case *dwarf.AddrType, *dwarf.BoolType, *dwarf.CharType, *dwarf.ComplexType, *dwarf.IntType, *dwarf.FloatType, *dwarf.UcharType, *dwarf.UintType:
  1744  		s := dtype.Common().Name
  1745  		if s != "" {
  1746  			if ss, ok := dwarfToName[s]; ok {
  1747  				s = ss
  1748  			}
  1749  			s = strings.Join(strings.Split(s, " "), "") // strip spaces
  1750  			name := c.Ident("_Ctype_" + s)
  1751  			tt := *t
  1752  			typedef[name.Name] = &tt
  1753  			if !*godefs {
  1754  				t.Go = name
  1755  			}
  1756  		}
  1757  	}
  1758  
  1759  	if t.Size < 0 {
  1760  		// Unsized types are [0]byte, unless they're typedefs of other types
  1761  		// or structs with tags.
  1762  		// if so, use the name we've already defined.
  1763  		t.Size = 0
  1764  		switch dt := dtype.(type) {
  1765  		case *dwarf.TypedefType:
  1766  			// ok
  1767  		case *dwarf.StructType:
  1768  			if dt.StructName != "" {
  1769  				break
  1770  			}
  1771  			t.Go = c.Opaque(0)
  1772  		default:
  1773  			t.Go = c.Opaque(0)
  1774  		}
  1775  		if t.C.Empty() {
  1776  			t.C.Set("void")
  1777  		}
  1778  	}
  1779  
  1780  	if t.C.Empty() {
  1781  		fatalf("%s: internal error: did not create C name for %s", lineno(pos), dtype)
  1782  	}
  1783  
  1784  	return t
  1785  }
  1786  
  1787  // isStructUnionClass reports whether the type described by the Go syntax x
  1788  // is a struct, union, or class with a tag.
  1789  func isStructUnionClass(x ast.Expr) bool {
  1790  	id, ok := x.(*ast.Ident)
  1791  	if !ok {
  1792  		return false
  1793  	}
  1794  	name := id.Name
  1795  	return strings.HasPrefix(name, "_Ctype_struct_") ||
  1796  		strings.HasPrefix(name, "_Ctype_union_") ||
  1797  		strings.HasPrefix(name, "_Ctype_class_")
  1798  }
  1799  
  1800  // FuncArg returns a Go type with the same memory layout as
  1801  // dtype when used as the type of a C function argument.
  1802  func (c *typeConv) FuncArg(dtype dwarf.Type, pos token.Pos) *Type {
  1803  	t := c.Type(dtype, pos)
  1804  	switch dt := dtype.(type) {
  1805  	case *dwarf.ArrayType:
  1806  		// Arrays are passed implicitly as pointers in C.
  1807  		// In Go, we must be explicit.
  1808  		tr := &TypeRepr{}
  1809  		tr.Set("%s*", t.C)
  1810  		return &Type{
  1811  			Size:  c.ptrSize,
  1812  			Align: c.ptrSize,
  1813  			Go:    &ast.StarExpr{X: t.Go},
  1814  			C:     tr,
  1815  		}
  1816  	case *dwarf.TypedefType:
  1817  		// C has much more relaxed rules than Go for
  1818  		// implicit type conversions.  When the parameter
  1819  		// is type T defined as *X, simulate a little of the
  1820  		// laxness of C by making the argument *X instead of T.
  1821  		if ptr, ok := base(dt.Type).(*dwarf.PtrType); ok {
  1822  			// Unless the typedef happens to point to void* since
  1823  			// Go has special rules around using unsafe.Pointer.
  1824  			if _, void := base(ptr.Type).(*dwarf.VoidType); void {
  1825  				break
  1826  			}
  1827  
  1828  			t = c.Type(ptr, pos)
  1829  			if t == nil {
  1830  				return nil
  1831  			}
  1832  
  1833  			// Remember the C spelling, in case the struct
  1834  			// has __attribute__((unavailable)) on it.  See issue 2888.
  1835  			t.Typedef = dt.Name
  1836  		}
  1837  	}
  1838  	return t
  1839  }
  1840  
  1841  // FuncType returns the Go type analogous to dtype.
  1842  // There is no guarantee about matching memory layout.
  1843  func (c *typeConv) FuncType(dtype *dwarf.FuncType, pos token.Pos) *FuncType {
  1844  	p := make([]*Type, len(dtype.ParamType))
  1845  	gp := make([]*ast.Field, len(dtype.ParamType))
  1846  	for i, f := range dtype.ParamType {
  1847  		// gcc's DWARF generator outputs a single DotDotDotType parameter for
  1848  		// function pointers that specify no parameters (e.g. void
  1849  		// (*__cgo_0)()).  Treat this special case as void.  This case is
  1850  		// invalid according to ISO C anyway (i.e. void (*__cgo_1)(...) is not
  1851  		// legal).
  1852  		if _, ok := f.(*dwarf.DotDotDotType); ok && i == 0 {
  1853  			p, gp = nil, nil
  1854  			break
  1855  		}
  1856  		p[i] = c.FuncArg(f, pos)
  1857  		gp[i] = &ast.Field{Type: p[i].Go}
  1858  	}
  1859  	var r *Type
  1860  	var gr []*ast.Field
  1861  	if _, ok := dtype.ReturnType.(*dwarf.VoidType); ok {
  1862  		gr = []*ast.Field{{Type: c.goVoid}}
  1863  	} else if dtype.ReturnType != nil {
  1864  		r = c.Type(dtype.ReturnType, pos)
  1865  		gr = []*ast.Field{{Type: r.Go}}
  1866  	}
  1867  	return &FuncType{
  1868  		Params: p,
  1869  		Result: r,
  1870  		Go: &ast.FuncType{
  1871  			Params:  &ast.FieldList{List: gp},
  1872  			Results: &ast.FieldList{List: gr},
  1873  		},
  1874  	}
  1875  }
  1876  
  1877  // Identifier
  1878  func (c *typeConv) Ident(s string) *ast.Ident {
  1879  	return ast.NewIdent(s)
  1880  }
  1881  
  1882  // Opaque type of n bytes.
  1883  func (c *typeConv) Opaque(n int64) ast.Expr {
  1884  	return &ast.ArrayType{
  1885  		Len: c.intExpr(n),
  1886  		Elt: c.byte,
  1887  	}
  1888  }
  1889  
  1890  // Expr for integer n.
  1891  func (c *typeConv) intExpr(n int64) ast.Expr {
  1892  	return &ast.BasicLit{
  1893  		Kind:  token.INT,
  1894  		Value: strconv.FormatInt(n, 10),
  1895  	}
  1896  }
  1897  
  1898  // Add padding of given size to fld.
  1899  func (c *typeConv) pad(fld []*ast.Field, sizes []int64, size int64) ([]*ast.Field, []int64) {
  1900  	n := len(fld)
  1901  	fld = fld[0 : n+1]
  1902  	fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)}
  1903  	sizes = sizes[0 : n+1]
  1904  	sizes[n] = size
  1905  	return fld, sizes
  1906  }
  1907  
  1908  // Struct conversion: return Go and (gc) C syntax for type.
  1909  func (c *typeConv) Struct(dt *dwarf.StructType, pos token.Pos) (expr *ast.StructType, csyntax string, align int64) {
  1910  	// Minimum alignment for a struct is 1 byte.
  1911  	align = 1
  1912  
  1913  	var buf bytes.Buffer
  1914  	buf.WriteString("struct {")
  1915  	fld := make([]*ast.Field, 0, 2*len(dt.Field)+1) // enough for padding around every field
  1916  	sizes := make([]int64, 0, 2*len(dt.Field)+1)
  1917  	off := int64(0)
  1918  
  1919  	// Rename struct fields that happen to be named Go keywords into
  1920  	// _{keyword}.  Create a map from C ident -> Go ident.  The Go ident will
  1921  	// be mangled.  Any existing identifier that already has the same name on
  1922  	// the C-side will cause the Go-mangled version to be prefixed with _.
  1923  	// (e.g. in a struct with fields '_type' and 'type', the latter would be
  1924  	// rendered as '__type' in Go).
  1925  	ident := make(map[string]string)
  1926  	used := make(map[string]bool)
  1927  	for _, f := range dt.Field {
  1928  		ident[f.Name] = f.Name
  1929  		used[f.Name] = true
  1930  	}
  1931  
  1932  	if !*godefs {
  1933  		for cid, goid := range ident {
  1934  			if token.Lookup(goid).IsKeyword() {
  1935  				// Avoid keyword
  1936  				goid = "_" + goid
  1937  
  1938  				// Also avoid existing fields
  1939  				for _, exist := used[goid]; exist; _, exist = used[goid] {
  1940  					goid = "_" + goid
  1941  				}
  1942  
  1943  				used[goid] = true
  1944  				ident[cid] = goid
  1945  			}
  1946  		}
  1947  	}
  1948  
  1949  	anon := 0
  1950  	for _, f := range dt.Field {
  1951  		if f.ByteOffset > off {
  1952  			fld, sizes = c.pad(fld, sizes, f.ByteOffset-off)
  1953  			off = f.ByteOffset
  1954  		}
  1955  
  1956  		name := f.Name
  1957  		ft := f.Type
  1958  
  1959  		// In godefs mode, if this field is a C11
  1960  		// anonymous union then treat the first field in the
  1961  		// union as the field in the struct.  This handles
  1962  		// cases like the glibc <sys/resource.h> file; see
  1963  		// issue 6677.
  1964  		if *godefs {
  1965  			if st, ok := f.Type.(*dwarf.StructType); ok && name == "" && st.Kind == "union" && len(st.Field) > 0 && !used[st.Field[0].Name] {
  1966  				name = st.Field[0].Name
  1967  				ident[name] = name
  1968  				ft = st.Field[0].Type
  1969  			}
  1970  		}
  1971  
  1972  		// TODO: Handle fields that are anonymous structs by
  1973  		// promoting the fields of the inner struct.
  1974  
  1975  		t := c.Type(ft, pos)
  1976  		tgo := t.Go
  1977  		size := t.Size
  1978  		talign := t.Align
  1979  		if f.BitSize > 0 {
  1980  			if f.BitSize%8 != 0 {
  1981  				continue
  1982  			}
  1983  			size = f.BitSize / 8
  1984  			name := tgo.(*ast.Ident).String()
  1985  			if strings.HasPrefix(name, "int") {
  1986  				name = "int"
  1987  			} else {
  1988  				name = "uint"
  1989  			}
  1990  			tgo = ast.NewIdent(name + fmt.Sprint(f.BitSize))
  1991  			talign = size
  1992  		}
  1993  
  1994  		if talign > 0 && f.ByteOffset%talign != 0 {
  1995  			// Drop misaligned fields, the same way we drop integer bit fields.
  1996  			// The goal is to make available what can be made available.
  1997  			// Otherwise one bad and unneeded field in an otherwise okay struct
  1998  			// makes the whole program not compile. Much of the time these
  1999  			// structs are in system headers that cannot be corrected.
  2000  			continue
  2001  		}
  2002  		n := len(fld)
  2003  		fld = fld[0 : n+1]
  2004  		if name == "" {
  2005  			name = fmt.Sprintf("anon%d", anon)
  2006  			anon++
  2007  			ident[name] = name
  2008  		}
  2009  		fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[name])}, Type: tgo}
  2010  		sizes = sizes[0 : n+1]
  2011  		sizes[n] = size
  2012  		off += size
  2013  		buf.WriteString(t.C.String())
  2014  		buf.WriteString(" ")
  2015  		buf.WriteString(name)
  2016  		buf.WriteString("; ")
  2017  		if talign > align {
  2018  			align = talign
  2019  		}
  2020  	}
  2021  	if off < dt.ByteSize {
  2022  		fld, sizes = c.pad(fld, sizes, dt.ByteSize-off)
  2023  		off = dt.ByteSize
  2024  	}
  2025  
  2026  	// If the last field in a non-zero-sized struct is zero-sized
  2027  	// the compiler is going to pad it by one (see issue 9401).
  2028  	// We can't permit that, because then the size of the Go
  2029  	// struct will not be the same as the size of the C struct.
  2030  	// Our only option in such a case is to remove the field,
  2031  	// which means that it can not be referenced from Go.
  2032  	for off > 0 && sizes[len(sizes)-1] == 0 {
  2033  		n := len(sizes)
  2034  		fld = fld[0 : n-1]
  2035  		sizes = sizes[0 : n-1]
  2036  	}
  2037  
  2038  	if off != dt.ByteSize {
  2039  		fatalf("%s: struct size calculation error off=%d bytesize=%d", lineno(pos), off, dt.ByteSize)
  2040  	}
  2041  	buf.WriteString("}")
  2042  	csyntax = buf.String()
  2043  
  2044  	if *godefs {
  2045  		godefsFields(fld)
  2046  	}
  2047  	expr = &ast.StructType{Fields: &ast.FieldList{List: fld}}
  2048  	return
  2049  }
  2050  
  2051  func upper(s string) string {
  2052  	if s == "" {
  2053  		return ""
  2054  	}
  2055  	r, size := utf8.DecodeRuneInString(s)
  2056  	if r == '_' {
  2057  		return "X" + s
  2058  	}
  2059  	return string(unicode.ToUpper(r)) + s[size:]
  2060  }
  2061  
  2062  // godefsFields rewrites field names for use in Go or C definitions.
  2063  // It strips leading common prefixes (like tv_ in tv_sec, tv_usec)
  2064  // converts names to upper case, and rewrites _ into Pad_godefs_n,
  2065  // so that all fields are exported.
  2066  func godefsFields(fld []*ast.Field) {
  2067  	prefix := fieldPrefix(fld)
  2068  	npad := 0
  2069  	for _, f := range fld {
  2070  		for _, n := range f.Names {
  2071  			if n.Name != prefix {
  2072  				n.Name = strings.TrimPrefix(n.Name, prefix)
  2073  			}
  2074  			if n.Name == "_" {
  2075  				// Use exported name instead.
  2076  				n.Name = "Pad_cgo_" + strconv.Itoa(npad)
  2077  				npad++
  2078  			}
  2079  			n.Name = upper(n.Name)
  2080  		}
  2081  	}
  2082  }
  2083  
  2084  // fieldPrefix returns the prefix that should be removed from all the
  2085  // field names when generating the C or Go code.  For generated
  2086  // C, we leave the names as is (tv_sec, tv_usec), since that's what
  2087  // people are used to seeing in C.  For generated Go code, such as
  2088  // package syscall's data structures, we drop a common prefix
  2089  // (so sec, usec, which will get turned into Sec, Usec for exporting).
  2090  func fieldPrefix(fld []*ast.Field) string {
  2091  	prefix := ""
  2092  	for _, f := range fld {
  2093  		for _, n := range f.Names {
  2094  			// Ignore field names that don't have the prefix we're
  2095  			// looking for.  It is common in C headers to have fields
  2096  			// named, say, _pad in an otherwise prefixed header.
  2097  			// If the struct has 3 fields tv_sec, tv_usec, _pad1, then we
  2098  			// still want to remove the tv_ prefix.
  2099  			// The check for "orig_" here handles orig_eax in the
  2100  			// x86 ptrace register sets, which otherwise have all fields
  2101  			// with reg_ prefixes.
  2102  			if strings.HasPrefix(n.Name, "orig_") || strings.HasPrefix(n.Name, "_") {
  2103  				continue
  2104  			}
  2105  			i := strings.Index(n.Name, "_")
  2106  			if i < 0 {
  2107  				continue
  2108  			}
  2109  			if prefix == "" {
  2110  				prefix = n.Name[:i+1]
  2111  			} else if prefix != n.Name[:i+1] {
  2112  				return ""
  2113  			}
  2114  		}
  2115  	}
  2116  	return prefix
  2117  }