gcc.go 47.4 KB
Newer Older
1 2 3 4
// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

Russ Cox's avatar
Russ Cox committed
5
// Annotate Ref in Prog with C types by parsing gcc debug output.
Russ Cox's avatar
Russ Cox committed
6
// Conversion of debug output to Go types.
7 8 9 10

package main

import (
11 12 13 14
	"bytes"
	"debug/dwarf"
	"debug/elf"
	"debug/macho"
15
	"debug/pe"
16
	"encoding/binary"
17
	"errors"
Russ Cox's avatar
Russ Cox committed
18
	"flag"
19 20
	"fmt"
	"go/ast"
21
	"go/parser"
22 23 24 25
	"go/token"
	"os"
	"strconv"
	"strings"
26
	"unicode"
27
	"unicode/utf8"
28 29
)

Russ Cox's avatar
Russ Cox committed
30 31 32 33
var debugDefine = flag.Bool("debug-define", false, "print relevant #defines")
var debugGcc = flag.Bool("debug-gcc", false, "print gcc invocations")

var nameToC = map[string]string{
34 35 36 37 38 39 40 41 42
	"schar":         "signed char",
	"uchar":         "unsigned char",
	"ushort":        "unsigned short",
	"uint":          "unsigned int",
	"ulong":         "unsigned long",
	"longlong":      "long long",
	"ulonglong":     "unsigned long long",
	"complexfloat":  "float complex",
	"complexdouble": "double complex",
Russ Cox's avatar
Russ Cox committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
}

// cname returns the C name to use for C.s.
// The expansions are listed in nameToC and also
// struct_foo becomes "struct foo", and similarly for
// union and enum.
func cname(s string) string {
	if t, ok := nameToC[s]; ok {
		return t
	}

	if strings.HasPrefix(s, "struct_") {
		return "struct " + s[len("struct_"):]
	}
	if strings.HasPrefix(s, "union_") {
		return "union " + s[len("union_"):]
	}
	if strings.HasPrefix(s, "enum_") {
		return "enum " + s[len("enum_"):]
	}
63 64 65
	if strings.HasPrefix(s, "sizeof_") {
		return "sizeof(" + cname(s[len("sizeof_"):]) + ")"
	}
Russ Cox's avatar
Russ Cox committed
66 67 68
	return s
}

69 70 71 72
// DiscardCgoDirectives processes the import C preamble, and discards
// all #cgo CFLAGS and LDFLAGS directives, so they don't make their
// way into _cgo_export.h.
func (f *File) DiscardCgoDirectives() {
73
	linesIn := strings.Split(f.Preamble, "\n")
74 75 76
	linesOut := make([]string, 0, len(linesIn))
	for _, line := range linesIn {
		l := strings.TrimSpace(line)
77
		if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(rune(l[4])) {
78
			linesOut = append(linesOut, line)
79 80
		} else {
			linesOut = append(linesOut, "")
81 82 83 84 85
		}
	}
	f.Preamble = strings.Join(linesOut, "\n")
}

86 87 88
// addToFlag appends args to flag.  All flags are later written out onto the
// _cgo_flags file for the build system to use.
func (p *Package) addToFlag(flag string, args []string) {
89
	p.CgoFlags[flag] = append(p.CgoFlags[flag], args...)
90 91 92 93 94 95
	if flag == "CFLAGS" {
		// We'll also need these when preprocessing for dwarf information.
		p.GccOptions = append(p.GccOptions, args...)
	}
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
// splitQuoted splits the string s around each instance of one or more consecutive
// white space characters while taking into account quotes and escaping, and
// returns an array of substrings of s or an empty list if s contains only white space.
// Single quotes and double quotes are recognized to prevent splitting within the
// quoted region, and are removed from the resulting substrings. If a quote in s
// isn't closed err will be set and r will have the unclosed argument as the
// last element.  The backslash is used for escaping.
//
// For example, the following string:
//
//     `a b:"c d" 'e''f'  "g\""`
//
// Would be parsed as:
//
//     []string{"a", "b:c d", "ef", `g"`}
//
112
func splitQuoted(s string) (r []string, err error) {
113
	var args []string
114
	arg := make([]rune, len(s))
115 116
	escaped := false
	quoted := false
117
	quote := '\x00'
118
	i := 0
119
	for _, r := range s {
120 121 122
		switch {
		case escaped:
			escaped = false
123
		case r == '\\':
124 125 126
			escaped = true
			continue
		case quote != 0:
127
			if r == quote {
128 129 130
				quote = 0
				continue
			}
131
		case r == '"' || r == '\'':
132
			quoted = true
133
			quote = r
134
			continue
135
		case unicode.IsSpace(r):
136 137 138 139 140 141 142
			if quoted || i > 0 {
				quoted = false
				args = append(args, string(arg[:i]))
				i = 0
			}
			continue
		}
143
		arg[i] = r
144 145 146 147 148 149
		i++
	}
	if quoted || i > 0 {
		args = append(args, string(arg[:i]))
	}
	if quote != 0 {
150
		err = errors.New("unclosed quote")
151
	} else if escaped {
152
		err = errors.New("unfinished escaping")
153 154 155 156
	}
	return args, err
}

Russ Cox's avatar
Russ Cox committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
// Translate rewrites f.AST, the original Go input, to remove
// references to the imported package C, replacing them with
// references to the equivalent Go types, functions, and variables.
func (p *Package) Translate(f *File) {
	for _, cref := range f.Ref {
		// Convert C.ulong to C.unsigned long, etc.
		cref.Name.C = cname(cref.Name.Go)
	}
	p.loadDefines(f)
	needType := p.guessKinds(f)
	if len(needType) > 0 {
		p.loadDWARF(f, needType)
	}
	p.rewriteRef(f)
}

// loadDefines coerces gcc into spitting out the #defines in use
// in the file f and saves relevant renamings in f.Name[name].Define.
func (p *Package) loadDefines(f *File) {
176
	var b bytes.Buffer
Russ Cox's avatar
Russ Cox committed
177
	b.WriteString(f.Preamble)
178
	b.WriteString(builtinProlog)
Russ Cox's avatar
Russ Cox committed
179
	stdout := p.gccDefines(b.Bytes())
180

181
	for _, line := range strings.Split(stdout, "\n") {
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		if len(line) < 9 || line[0:7] != "#define" {
			continue
		}

		line = strings.TrimSpace(line[8:])

		var key, val string
		spaceIndex := strings.Index(line, " ")
		tabIndex := strings.Index(line, "\t")

		if spaceIndex == -1 && tabIndex == -1 {
			continue
		} else if tabIndex == -1 || (spaceIndex != -1 && spaceIndex < tabIndex) {
			key = line[0:spaceIndex]
			val = strings.TrimSpace(line[spaceIndex:])
		} else {
			key = line[0:tabIndex]
			val = strings.TrimSpace(line[tabIndex:])
		}

Russ Cox's avatar
Russ Cox committed
202 203 204
		if n := f.Name[key]; n != nil {
			if *debugDefine {
				fmt.Fprintf(os.Stderr, "#define %s %s\n", key, val)
205
			}
Russ Cox's avatar
Russ Cox committed
206
			n.Define = val
207
		}
208
	}
Russ Cox's avatar
Russ Cox committed
209
}
210

Russ Cox's avatar
Russ Cox committed
211 212 213 214
// guessKinds tricks gcc into revealing the kind of each
// name xxx for the references C.xxx in the Go input.
// The kind is either a constant, type, or variable.
func (p *Package) guessKinds(f *File) []*Name {
215 216 217
	// Determine kinds for names we already know about,
	// like #defines or 'struct foo', before bothering with gcc.
	var names, needType []*Name
218 219
	for _, key := range nameKeys(f.Name) {
		n := f.Name[key]
Russ Cox's avatar
Russ Cox committed
220 221 222
		// If we've already found this name as a #define
		// and we can translate it as a constant value, do so.
		if n.Define != "" {
223
			isConst := false
Russ Cox's avatar
Russ Cox committed
224
			if _, err := strconv.Atoi(n.Define); err == nil {
225
				isConst = true
Russ Cox's avatar
Russ Cox committed
226
			} else if n.Define[0] == '"' || n.Define[0] == '\'' {
227
				if _, err := parser.ParseExpr(n.Define); err == nil {
228
					isConst = true
Russ Cox's avatar
Russ Cox committed
229 230
				}
			}
231
			if isConst {
Russ Cox's avatar
Russ Cox committed
232
				n.Kind = "const"
233 234 235 236
				// Turn decimal into hex, just for consistency
				// with enum-derived constants.  Otherwise
				// in the cgo -godefs output half the constants
				// are in hex and half are in whatever the #define used.
Russ Cox's avatar
Russ Cox committed
237
				i, err := strconv.ParseInt(n.Define, 0, 64)
238 239 240 241 242
				if err == nil {
					n.Const = fmt.Sprintf("%#x", i)
				} else {
					n.Const = n.Define
				}
Russ Cox's avatar
Russ Cox committed
243 244 245 246 247 248 249 250
				continue
			}

			if isName(n.Define) {
				n.C = n.Define
			}
		}

251 252 253
		needType = append(needType, n)

		// If this is a struct, union, or enum type name, no need to guess the kind.
Russ Cox's avatar
Russ Cox committed
254 255 256 257 258
		if strings.HasPrefix(n.C, "struct ") || strings.HasPrefix(n.C, "union ") || strings.HasPrefix(n.C, "enum ") {
			n.Kind = "type"
			continue
		}

259 260
		// Otherwise, we'll need to find out from gcc.
		names = append(names, n)
Russ Cox's avatar
Russ Cox committed
261 262
	}

263 264
	// Bypass gcc if there's nothing left to find out.
	if len(names) == 0 {
Russ Cox's avatar
Russ Cox committed
265 266 267
		return needType
	}

268 269 270 271 272 273 274 275 276 277
	// Coerce gcc into telling us whether each name is a type, a value, or undeclared.
	// For names, find out whether they are integer constants.
	// We used to look at specific warning or error messages here, but that tied the
	// behavior too closely to specific versions of the compilers.
	// Instead, arrange that we can infer what we need from only the presence or absence
	// of an error on a specific line.
	//
	// For each name, we generate these lines, where xxx is the index in toSniff plus one.
	//
	//	#line xxx "not-declared"
278
	//	void __cgo_f_xxx_1(void) { __typeof__(name) *__cgo_undefined__; }
279 280 281 282 283 284 285 286 287 288 289 290 291 292
	//	#line xxx "not-type"
	//	void __cgo_f_xxx_2(void) { name *__cgo_undefined__; }
	//	#line xxx "not-const"
	//	void __cgo_f_xxx_3(void) { enum { __cgo_undefined__ = (name)*1 }; }
	//
	// If we see an error at not-declared:xxx, the corresponding name is not declared.
	// If we see an error at not-type:xxx, the corresponding name is a type.
	// If we see an error at not-const:xxx, the corresponding name is not an integer constant.
	// If we see no errors, we assume the name is an expression but not a constant
	// (so a variable or a function).
	//
	// The specific input forms are chosen so that they are valid C syntax regardless of
	// whether name denotes a type or an expression.

Russ Cox's avatar
Russ Cox committed
293 294
	var b bytes.Buffer
	b.WriteString(f.Preamble)
295
	b.WriteString(builtinProlog)
296 297 298

	for i, n := range names {
		fmt.Fprintf(&b, "#line %d \"not-declared\"\n"+
299
			"void __cgo_f_%d_1(void) { __typeof__(%s) *__cgo_undefined__; }\n"+
300 301 302 303 304 305 306 307 308 309 310
			"#line %d \"not-type\"\n"+
			"void __cgo_f_%d_2(void) { %s *__cgo_undefined__; }\n"+
			"#line %d \"not-const\"\n"+
			"void __cgo_f_%d_3(void) { enum { __cgo__undefined__ = (%s)*1 }; }\n",
			i+1, i+1, n.C,
			i+1, i+1, n.C,
			i+1, i+1, n.C)
	}
	fmt.Fprintf(&b, "#line 1 \"completed\"\n"+
		"int __cgo__1 = __cgo__2;\n")

Russ Cox's avatar
Russ Cox committed
311
	stderr := p.gccErrors(b.Bytes())
312
	if stderr == "" {
313
		fatalf("%s produced no output\non input:\n%s", p.gccBaseCmd()[0], b.Bytes())
Russ Cox's avatar
Russ Cox committed
314 315
	}

316 317 318 319 320
	completed := false
	sniff := make([]int, len(names))
	const (
		notType = 1 << iota
		notConst
321
		notDeclared
322
	)
323
	for _, line := range strings.Split(stderr, "\n") {
324 325 326
		if !strings.Contains(line, ": error:") {
			// we only care about errors.
			// we tried to turn off warnings on the command line, but one never knows.
327
			continue
328
		}
329 330 331

		c1 := strings.Index(line, ":")
		if c1 < 0 {
332
			continue
333
		}
334 335
		c2 := strings.Index(line[c1+1:], ":")
		if c2 < 0 {
Russ Cox's avatar
Russ Cox committed
336
			continue
337
		}
338 339 340 341 342 343
		c2 += c1 + 1

		filename := line[:c1]
		i, _ := strconv.Atoi(line[c1+1 : c2])
		i--
		if i < 0 || i >= len(names) {
Russ Cox's avatar
Russ Cox committed
344
			continue
345
		}
Russ Cox's avatar
Russ Cox committed
346

347 348 349 350 351 352 353 354 355
		switch filename {
		case "completed":
			// Strictly speaking, there is no guarantee that seeing the error at completed:1
			// (at the end of the file) means we've seen all the errors from earlier in the file,
			// but usually it does. Certainly if we don't see the completed:1 error, we did
			// not get all the errors we expected.
			completed = true

		case "not-declared":
356
			sniff[i] |= notDeclared
357 358 359 360
		case "not-type":
			sniff[i] |= notType
		case "not-const":
			sniff[i] |= notConst
361 362
		}
	}
363 364

	if !completed {
365
		fatalf("%s did not produce error at completed:1\non input:\n%s\nfull error output:\n%s", p.gccBaseCmd()[0], b.Bytes(), stderr)
366 367 368 369
	}

	for i, n := range names {
		switch sniff[i] {
370
		default:
371 372 373 374 375 376 377
			error_(token.NoPos, "could not determine kind of name for C.%s", fixGo(n.Go))
		case notType:
			n.Kind = "const"
		case notConst:
			n.Kind = "type"
		case notConst | notType:
			n.Kind = "not-type"
Russ Cox's avatar
Russ Cox committed
378 379
		}
	}
380
	if nerrors > 0 {
381 382 383 384 385 386 387 388
		// Check if compiling the preamble by itself causes any errors,
		// because the messages we've printed out so far aren't helpful
		// to users debugging preamble mistakes.  See issue 8442.
		preambleErrors := p.gccErrors([]byte(f.Preamble))
		if len(preambleErrors) > 0 {
			error_(token.NoPos, "\n%s errors for preamble:\n%s", p.gccBaseCmd()[0], preambleErrors)
		}

389
		fatalf("unresolved names")
390
	}
391 392

	needType = append(needType, names...)
Russ Cox's avatar
Russ Cox committed
393 394
	return needType
}
395

Russ Cox's avatar
Russ Cox committed
396 397 398 399
// loadDWARF parses the DWARF debug information generated
// by gcc to learn the details of the constants, variables, and types
// being referred to as C.xxx.
func (p *Package) loadDWARF(f *File, names []*Name) {
400 401 402 403 404
	// Extract the types from the DWARF section of an object
	// from a well-formed C program.  Gcc only generates DWARF info
	// for symbols in the object file, so it is not enough to print the
	// preamble and hope the symbols we care about will be there.
	// Instead, emit
405
	//	__typeof__(names[i]) *__cgo__i;
406 407
	// for each entry in names and then dereference the type we
	// learn for __cgo__i.
Russ Cox's avatar
Russ Cox committed
408 409
	var b bytes.Buffer
	b.WriteString(f.Preamble)
410
	b.WriteString(builtinProlog)
411
	for i, n := range names {
412
		fmt.Fprintf(&b, "__typeof__(%s) *__cgo__%d;\n", n.C, i)
Russ Cox's avatar
Russ Cox committed
413 414 415
		if n.Kind == "const" {
			fmt.Fprintf(&b, "enum { __cgo_enum__%d = %s };\n", i, n.C)
		}
416
	}
417 418 419 420 421 422 423 424 425 426 427 428 429

	// Apple's LLVM-based gcc does not include the enumeration
	// names and values in its DWARF debug output.  In case we're
	// using such a gcc, create a data block initialized with the values.
	// We can read them out of the object file.
	fmt.Fprintf(&b, "long long __cgodebug_data[] = {\n")
	for _, n := range names {
		if n.Kind == "const" {
			fmt.Fprintf(&b, "\t%s,\n", n.C)
		} else {
			fmt.Fprintf(&b, "\t0,\n")
		}
	}
430 431 432 433 434 435
	// for the last entry, we can not use 0, otherwise
	// in case all __cgodebug_data is zero initialized,
	// LLVM-based gcc will place the it in the __DATA.__common
	// zero-filled section (our debug/macho doesn't support
	// this)
	fmt.Fprintf(&b, "\t1\n")
436 437 438 439 440 441 442
	fmt.Fprintf(&b, "};\n")

	d, bo, debugData := p.gccDebug(b.Bytes())
	enumVal := make([]int64, len(debugData)/8)
	for i := range enumVal {
		enumVal[i] = int64(bo.Uint64(debugData[i*8:]))
	}
443

Adam Langley's avatar
Adam Langley committed
444
	// Scan DWARF info for top-level TagVariable entries with AttrName __cgo__i.
445
	types := make([]dwarf.Type, len(names))
446
	enums := make([]dwarf.Offset, len(names))
Russ Cox's avatar
Russ Cox committed
447 448 449 450
	nameToIndex := make(map[*Name]int)
	for i, n := range names {
		nameToIndex[n] = i
	}
451 452 453 454
	nameToRef := make(map[*Name]*Ref)
	for _, ref := range f.Ref {
		nameToRef[ref.Name] = ref
	}
455
	r := d.Reader()
456
	for {
457
		e, err := r.Next()
458
		if err != nil {
459
			fatalf("reading DWARF entry: %s", err)
460 461
		}
		if e == nil {
462
			break
463
		}
464 465 466 467 468 469
		switch e.Tag {
		case dwarf.TagEnumerationType:
			offset := e.Offset
			for {
				e, err := r.Next()
				if err != nil {
470
					fatalf("reading DWARF entry: %s", err)
471 472 473 474 475 476
				}
				if e.Tag == 0 {
					break
				}
				if e.Tag == dwarf.TagEnumerator {
					entryName := e.Val(dwarf.AttrName).(string)
Russ Cox's avatar
Russ Cox committed
477 478 479 480 481
					if strings.HasPrefix(entryName, "__cgo_enum__") {
						n, _ := strconv.Atoi(entryName[len("__cgo_enum__"):])
						if 0 <= n && n < len(names) {
							enums[n] = offset
						}
482 483 484 485 486 487 488
					}
				}
			}
		case dwarf.TagVariable:
			name, _ := e.Val(dwarf.AttrName).(string)
			typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset)
			if name == "" || typOff == 0 {
489
				fatalf("malformed DWARF TagVariable entry")
490 491 492 493 494 495
			}
			if !strings.HasPrefix(name, "__cgo__") {
				break
			}
			typ, err := d.Type(typOff)
			if err != nil {
496
				fatalf("loading DWARF type: %s", err)
497 498 499
			}
			t, ok := typ.(*dwarf.PtrType)
			if !ok || t == nil {
500
				fatalf("internal error: %s has non-pointer type", name)
501 502 503
			}
			i, err := strconv.Atoi(name[7:])
			if err != nil {
504
				fatalf("malformed __cgo__ name: %s", name)
505 506 507 508
			}
			if enums[i] != 0 {
				t, err := d.Type(enums[i])
				if err != nil {
509
					fatalf("loading DWARF type: %s", err)
510 511 512 513 514
				}
				types[i] = t
			} else {
				types[i] = t.Type
			}
515 516
		}
		if e.Tag != dwarf.TagCompileUnit {
517
			r.SkipChildren()
518 519 520
		}
	}

Russ Cox's avatar
Russ Cox committed
521
	// Record types and typedef information.
522
	var conv typeConv
Russ Cox's avatar
Russ Cox committed
523
	conv.Init(p.PtrSize, p.IntSize)
Russ Cox's avatar
Russ Cox committed
524
	for i, n := range names {
525 526 527
		if types[i] == nil {
			continue
		}
528 529 530 531
		pos := token.NoPos
		if ref, ok := nameToRef[n]; ok {
			pos = ref.Pos()
		}
532
		f, fok := types[i].(*dwarf.FuncType)
Russ Cox's avatar
Russ Cox committed
533 534
		if n.Kind != "type" && fok {
			n.Kind = "func"
535
			n.FuncType = conv.FuncType(f, pos)
Russ Cox's avatar
Russ Cox committed
536
		} else {
537
			n.Type = conv.Type(types[i], pos)
538
			if enums[i] != 0 && n.Type.EnumValues != nil {
539
				k := fmt.Sprintf("__cgo_enum__%d", i)
Russ Cox's avatar
Russ Cox committed
540
				n.Kind = "const"
541
				n.Const = fmt.Sprintf("%#x", n.Type.EnumValues[k])
542 543
				// Remove injected enum to ensure the value will deep-compare
				// equally in future loads of the same constant.
Russ Cox's avatar
Russ Cox committed
544
				delete(n.Type.EnumValues, k)
Russ Cox's avatar
Russ Cox committed
545
			}
546 547 548 549
			// Prefer debug data over DWARF debug output, if we have it.
			if n.Kind == "const" && i < len(enumVal) {
				n.Const = fmt.Sprintf("%#x", enumVal[i])
			}
Russ Cox's avatar
Russ Cox committed
550
		}
551
		conv.FinishType(pos)
552 553 554
	}
}

555 556 557 558 559 560 561 562 563 564 565 566 567 568
// mangleName does name mangling to translate names
// from the original Go source files to the names
// used in the final Go files generated by cgo.
func (p *Package) mangleName(n *Name) {
	// When using gccgo variables have to be
	// exported so that they become global symbols
	// that the C code can refer to.
	prefix := "_C"
	if *gccgo && n.IsVar() {
		prefix = "C"
	}
	n.Mangle = prefix + n.Kind + "_" + n.Go
}

Russ Cox's avatar
Russ Cox committed
569 570
// rewriteRef rewrites all the C.xxx references in f.AST to refer to the
// Go equivalents, now that we have figured out the meaning of all
571
// the xxx.  In *godefs mode, rewriteRef replaces the names
572
// with full definitions instead of mangled names.
Russ Cox's avatar
Russ Cox committed
573
func (p *Package) rewriteRef(f *File) {
574 575 576 577 578
	// Keep a list of all the functions, to remove the ones
	// only used as expressions and avoid generating bridge
	// code for them.
	functions := make(map[string]bool)

Russ Cox's avatar
Russ Cox committed
579 580 581 582 583 584
	// Assign mangled names.
	for _, n := range f.Name {
		if n.Kind == "not-type" {
			n.Kind = "var"
		}
		if n.Mangle == "" {
585 586 587 588
			p.mangleName(n)
		}
		if n.Kind == "func" {
			functions[n.Go] = false
Russ Cox's avatar
Russ Cox committed
589
		}
Russ Cox's avatar
Russ Cox committed
590
	}
Russ Cox's avatar
Russ Cox committed
591 592 593 594 595 596

	// Now that we have all the name types filled in,
	// scan through the Refs to identify the ones that
	// are trying to do a ,err call.  Also check that
	// functions are only used in calls.
	for _, r := range f.Ref {
597
		if r.Name.Kind == "const" && r.Name.Const == "" {
598
			error_(r.Pos(), "unable to find value of constant C.%s", fixGo(r.Name.Go))
599
		}
Russ Cox's avatar
Russ Cox committed
600 601 602 603 604 605 606 607 608
		var expr ast.Expr = ast.NewIdent(r.Name.Mangle) // default
		switch r.Context {
		case "call", "call2":
			if r.Name.Kind != "func" {
				if r.Name.Kind == "type" {
					r.Context = "type"
					expr = r.Name.Type.Go
					break
				}
609
				error_(r.Pos(), "call of non-function C.%s", fixGo(r.Name.Go))
Russ Cox's avatar
Russ Cox committed
610 611
				break
			}
612
			functions[r.Name.Go] = true
Russ Cox's avatar
Russ Cox committed
613
			if r.Context == "call2" {
614 615 616 617
				if r.Name.Go == "_CMalloc" {
					error_(r.Pos(), "no two-result form for C.malloc")
					break
				}
Russ Cox's avatar
Russ Cox committed
618 619 620 621 622 623 624 625 626
				// Invent new Name for the two-result function.
				n := f.Name["2"+r.Name.Go]
				if n == nil {
					n = new(Name)
					*n = *r.Name
					n.AddError = true
					n.Mangle = "_C2func_" + n.Go
					f.Name["2"+r.Name.Go] = n
				}
627
				expr = ast.NewIdent(n.Mangle)
Russ Cox's avatar
Russ Cox committed
628 629 630 631 632
				r.Name = n
				break
			}
		case "expr":
			if r.Name.Kind == "func" {
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
				// Function is being used in an expression, to e.g. pass around a C function pointer.
				// Create a new Name for this Ref which causes the variable to be declared in Go land.
				fpName := "fp_" + r.Name.Go
				name := f.Name[fpName]
				if name == nil {
					name = &Name{
						Go:   fpName,
						C:    r.Name.C,
						Kind: "fpvar",
						Type: &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*"), Go: ast.NewIdent("unsafe.Pointer")},
					}
					p.mangleName(name)
					f.Name[fpName] = name
				}
				r.Name = name
648 649 650 651 652 653 654
				// Rewrite into call to _Cgo_ptr to prevent assignments.  The _Cgo_ptr
				// function is defined in out.go and simply returns its argument. See
				// issue 7757.
				expr = &ast.CallExpr{
					Fun:  &ast.Ident{NamePos: (*r.Expr).Pos(), Name: "_Cgo_ptr"},
					Args: []ast.Expr{ast.NewIdent(name.Mangle)},
				}
655
			} else if r.Name.Kind == "type" {
Russ Cox's avatar
Russ Cox committed
656 657
				// Okay - might be new(T)
				expr = r.Name.Type.Go
658
			} else if r.Name.Kind == "var" {
659
				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
Russ Cox's avatar
Russ Cox committed
660 661
			}

662 663 664 665 666 667 668
		case "selector":
			if r.Name.Kind == "var" {
				expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}
			} else {
				error_(r.Pos(), "only C variables allowed in selector expression", fixGo(r.Name.Go))
			}

Russ Cox's avatar
Russ Cox committed
669 670
		case "type":
			if r.Name.Kind != "type" {
671
				error_(r.Pos(), "expression C.%s used as type", fixGo(r.Name.Go))
672 673 674
			} else if r.Name.Type == nil {
				// Use of C.enum_x, C.struct_x or C.union_x without C definition.
				// GCC won't raise an error when using pointers to such unknown types.
675
				error_(r.Pos(), "type C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
Eric Clark's avatar
Eric Clark committed
676 677
			} else {
				expr = r.Name.Type.Go
Russ Cox's avatar
Russ Cox committed
678 679 680
			}
		default:
			if r.Name.Kind == "func" {
681
				error_(r.Pos(), "must call C.%s", fixGo(r.Name.Go))
Russ Cox's avatar
Russ Cox committed
682 683
			}
		}
684
		if *godefs {
685 686 687
			// Substitute definition for mangled type name.
			if id, ok := expr.(*ast.Ident); ok {
				if t := typedef[id.Name]; t != nil {
Russ Cox's avatar
Russ Cox committed
688
					expr = t.Go
689 690 691 692 693 694
				}
				if id.Name == r.Name.Mangle && r.Name.Const != "" {
					expr = ast.NewIdent(r.Name.Const)
				}
			}
		}
695 696 697 698 699 700 701 702 703 704

		// Copy position information from old expr into new expr,
		// in case expression being replaced is first on line.
		// See golang.org/issue/6563.
		pos := (*r.Expr).Pos()
		switch x := expr.(type) {
		case *ast.Ident:
			expr = &ast.Ident{NamePos: pos, Name: x.Name}
		}

Russ Cox's avatar
Russ Cox committed
705
		*r.Expr = expr
Russ Cox's avatar
Russ Cox committed
706
	}
707 708 709 710 711 712 713 714

	// Remove functions only used as expressions, so their respective
	// bridge functions are not generated.
	for name, used := range functions {
		if !used {
			delete(f.Name, name)
		}
	}
Russ Cox's avatar
Russ Cox committed
715 716
}

717 718 719 720 721
// gccBaseCmd returns the start of the compiler command line.
// It uses $CC if set, or else $GCC, or else the compiler recorded
// during the initial build as defaultCC.
// defaultCC is defined in zdefaultcc.go, written by cmd/dist.
func (p *Package) gccBaseCmd() []string {
Russ Cox's avatar
Russ Cox committed
722
	// Use $CC if set, since that's what the build uses.
723
	if ret := strings.Fields(os.Getenv("CC")); len(ret) > 0 {
Russ Cox's avatar
Russ Cox committed
724
		return ret
725
	}
726 727
	// Try $GCC if set, since that's what we used to use.
	if ret := strings.Fields(os.Getenv("GCC")); len(ret) > 0 {
Russ Cox's avatar
Russ Cox committed
728 729
		return ret
	}
730
	return strings.Fields(defaultCC)
731 732
}

Shenghou Ma's avatar
Shenghou Ma committed
733
// gccMachine returns the gcc -m flag to use, either "-m32", "-m64" or "-marm".
734
func (p *Package) gccMachine() []string {
735
	switch goarch {
736 737 738 739
	case "amd64":
		return []string{"-m64"}
	case "386":
		return []string{"-m32"}
Shenghou Ma's avatar
Shenghou Ma committed
740
	case "arm":
741
		return []string{"-marm"} // not thumb
742 743
	}
	return nil
Russ Cox's avatar
Russ Cox committed
744
}
745

Russ Cox's avatar
Russ Cox committed
746 747 748
func gccTmp() string {
	return *objDir + "_cgo_.o"
}
Russ Cox's avatar
Russ Cox committed
749 750 751 752

// gccCmd returns the gcc command line to use for compiling
// the input.
func (p *Package) gccCmd() []string {
753
	c := append(p.gccBaseCmd(),
754 755 756 757 758 759
		"-w",          // no warnings
		"-Wno-error",  // warnings are not errors
		"-o"+gccTmp(), // write object to tmp
		"-gdwarf-2",   // generate DWARF v2 debugging symbols
		"-c",          // do not link
		"-xc",         // input language is C
760 761
	)
	if strings.Contains(c[0], "clang") {
Russ Cox's avatar
Russ Cox committed
762 763
		c = append(c,
			"-ferror-limit=0",
764 765 766 767
			// Apple clang version 1.7 (tags/Apple/clang-77) (based on LLVM 2.9svn)
			// doesn't have -Wno-unneeded-internal-declaration, so we need yet another
			// flag to disable the warning. Yes, really good diagnostics, clang.
			"-Wno-unknown-warning-option",
Russ Cox's avatar
Russ Cox committed
768
			"-Wno-unneeded-internal-declaration",
769 770
			"-Wno-unused-function",
			"-Qunused-arguments",
771 772 773 774 775 776 777
			// Clang embeds prototypes for some builtin functions,
			// like malloc and calloc, but all size_t parameters are
			// incorrectly typed unsigned long. We work around that
			// by disabling the builtin functions (this is safe as
			// it won't affect the actual compilation of the C code).
			// See: http://golang.org/issue/6506.
			"-fno-builtin",
Russ Cox's avatar
Russ Cox committed
778 779 780
		)
	}

781
	c = append(c, p.GccOptions...)
782
	c = append(c, p.gccMachine()...)
783 784
	c = append(c, "-") //read input from standard input
	return c
Russ Cox's avatar
Russ Cox committed
785 786 787
}

// gccDebug runs gcc -gdwarf-2 over the C program stdin and
788 789
// returns the corresponding DWARF data and, if present, debug data block.
func (p *Package) gccDebug(stdin []byte) (*dwarf.Data, binary.ByteOrder, []byte) {
790
	runGcc(stdin, p.gccCmd())
791

792 793 794 795 796
	isDebugData := func(s string) bool {
		// Some systems use leading _ to denote non-assembly symbols.
		return s == "__cgodebug_data" || s == "___cgodebug_data"
	}

Russ Cox's avatar
Russ Cox committed
797
	if f, err := macho.Open(gccTmp()); err == nil {
Dave Cheney's avatar
Dave Cheney committed
798
		defer f.Close()
799 800
		d, err := f.DWARF()
		if err != nil {
Russ Cox's avatar
Russ Cox committed
801
			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
802 803 804 805 806
		}
		var data []byte
		if f.Symtab != nil {
			for i := range f.Symtab.Syms {
				s := &f.Symtab.Syms[i]
807
				if isDebugData(s.Name) {
808 809 810 811 812 813 814 815 816 817
					// Found it.  Now find data section.
					if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) {
						sect := f.Sections[i]
						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
							if sdat, err := sect.Data(); err == nil {
								data = sdat[s.Value-sect.Addr:]
							}
						}
					}
				}
818
			}
819
		}
820
		return d, f.ByteOrder, data
821 822
	}

Russ Cox's avatar
Russ Cox committed
823
	if f, err := elf.Open(gccTmp()); err == nil {
Dave Cheney's avatar
Dave Cheney committed
824
		defer f.Close()
825 826
		d, err := f.DWARF()
		if err != nil {
Russ Cox's avatar
Russ Cox committed
827
			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
828
		}
829 830 831 832 833
		var data []byte
		symtab, err := f.Symbols()
		if err == nil {
			for i := range symtab {
				s := &symtab[i]
834
				if isDebugData(s.Name) {
835 836 837 838 839 840 841 842 843 844 845 846 847
					// Found it.  Now find data section.
					if i := int(s.Section); 0 <= i && i < len(f.Sections) {
						sect := f.Sections[i]
						if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size {
							if sdat, err := sect.Data(); err == nil {
								data = sdat[s.Value-sect.Addr:]
							}
						}
					}
				}
			}
		}
		return d, f.ByteOrder, data
848
	}
849

Russ Cox's avatar
Russ Cox committed
850
	if f, err := pe.Open(gccTmp()); err == nil {
Dave Cheney's avatar
Dave Cheney committed
851
		defer f.Close()
852 853
		d, err := f.DWARF()
		if err != nil {
Russ Cox's avatar
Russ Cox committed
854
			fatalf("cannot load DWARF output from %s: %v", gccTmp(), err)
855
		}
856 857
		var data []byte
		for _, s := range f.Symbols {
858
			if isDebugData(s.Name) {
859 860 861 862 863 864 865 866 867 868 869
				if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) {
					sect := f.Sections[i]
					if s.Value < sect.Size {
						if sdat, err := sect.Data(); err == nil {
							data = sdat[s.Value:]
						}
					}
				}
			}
		}
		return d, binary.LittleEndian, data
870 871
	}

Russ Cox's avatar
Russ Cox committed
872
	fatalf("cannot parse gcc output %s as ELF, Mach-O, PE object", gccTmp())
873
	panic("not reached")
874 875
}

Russ Cox's avatar
Russ Cox committed
876 877 878 879 880
// gccDefines runs gcc -E -dM -xc - over the C program stdin
// and returns the corresponding standard output, which is the
// #defines that gcc encountered while processing the input
// and its included files.
func (p *Package) gccDefines(stdin []byte) string {
881
	base := append(p.gccBaseCmd(), "-E", "-dM", "-xc")
882
	base = append(base, p.gccMachine()...)
883
	stdout, _ := runGcc(stdin, append(append(base, p.GccOptions...), "-"))
Russ Cox's avatar
Russ Cox committed
884 885 886 887 888 889 890 891
	return stdout
}

// gccErrors runs gcc over the C program stdin and returns
// the errors that gcc prints.  That is, this function expects
// gcc to fail.
func (p *Package) gccErrors(stdin []byte) string {
	// TODO(rsc): require failure
892
	args := p.gccCmd()
893

Russ Cox's avatar
Russ Cox committed
894 895 896 897 898 899 900 901 902
	if *debugGcc {
		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " "))
		os.Stderr.Write(stdin)
		fmt.Fprint(os.Stderr, "EOF\n")
	}
	stdout, stderr, _ := run(stdin, args)
	if *debugGcc {
		os.Stderr.Write(stdout)
		os.Stderr.Write(stderr)
903
	}
Russ Cox's avatar
Russ Cox committed
904 905
	return string(stderr)
}
906

Russ Cox's avatar
Russ Cox committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
// runGcc runs the gcc command line args with stdin on standard input.
// If the command exits with a non-zero exit status, runGcc prints
// details about what was run and exits.
// Otherwise runGcc returns the data written to standard output and standard error.
// Note that for some of the uses we expect useful data back
// on standard error, but for those uses gcc must still exit 0.
func runGcc(stdin []byte, args []string) (string, string) {
	if *debugGcc {
		fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " "))
		os.Stderr.Write(stdin)
		fmt.Fprint(os.Stderr, "EOF\n")
	}
	stdout, stderr, ok := run(stdin, args)
	if *debugGcc {
		os.Stderr.Write(stdout)
		os.Stderr.Write(stderr)
	}
924
	if !ok {
Russ Cox's avatar
Russ Cox committed
925 926
		os.Stderr.Write(stderr)
		os.Exit(2)
927
	}
Russ Cox's avatar
Russ Cox committed
928
	return string(stdout), string(stderr)
929 930
}

Russ Cox's avatar
Russ Cox committed
931 932 933 934
// A typeConv is a translator from dwarf types to Go types
// with equivalent memory layout.
type typeConv struct {
	// Cache of already-translated or in-progress types.
935 936
	m       map[dwarf.Type]*Type
	typedef map[string]ast.Expr
Russ Cox's avatar
Russ Cox committed
937

938 939
	// Map from types to incomplete pointers to those types.
	ptrs map[dwarf.Type][]*Type
940 941
	// Keys of ptrs in insertion order (deterministic worklist)
	ptrKeys []dwarf.Type
942

Russ Cox's avatar
Russ Cox committed
943
	// Predeclared types.
Devon H. O'Dell's avatar
Devon H. O'Dell committed
944
	bool                                   ast.Expr
945 946 947 948
	byte                                   ast.Expr // denotes padding
	int8, int16, int32, int64              ast.Expr
	uint8, uint16, uint32, uint64, uintptr ast.Expr
	float32, float64                       ast.Expr
949
	complex64, complex128                  ast.Expr
950 951
	void                                   ast.Expr
	string                                 ast.Expr
952
	goVoid                                 ast.Expr // _Ctype_void, denotes C's void
953
	goVoidPtr                              ast.Expr // unsafe.Pointer or *byte
Russ Cox's avatar
Russ Cox committed
954

955
	ptrSize int64
Russ Cox's avatar
Russ Cox committed
956
	intSize int64
Russ Cox's avatar
Russ Cox committed
957 958
}

959
var tagGen int
Russ Cox's avatar
Russ Cox committed
960
var typedef = make(map[string]*Type)
961
var goIdent = make(map[string]*ast.Ident)
962

Russ Cox's avatar
Russ Cox committed
963
func (c *typeConv) Init(ptrSize, intSize int64) {
964
	c.ptrSize = ptrSize
Russ Cox's avatar
Russ Cox committed
965
	c.intSize = intSize
966
	c.m = make(map[dwarf.Type]*Type)
967
	c.ptrs = make(map[dwarf.Type][]*Type)
Devon H. O'Dell's avatar
Devon H. O'Dell committed
968
	c.bool = c.Ident("bool")
969 970 971 972 973 974 975 976 977 978 979 980
	c.byte = c.Ident("byte")
	c.int8 = c.Ident("int8")
	c.int16 = c.Ident("int16")
	c.int32 = c.Ident("int32")
	c.int64 = c.Ident("int64")
	c.uint8 = c.Ident("uint8")
	c.uint16 = c.Ident("uint16")
	c.uint32 = c.Ident("uint32")
	c.uint64 = c.Ident("uint64")
	c.uintptr = c.Ident("uintptr")
	c.float32 = c.Ident("float32")
	c.float64 = c.Ident("float64")
981 982
	c.complex64 = c.Ident("complex64")
	c.complex128 = c.Ident("complex128")
983 984
	c.void = c.Ident("void")
	c.string = c.Ident("string")
985
	c.goVoid = c.Ident("_Ctype_void")
986 987

	// Normally cgo translates void* to unsafe.Pointer,
988 989
	// but for historical reasons -godefs uses *byte instead.
	if *godefs {
990 991 992 993
		c.goVoidPtr = &ast.StarExpr{X: c.byte}
	} else {
		c.goVoidPtr = c.Ident("unsafe.Pointer")
	}
Russ Cox's avatar
Russ Cox committed
994 995 996 997 998 999
}

// base strips away qualifiers and typedefs to get the underlying type
func base(dt dwarf.Type) dwarf.Type {
	for {
		if d, ok := dt.(*dwarf.QualType); ok {
1000 1001
			dt = d.Type
			continue
Russ Cox's avatar
Russ Cox committed
1002 1003
		}
		if d, ok := dt.(*dwarf.TypedefType); ok {
1004 1005
			dt = d.Type
			continue
Russ Cox's avatar
Russ Cox committed
1006
		}
1007
		break
Russ Cox's avatar
Russ Cox committed
1008
	}
1009
	return dt
Russ Cox's avatar
Russ Cox committed
1010 1011 1012
}

// Map from dwarf text names to aliases we use in package "C".
Russ Cox's avatar
Russ Cox committed
1013
var dwarfToName = map[string]string{
1014 1015 1016 1017 1018 1019
	"long int":               "long",
	"long unsigned int":      "ulong",
	"unsigned int":           "uint",
	"short unsigned int":     "ushort",
	"short int":              "short",
	"long long int":          "longlong",
Russ Cox's avatar
Russ Cox committed
1020
	"long long unsigned int": "ulonglong",
1021
	"signed char":            "schar",
1022 1023
	"float complex":          "complexfloat",
	"double complex":         "complexdouble",
Robert Griesemer's avatar
Robert Griesemer committed
1024
}
Russ Cox's avatar
Russ Cox committed
1025

1026 1027
const signedDelta = 64

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
// String returns the current type representation.  Format arguments
// are assembled within this method so that any changes in mutable
// values are taken into account.
func (tr *TypeRepr) String() string {
	if len(tr.Repr) == 0 {
		return ""
	}
	if len(tr.FormatArgs) == 0 {
		return tr.Repr
	}
	return fmt.Sprintf(tr.Repr, tr.FormatArgs...)
}

// Empty returns true if the result of String would be "".
func (tr *TypeRepr) Empty() bool {
	return len(tr.Repr) == 0
}

// Set modifies the type representation.
// If fargs are provided, repr is used as a format for fmt.Sprintf.
// Otherwise, repr is used unprocessed as the type representation.
func (tr *TypeRepr) Set(repr string, fargs ...interface{}) {
	tr.Repr = repr
	tr.FormatArgs = fargs
}

1054
// FinishType completes any outstanding type mapping work.
1055
// In particular, it resolves incomplete pointer types.
1056 1057 1058
func (c *typeConv) FinishType(pos token.Pos) {
	// Completing one pointer type might produce more to complete.
	// Keep looping until they're all done.
1059 1060 1061 1062 1063 1064 1065 1066 1067
	for len(c.ptrKeys) > 0 {
		dtype := c.ptrKeys[0]
		c.ptrKeys = c.ptrKeys[1:]

		// Note Type might invalidate c.ptrs[dtype].
		t := c.Type(dtype, pos)
		for _, ptr := range c.ptrs[dtype] {
			ptr.Go.(*ast.StarExpr).X = t.Go
			ptr.C.Set("%s*", t.C)
1068
		}
1069
		c.ptrs[dtype] = nil // retain the map key
1070 1071 1072
	}
}

Russ Cox's avatar
Russ Cox committed
1073 1074
// Type returns a *Type with the same memory layout as
// dtype when used as the type of a variable or a struct field.
1075
func (c *typeConv) Type(dtype dwarf.Type, pos token.Pos) *Type {
Russ Cox's avatar
Russ Cox committed
1076 1077
	if t, ok := c.m[dtype]; ok {
		if t.Go == nil {
1078
			fatalf("%s: type conversion loop at %s", lineno(pos), dtype)
Russ Cox's avatar
Russ Cox committed
1079
		}
1080
		return t
Russ Cox's avatar
Russ Cox committed
1081 1082
	}

1083
	t := new(Type)
1084
	t.Size = dtype.Size() // note: wrong for array of pointers, corrected below
1085
	t.Align = -1
1086
	t.C = &TypeRepr{Repr: dtype.Common().Name}
1087
	c.m[dtype] = t
Russ Cox's avatar
Russ Cox committed
1088

Russ Cox's avatar
Russ Cox committed
1089 1090
	switch dt := dtype.(type) {
	default:
1091
		fatalf("%s: unexpected type: %s", lineno(pos), dtype)
Russ Cox's avatar
Russ Cox committed
1092 1093 1094

	case *dwarf.AddrType:
		if t.Size != c.ptrSize {
1095
			fatalf("%s: unexpected: %d-byte address type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1096
		}
1097 1098
		t.Go = c.uintptr
		t.Align = t.Size
Russ Cox's avatar
Russ Cox committed
1099 1100 1101 1102

	case *dwarf.ArrayType:
		if dt.StrideBitSize > 0 {
			// Cannot represent bit-sized elements in Go.
1103 1104
			t.Go = c.Opaque(t.Size)
			break
Russ Cox's avatar
Russ Cox committed
1105
		}
1106 1107 1108 1109 1110 1111
		count := dt.Count
		if count == -1 {
			// Indicates flexible array member, which Go doesn't support.
			// Translate to zero-length array instead.
			count = 0
		}
1112
		sub := c.Type(dt.Type, pos)
1113
		t.Align = sub.Align
1114
		t.Go = &ast.ArrayType{
1115
			Len: c.intExpr(count),
1116 1117
			Elt: sub.Go,
		}
1118 1119
		// Recalculate t.Size now that we know sub.Size.
		t.Size = count * sub.Size
1120
		t.C.Set("__typeof__(%s[%d])", sub.C, dt.Count)
Russ Cox's avatar
Russ Cox committed
1121

Devon H. O'Dell's avatar
Devon H. O'Dell committed
1122 1123
	case *dwarf.BoolType:
		t.Go = c.bool
1124
		t.Align = 1
Devon H. O'Dell's avatar
Devon H. O'Dell committed
1125

Russ Cox's avatar
Russ Cox committed
1126 1127
	case *dwarf.CharType:
		if t.Size != 1 {
1128
			fatalf("%s: unexpected: %d-byte char type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1129
		}
1130 1131
		t.Go = c.int8
		t.Align = 1
Russ Cox's avatar
Russ Cox committed
1132 1133

	case *dwarf.EnumType:
1134 1135 1136
		if t.Align = t.Size; t.Align >= c.ptrSize {
			t.Align = c.ptrSize
		}
1137
		t.C.Set("enum " + dt.EnumName)
1138 1139 1140 1141 1142 1143 1144 1145 1146
		signed := 0
		t.EnumValues = make(map[string]int64)
		for _, ev := range dt.Val {
			t.EnumValues[ev.Name] = ev.Val
			if ev.Val < 0 {
				signed = signedDelta
			}
		}
		switch t.Size + int64(signed) {
Russ Cox's avatar
Russ Cox committed
1147
		default:
1148
			fatalf("%s: unexpected: %d-byte enum type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1149
		case 1:
1150
			t.Go = c.uint8
Russ Cox's avatar
Russ Cox committed
1151
		case 2:
1152
			t.Go = c.uint16
Russ Cox's avatar
Russ Cox committed
1153
		case 4:
1154
			t.Go = c.uint32
Russ Cox's avatar
Russ Cox committed
1155
		case 8:
1156
			t.Go = c.uint64
1157 1158 1159 1160 1161 1162 1163 1164
		case 1 + signedDelta:
			t.Go = c.int8
		case 2 + signedDelta:
			t.Go = c.int16
		case 4 + signedDelta:
			t.Go = c.int32
		case 8 + signedDelta:
			t.Go = c.int64
1165
		}
Russ Cox's avatar
Russ Cox committed
1166 1167 1168 1169

	case *dwarf.FloatType:
		switch t.Size {
		default:
1170
			fatalf("%s: unexpected: %d-byte float type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1171
		case 4:
1172
			t.Go = c.float32
Russ Cox's avatar
Russ Cox committed
1173
		case 8:
1174
			t.Go = c.float64
Russ Cox's avatar
Russ Cox committed
1175 1176
		}
		if t.Align = t.Size; t.Align >= c.ptrSize {
1177
			t.Align = c.ptrSize
Russ Cox's avatar
Russ Cox committed
1178 1179
		}

1180 1181 1182
	case *dwarf.ComplexType:
		switch t.Size {
		default:
1183
			fatalf("%s: unexpected: %d-byte complex type - %s", lineno(pos), t.Size, dtype)
1184 1185 1186 1187 1188 1189 1190 1191 1192
		case 8:
			t.Go = c.complex64
		case 16:
			t.Go = c.complex128
		}
		if t.Align = t.Size; t.Align >= c.ptrSize {
			t.Align = c.ptrSize
		}

Russ Cox's avatar
Russ Cox committed
1193 1194 1195
	case *dwarf.FuncType:
		// No attempt at translation: would enable calls
		// directly between worlds, but we need to moderate those.
1196 1197
		t.Go = c.uintptr
		t.Align = c.ptrSize
Russ Cox's avatar
Russ Cox committed
1198 1199 1200

	case *dwarf.IntType:
		if dt.BitSize > 0 {
1201
			fatalf("%s: unexpected: %d-bit int type - %s", lineno(pos), dt.BitSize, dtype)
Russ Cox's avatar
Russ Cox committed
1202 1203 1204
		}
		switch t.Size {
		default:
1205
			fatalf("%s: unexpected: %d-byte int type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1206
		case 1:
1207
			t.Go = c.int8
Russ Cox's avatar
Russ Cox committed
1208
		case 2:
1209
			t.Go = c.int16
Russ Cox's avatar
Russ Cox committed
1210
		case 4:
1211
			t.Go = c.int32
Russ Cox's avatar
Russ Cox committed
1212
		case 8:
1213
			t.Go = c.int64
Russ Cox's avatar
Russ Cox committed
1214 1215
		}
		if t.Align = t.Size; t.Align >= c.ptrSize {
1216
			t.Align = c.ptrSize
Russ Cox's avatar
Russ Cox committed
1217 1218 1219
		}

	case *dwarf.PtrType:
1220 1221 1222 1223 1224
		// Clang doesn't emit DW_AT_byte_size for pointer types.
		if t.Size != c.ptrSize && t.Size != -1 {
			fatalf("%s: unexpected: %d-byte pointer type - %s", lineno(pos), t.Size, dtype)
		}
		t.Size = c.ptrSize
1225
		t.Align = c.ptrSize
Russ Cox's avatar
Russ Cox committed
1226 1227

		if _, ok := base(dt.Type).(*dwarf.VoidType); ok {
1228
			t.Go = c.goVoidPtr
1229
			t.C.Set("void*")
1230
			break
Russ Cox's avatar
Russ Cox committed
1231 1232
		}

1233 1234 1235
		// Placeholder initialization; completed in FinishType.
		t.Go = &ast.StarExpr{}
		t.C.Set("<incomplete>*")
1236 1237 1238
		if _, ok := c.ptrs[dt.Type]; !ok {
			c.ptrKeys = append(c.ptrKeys, dt.Type)
		}
1239
		c.ptrs[dt.Type] = append(c.ptrs[dt.Type], t)
Russ Cox's avatar
Russ Cox committed
1240 1241 1242

	case *dwarf.QualType:
		// Ignore qualifier.
1243
		t = c.Type(dt.Type, pos)
1244 1245
		c.m[dtype] = t
		return t
Russ Cox's avatar
Russ Cox committed
1246 1247 1248 1249

	case *dwarf.StructType:
		// Convert to Go struct, being careful about alignment.
		// Have to give it a name to simulate C "struct foo" references.
1250
		tag := dt.StructName
1251 1252 1253
		if dt.ByteSize < 0 && tag == "" { // opaque unnamed struct - should not be possible
			break
		}
Russ Cox's avatar
Russ Cox committed
1254
		if tag == "" {
1255 1256
			tag = "__" + strconv.Itoa(tagGen)
			tagGen++
1257 1258
		} else if t.C.Empty() {
			t.C.Set(dt.Kind + " " + tag)
Russ Cox's avatar
Russ Cox committed
1259
		}
Russ Cox's avatar
Russ Cox committed
1260
		name := c.Ident("_Ctype_" + dt.Kind + "_" + tag)
1261
		t.Go = name // publish before recursive calls
1262
		goIdent[name.Name] = name
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
		if dt.ByteSize < 0 {
			// Size calculation in c.Struct/c.Opaque will die with size=-1 (unknown),
			// so execute the basic things that the struct case would do
			// other than try to determine a Go representation.
			tt := *t
			tt.C = &TypeRepr{"%s %s", []interface{}{dt.Kind, tag}}
			tt.Go = c.Ident("struct{}")
			typedef[name.Name] = &tt
			break
		}
Russ Cox's avatar
Russ Cox committed
1273
		switch dt.Kind {
1274
		case "class", "union":
1275
			t.Go = c.Opaque(t.Size)
1276
			if t.C.Empty() {
1277
				t.C.Set("__typeof__(unsigned char[%d])", t.Size)
Russ Cox's avatar
Russ Cox committed
1278
			}
1279
			t.Align = 1 // TODO: should probably base this on field alignment.
Russ Cox's avatar
Russ Cox committed
1280
			typedef[name.Name] = t
Russ Cox's avatar
Russ Cox committed
1281
		case "struct":
1282
			g, csyntax, align := c.Struct(dt, pos)
1283 1284
			if t.C.Empty() {
				t.C.Set(csyntax)
Russ Cox's avatar
Russ Cox committed
1285
			}
1286
			t.Align = align
Russ Cox's avatar
Russ Cox committed
1287 1288 1289 1290 1291 1292
			tt := *t
			if tag != "" {
				tt.C = &TypeRepr{"struct %s", []interface{}{tag}}
			}
			tt.Go = g
			typedef[name.Name] = &tt
Russ Cox's avatar
Russ Cox committed
1293 1294 1295 1296 1297 1298 1299 1300
		}

	case *dwarf.TypedefType:
		// Record typedef for printing.
		if dt.Name == "_GoString_" {
			// Special C name for Go string type.
			// Knows string layout used by compilers: pointer plus length,
			// which rounds up to 2 pointers after alignment.
1301 1302 1303 1304 1305
			t.Go = c.string
			t.Size = c.ptrSize * 2
			t.Align = c.ptrSize
			break
		}
Russ Cox's avatar
Russ Cox committed
1306 1307 1308 1309 1310 1311 1312 1313
		if dt.Name == "_GoBytes_" {
			// Special C name for Go []byte type.
			// Knows slice layout used by compilers: pointer, length, cap.
			t.Go = c.Ident("[]byte")
			t.Size = c.ptrSize + 4 + 4
			t.Align = c.ptrSize
			break
		}
1314 1315
		name := c.Ident("_Ctype_" + dt.Name)
		goIdent[name.Name] = name
1316
		sub := c.Type(dt.Type, pos)
1317
		t.Go = name
1318 1319
		t.Size = sub.Size
		t.Align = sub.Align
1320 1321
		oldType := typedef[name.Name]
		if oldType == nil {
Russ Cox's avatar
Russ Cox committed
1322 1323 1324
			tt := *t
			tt.Go = sub.Go
			typedef[name.Name] = &tt
Russ Cox's avatar
Russ Cox committed
1325
		}
1326 1327 1328 1329

		// If sub.Go.Name is "_Ctype_struct_foo" or "_Ctype_union_foo" or "_Ctype_class_foo",
		// use that as the Go form for this typedef too, so that the typedef will be interchangeable
		// with the base type.
1330 1331
		// In -godefs mode, do this for all typedefs.
		if isStructUnionClass(sub.Go) || *godefs {
1332
			t.Go = sub.Go
1333

1334 1335 1336 1337 1338
			if isStructUnionClass(sub.Go) {
				// Use the typedef name for C code.
				typedef[sub.Go.(*ast.Ident).Name].C = t.C
			}

1339 1340 1341 1342 1343 1344 1345 1346
			// If we've seen this typedef before, and it
			// was an anonymous struct/union/class before
			// too, use the old definition.
			// TODO: it would be safer to only do this if
			// we verify that the types are the same.
			if oldType != nil && isStructUnionClass(oldType.Go) {
				t.Go = oldType.Go
			}
1347
		}
Russ Cox's avatar
Russ Cox committed
1348 1349 1350

	case *dwarf.UcharType:
		if t.Size != 1 {
1351
			fatalf("%s: unexpected: %d-byte uchar type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1352
		}
1353 1354
		t.Go = c.uint8
		t.Align = 1
Russ Cox's avatar
Russ Cox committed
1355 1356 1357

	case *dwarf.UintType:
		if dt.BitSize > 0 {
1358
			fatalf("%s: unexpected: %d-bit uint type - %s", lineno(pos), dt.BitSize, dtype)
Russ Cox's avatar
Russ Cox committed
1359 1360 1361
		}
		switch t.Size {
		default:
1362
			fatalf("%s: unexpected: %d-byte uint type - %s", lineno(pos), t.Size, dtype)
Russ Cox's avatar
Russ Cox committed
1363
		case 1:
1364
			t.Go = c.uint8
Russ Cox's avatar
Russ Cox committed
1365
		case 2:
1366
			t.Go = c.uint16
Russ Cox's avatar
Russ Cox committed
1367
		case 4:
1368
			t.Go = c.uint32
Russ Cox's avatar
Russ Cox committed
1369
		case 8:
1370
			t.Go = c.uint64
Russ Cox's avatar
Russ Cox committed
1371 1372
		}
		if t.Align = t.Size; t.Align >= c.ptrSize {
1373
			t.Align = c.ptrSize
Russ Cox's avatar
Russ Cox committed
1374 1375 1376
		}

	case *dwarf.VoidType:
1377
		t.Go = c.goVoid
1378
		t.C.Set("void")
1379
		t.Align = 1
Russ Cox's avatar
Russ Cox committed
1380 1381 1382
	}

	switch dtype.(type) {
Devon H. O'Dell's avatar
Devon H. O'Dell committed
1383
	case *dwarf.AddrType, *dwarf.BoolType, *dwarf.CharType, *dwarf.IntType, *dwarf.FloatType, *dwarf.UcharType, *dwarf.UintType:
1384
		s := dtype.Common().Name
Russ Cox's avatar
Russ Cox committed
1385
		if s != "" {
Russ Cox's avatar
Russ Cox committed
1386
			if ss, ok := dwarfToName[s]; ok {
1387
				s = ss
Russ Cox's avatar
Russ Cox committed
1388
			}
1389
			s = strings.Join(strings.Split(s, " "), "") // strip spaces
Russ Cox's avatar
Russ Cox committed
1390
			name := c.Ident("_Ctype_" + s)
Russ Cox's avatar
Russ Cox committed
1391 1392
			tt := *t
			typedef[name.Name] = &tt
1393
			if !*godefs {
1394 1395
				t.Go = name
			}
Russ Cox's avatar
Russ Cox committed
1396 1397 1398
		}
	}

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
	if t.Size < 0 {
		// Unsized types are [0]byte, unless they're typedefs of other types
		// or structs with tags.
		// if so, use the name we've already defined.
		t.Size = 0
		switch dt := dtype.(type) {
		case *dwarf.TypedefType:
			// ok
		case *dwarf.StructType:
			if dt.StructName != "" {
				break
1410
			}
1411 1412 1413 1414 1415 1416
			t.Go = c.Opaque(0)
		default:
			t.Go = c.Opaque(0)
		}
		if t.C.Empty() {
			t.C.Set("void")
1417 1418 1419
		}
	}

1420
	if t.C.Empty() {
1421
		fatalf("%s: internal error: did not create C name for %s", lineno(pos), dtype)
Russ Cox's avatar
Russ Cox committed
1422 1423
	}

1424
	return t
Russ Cox's avatar
Russ Cox committed
1425 1426
}

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
// isStructUnionClass reports whether the type described by the Go syntax x
// is a struct, union, or class with a tag.
func isStructUnionClass(x ast.Expr) bool {
	id, ok := x.(*ast.Ident)
	if !ok {
		return false
	}
	name := id.Name
	return strings.HasPrefix(name, "_Ctype_struct_") ||
		strings.HasPrefix(name, "_Ctype_union_") ||
		strings.HasPrefix(name, "_Ctype_class_")
}

Russ Cox's avatar
Russ Cox committed
1440 1441
// FuncArg returns a Go type with the same memory layout as
// dtype when used as the type of a C function argument.
1442 1443
func (c *typeConv) FuncArg(dtype dwarf.Type, pos token.Pos) *Type {
	t := c.Type(dtype, pos)
Russ Cox's avatar
Russ Cox committed
1444 1445 1446 1447
	switch dt := dtype.(type) {
	case *dwarf.ArrayType:
		// Arrays are passed implicitly as pointers in C.
		// In Go, we must be explicit.
1448 1449
		tr := &TypeRepr{}
		tr.Set("%s*", t.C)
Russ Cox's avatar
Russ Cox committed
1450
		return &Type{
1451
			Size:  c.ptrSize,
Russ Cox's avatar
Russ Cox committed
1452
			Align: c.ptrSize,
1453
			Go:    &ast.StarExpr{X: t.Go},
1454
			C:     tr,
1455
		}
Russ Cox's avatar
Russ Cox committed
1456 1457 1458 1459 1460 1461
	case *dwarf.TypedefType:
		// C has much more relaxed rules than Go for
		// implicit type conversions.  When the parameter
		// is type T defined as *X, simulate a little of the
		// laxness of C by making the argument *X instead of T.
		if ptr, ok := base(dt.Type).(*dwarf.PtrType); ok {
1462 1463
			// Unless the typedef happens to point to void* since
			// Go has special rules around using unsafe.Pointer.
Russ Cox's avatar
Russ Cox committed
1464 1465
			if _, void := base(ptr.Type).(*dwarf.VoidType); void {
				break
1466
			}
Russ Cox's avatar
Russ Cox committed
1467 1468 1469 1470 1471 1472 1473 1474 1475

			t = c.Type(ptr, pos)
			if t == nil {
				return nil
			}

			// Remember the C spelling, in case the struct
			// has __attribute__((unavailable)) on it.  See issue 2888.
			t.Typedef = dt.Name
Russ Cox's avatar
Russ Cox committed
1476 1477
		}
	}
1478
	return t
Russ Cox's avatar
Russ Cox committed
1479 1480 1481 1482
}

// FuncType returns the Go type analogous to dtype.
// There is no guarantee about matching memory layout.
1483
func (c *typeConv) FuncType(dtype *dwarf.FuncType, pos token.Pos) *FuncType {
1484 1485
	p := make([]*Type, len(dtype.ParamType))
	gp := make([]*ast.Field, len(dtype.ParamType))
Russ Cox's avatar
Russ Cox committed
1486
	for i, f := range dtype.ParamType {
1487 1488 1489 1490 1491 1492
		// gcc's DWARF generator outputs a single DotDotDotType parameter for
		// function pointers that specify no parameters (e.g. void
		// (*__cgo_0)()).  Treat this special case as void.  This case is
		// invalid according to ISO C anyway (i.e. void (*__cgo_1)(...) is not
		// legal).
		if _, ok := f.(*dwarf.DotDotDotType); ok && i == 0 {
1493 1494
			p, gp = nil, nil
			break
1495
		}
1496
		p[i] = c.FuncArg(f, pos)
1497
		gp[i] = &ast.Field{Type: p[i].Go}
Russ Cox's avatar
Russ Cox committed
1498
	}
1499 1500
	var r *Type
	var gr []*ast.Field
1501 1502 1503
	if _, ok := dtype.ReturnType.(*dwarf.VoidType); ok {
		gr = []*ast.Field{{Type: c.goVoid}}
	} else if dtype.ReturnType != nil {
1504
		r = c.Type(dtype.ReturnType, pos)
Russ Cox's avatar
Russ Cox committed
1505
		gr = []*ast.Field{{Type: r.Go}}
Russ Cox's avatar
Russ Cox committed
1506 1507 1508 1509 1510
	}
	return &FuncType{
		Params: p,
		Result: r,
		Go: &ast.FuncType{
1511
			Params:  &ast.FieldList{List: gp},
1512
			Results: &ast.FieldList{List: gr},
Robert Griesemer's avatar
Robert Griesemer committed
1513
		},
1514
	}
Russ Cox's avatar
Russ Cox committed
1515 1516 1517
}

// Identifier
Russ Cox's avatar
Russ Cox committed
1518 1519 1520
func (c *typeConv) Ident(s string) *ast.Ident {
	return ast.NewIdent(s)
}
Russ Cox's avatar
Russ Cox committed
1521 1522 1523 1524 1525

// Opaque type of n bytes.
func (c *typeConv) Opaque(n int64) ast.Expr {
	return &ast.ArrayType{
		Len: c.intExpr(n),
Robert Griesemer's avatar
Robert Griesemer committed
1526
		Elt: c.byte,
1527
	}
Russ Cox's avatar
Russ Cox committed
1528 1529 1530 1531 1532
}

// Expr for integer n.
func (c *typeConv) intExpr(n int64) ast.Expr {
	return &ast.BasicLit{
1533
		Kind:  token.INT,
Russ Cox's avatar
Russ Cox committed
1534
		Value: strconv.FormatInt(n, 10),
1535
	}
Russ Cox's avatar
Russ Cox committed
1536 1537 1538 1539
}

// Add padding of given size to fld.
func (c *typeConv) pad(fld []*ast.Field, size int64) []*ast.Field {
1540 1541 1542 1543
	n := len(fld)
	fld = fld[0 : n+1]
	fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)}
	return fld
Russ Cox's avatar
Russ Cox committed
1544 1545
}

Russ Cox's avatar
Russ Cox committed
1546
// Struct conversion: return Go and (6g) C syntax for type.
1547
func (c *typeConv) Struct(dt *dwarf.StructType, pos token.Pos) (expr *ast.StructType, csyntax string, align int64) {
1548 1549 1550
	// Minimum alignment for a struct is 1 byte.
	align = 1

Russ Cox's avatar
Russ Cox committed
1551 1552
	var buf bytes.Buffer
	buf.WriteString("struct {")
1553 1554
	fld := make([]*ast.Field, 0, 2*len(dt.Field)+1) // enough for padding around every field
	off := int64(0)
1555

Russ Cox's avatar
Russ Cox committed
1556
	// Rename struct fields that happen to be named Go keywords into
1557 1558 1559 1560 1561
	// _{keyword}.  Create a map from C ident -> Go ident.  The Go ident will
	// be mangled.  Any existing identifier that already has the same name on
	// the C-side will cause the Go-mangled version to be prefixed with _.
	// (e.g. in a struct with fields '_type' and 'type', the latter would be
	// rendered as '__type' in Go).
1562 1563
	ident := make(map[string]string)
	used := make(map[string]bool)
1564
	for _, f := range dt.Field {
1565 1566
		ident[f.Name] = f.Name
		used[f.Name] = true
1567 1568
	}

1569
	if !*godefs {
1570
		for cid, goid := range ident {
1571
			if token.Lookup(goid).IsKeyword() {
1572
				// Avoid keyword
1573 1574
				goid = "_" + goid

1575 1576 1577 1578 1579 1580 1581 1582
				// Also avoid existing fields
				for _, exist := used[goid]; exist; _, exist = used[goid] {
					goid = "_" + goid
				}

				used[goid] = true
				ident[cid] = goid
			}
1583 1584 1585
		}
	}

1586
	anon := 0
Russ Cox's avatar
Russ Cox committed
1587 1588
	for _, f := range dt.Field {
		if f.ByteOffset > off {
1589 1590
			fld = c.pad(fld, f.ByteOffset-off)
			off = f.ByteOffset
Russ Cox's avatar
Russ Cox committed
1591
		}
1592 1593 1594 1595

		name := f.Name
		ft := f.Type

1596
		// In godefs mode, if this field is a C11
1597 1598 1599 1600
		// anonymous union then treat the first field in the
		// union as the field in the struct.  This handles
		// cases like the glibc <sys/resource.h> file; see
		// issue 6677.
1601
		if *godefs {
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
			if st, ok := f.Type.(*dwarf.StructType); ok && name == "" && st.Kind == "union" && len(st.Field) > 0 && !used[st.Field[0].Name] {
				name = st.Field[0].Name
				ident[name] = name
				ft = st.Field[0].Type
			}
		}

		// TODO: Handle fields that are anonymous structs by
		// promoting the fields of the inner struct.

		t := c.Type(ft, pos)
1613 1614
		tgo := t.Go
		size := t.Size
1615
		talign := t.Align
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
		if f.BitSize > 0 {
			if f.BitSize%8 != 0 {
				continue
			}
			size = f.BitSize / 8
			name := tgo.(*ast.Ident).String()
			if strings.HasPrefix(name, "int") {
				name = "int"
			} else {
				name = "uint"
			}
			tgo = ast.NewIdent(name + fmt.Sprint(f.BitSize))
1628
			talign = size
1629 1630
		}

1631
		if talign > 0 && f.ByteOffset%talign != 0 {
1632 1633 1634 1635 1636 1637 1638
			// Drop misaligned fields, the same way we drop integer bit fields.
			// The goal is to make available what can be made available.
			// Otherwise one bad and unneeded field in an otherwise okay struct
			// makes the whole program not compile. Much of the time these
			// structs are in system headers that cannot be corrected.
			continue
		}
1639 1640
		n := len(fld)
		fld = fld[0 : n+1]
1641 1642 1643 1644 1645 1646 1647
		if name == "" {
			name = fmt.Sprintf("anon%d", anon)
			anon++
			ident[name] = name
		}
		fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[name])}, Type: tgo}
		off += size
1648
		buf.WriteString(t.C.String())
Russ Cox's avatar
Russ Cox committed
1649
		buf.WriteString(" ")
1650
		buf.WriteString(name)
Russ Cox's avatar
Russ Cox committed
1651
		buf.WriteString("; ")
1652 1653
		if talign > align {
			align = talign
Russ Cox's avatar
Russ Cox committed
1654 1655 1656
		}
	}
	if off < dt.ByteSize {
1657 1658
		fld = c.pad(fld, dt.ByteSize-off)
		off = dt.ByteSize
Russ Cox's avatar
Russ Cox committed
1659 1660
	}
	if off != dt.ByteSize {
Russ Cox's avatar
Russ Cox committed
1661
		fatalf("%s: struct size calculation error off=%d bytesize=%d", lineno(pos), off, dt.ByteSize)
Russ Cox's avatar
Russ Cox committed
1662
	}
Russ Cox's avatar
Russ Cox committed
1663 1664
	buf.WriteString("}")
	csyntax = buf.String()
1665

1666
	if *godefs {
1667
		godefsFields(fld)
1668
	}
1669
	expr = &ast.StructType{Fields: &ast.FieldList{List: fld}}
1670
	return
Russ Cox's avatar
Russ Cox committed
1671
}
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

func upper(s string) string {
	if s == "" {
		return ""
	}
	r, size := utf8.DecodeRuneInString(s)
	if r == '_' {
		return "X" + s
	}
	return string(unicode.ToUpper(r)) + s[size:]
}

// godefsFields rewrites field names for use in Go or C definitions.
// It strips leading common prefixes (like tv_ in tv_sec, tv_usec)
// converts names to upper case, and rewrites _ into Pad_godefs_n,
// so that all fields are exported.
func godefsFields(fld []*ast.Field) {
	prefix := fieldPrefix(fld)
	npad := 0
	for _, f := range fld {
		for _, n := range f.Names {
1693 1694
			if n.Name != prefix {
				n.Name = strings.TrimPrefix(n.Name, prefix)
1695 1696 1697 1698 1699 1700
			}
			if n.Name == "_" {
				// Use exported name instead.
				n.Name = "Pad_cgo_" + strconv.Itoa(npad)
				npad++
			}
1701
			n.Name = upper(n.Name)
1702 1703 1704 1705 1706
		}
	}
}

// fieldPrefix returns the prefix that should be removed from all the
1707
// field names when generating the C or Go code.  For generated
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
// C, we leave the names as is (tv_sec, tv_usec), since that's what
// people are used to seeing in C.  For generated Go code, such as
// package syscall's data structures, we drop a common prefix
// (so sec, usec, which will get turned into Sec, Usec for exporting).
func fieldPrefix(fld []*ast.Field) string {
	prefix := ""
	for _, f := range fld {
		for _, n := range f.Names {
			// Ignore field names that don't have the prefix we're
			// looking for.  It is common in C headers to have fields
			// named, say, _pad in an otherwise prefixed header.
			// If the struct has 3 fields tv_sec, tv_usec, _pad1, then we
			// still want to remove the tv_ prefix.
1721
			// The check for "orig_" here handles orig_eax in the
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
			// x86 ptrace register sets, which otherwise have all fields
			// with reg_ prefixes.
			if strings.HasPrefix(n.Name, "orig_") || strings.HasPrefix(n.Name, "_") {
				continue
			}
			i := strings.Index(n.Name, "_")
			if i < 0 {
				continue
			}
			if prefix == "" {
				prefix = n.Name[:i+1]
			} else if prefix != n.Name[:i+1] {
				return ""
			}
		}
	}
	return prefix
}