Colin Cross | 1371fe4 | 2019-03-19 21:08:48 -0700 | [diff] [blame] | 1 | // Copyright 2018 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 | // cgo was incorrectly adding padding after a packed struct. |
| 6 | |
| 7 | package cgotest |
| 8 | |
| 9 | /* |
| 10 | #include <stddef.h> |
| 11 | #include <stdint.h> |
| 12 | #include <stdlib.h> |
| 13 | |
| 14 | typedef struct { |
| 15 | void *f1; |
| 16 | uint32_t f2; |
| 17 | } __attribute__((__packed__)) innerPacked; |
| 18 | |
| 19 | typedef struct { |
| 20 | innerPacked g1; |
| 21 | uint64_t g2; |
| 22 | } outerPacked; |
| 23 | |
| 24 | typedef struct { |
| 25 | void *f1; |
| 26 | uint32_t f2; |
| 27 | } innerUnpacked; |
| 28 | |
| 29 | typedef struct { |
| 30 | innerUnpacked g1; |
| 31 | uint64_t g2; |
| 32 | } outerUnpacked; |
| 33 | |
| 34 | size_t offset(int x) { |
| 35 | switch (x) { |
| 36 | case 0: |
| 37 | return offsetof(innerPacked, f2); |
| 38 | case 1: |
| 39 | return offsetof(outerPacked, g2); |
| 40 | case 2: |
| 41 | return offsetof(innerUnpacked, f2); |
| 42 | case 3: |
| 43 | return offsetof(outerUnpacked, g2); |
| 44 | default: |
| 45 | abort(); |
| 46 | } |
| 47 | } |
| 48 | */ |
| 49 | import "C" |
| 50 | |
| 51 | import ( |
| 52 | "testing" |
| 53 | "unsafe" |
| 54 | ) |
| 55 | |
| 56 | func offset(i int) uintptr { |
| 57 | var pi C.innerPacked |
| 58 | var po C.outerPacked |
| 59 | var ui C.innerUnpacked |
| 60 | var uo C.outerUnpacked |
| 61 | switch i { |
| 62 | case 0: |
| 63 | return unsafe.Offsetof(pi.f2) |
| 64 | case 1: |
| 65 | return unsafe.Offsetof(po.g2) |
| 66 | case 2: |
| 67 | return unsafe.Offsetof(ui.f2) |
| 68 | case 3: |
| 69 | return unsafe.Offsetof(uo.g2) |
| 70 | default: |
| 71 | panic("can't happen") |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func test28896(t *testing.T) { |
| 76 | for i := 0; i < 4; i++ { |
| 77 | c := uintptr(C.offset(C.int(i))) |
| 78 | g := offset(i) |
| 79 | if c != g { |
| 80 | t.Errorf("%d: C: %d != Go %d", i, c, g) |
| 81 | } |
| 82 | } |
| 83 | } |