Debian Codegraph @

libgo/go/cmd/cgo/gcc.go

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