forked from elliotchance/c2go
/
sizeof.go
97 lines (75 loc) · 1.88 KB
/
sizeof.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package types
import (
"errors"
"fmt"
"strings"
"github.com/elliotchance/c2go/program"
)
func removePrefix(s, prefix string) string {
if strings.HasPrefix(s, prefix) {
s = s[len(prefix):]
}
return s
}
// SizeOf returns the number of bytes for a type. This the same as using the
// sizeof operator/function in C.
func SizeOf(p *program.Program, cType string) (int, error) {
// Remove keywords that do not effect the size.
cType = removePrefix(cType, "signed ")
cType = removePrefix(cType, "unsigned ")
cType = removePrefix(cType, "const ")
cType = removePrefix(cType, "volatile ")
// FIXME: The pointer size will be different on different platforms. We
// should find out the correct size at runtime.
pointerSize := 8
// A structure will be the sum of its parts.
if strings.HasPrefix(cType, "struct ") {
totalBytes := 0
s := p.Structs[cType[7:]]
if s == nil {
return 0, errors.New(fmt.Sprintf("could not sizeof: %s", cType))
}
for _, t := range s.Fields {
var bytes int
var err error
switch f := t.(type) {
case string:
bytes, err = SizeOf(p, f)
case *program.Struct:
bytes, err = SizeOf(p, f.Name)
}
if err != nil {
return 0, err
}
totalBytes += bytes
}
// The size of a struct is rounded up to fit the size of the pointer of
// the OS.
if totalBytes%pointerSize != 0 {
totalBytes += pointerSize - (totalBytes % pointerSize)
}
return totalBytes, nil
}
// Function pointers are one byte?
if strings.Index(cType, "(") >= 0 {
return 1, nil
}
if strings.HasSuffix(cType, "*") {
return pointerSize, nil
}
switch cType {
case "char", "void":
return 1, nil
case "short":
return 2, nil
case "int", "float":
return 4, nil
case "long", "double":
return 8, nil
case "long double":
return 16, nil
default:
return pointerSize, errors.New(
fmt.Sprintf("cannot determine size of: %s", cType))
}
}