/
zlib_generate.go
293 lines (251 loc) · 8.47 KB
/
zlib_generate.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//+build zlib_generate
// Based on geek1011/dictutil/marisa/libmarisa_generate.go
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"regexp"
"strings"
)
func main() {
// url := "https://github.com/madler/zlib/archive/v1.2.11.tar.gz"
// version := "cacf7f1"
// url := "https://gitlab.com/sortix/libz/-/archive/v1.2.11/libz-v1.2.11.tar.gz"
// version := "cacf7f1d"
url := "https://gitlab.com/sortix/libz/-/archive/852e2b05851bfa471eb627ae16bf7b1d5e0a5a78/libz-852e2b05851bfa471eb627ae16bf7b1d5e0a5a78.tar.gz"
version := "852e2b05"
if files, err := tarball(url); err != nil {
fmt.Fprintf(os.Stderr, "Error: download tarball %#v: %v\n", url, err)
os.Exit(1)
return
} else if err := func() error {
if mr, err := libzlib(files, version); err != nil {
return err
} else if mf, err := os.OpenFile("zlib.c", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644); err != nil {
return err
} else if _, err := io.Copy(mf, mr); err != nil {
mf.Close()
return err
} else {
return mf.Close()
}
}(); err != nil {
fmt.Fprintf(os.Stderr, "Error: generate zlib.c: %v\n", err)
os.Exit(1)
return
} else if err := func() error {
if mr, err := hzlib(files, version); err != nil {
return err
} else if mf, err := os.OpenFile("zlib.h", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644); err != nil {
return err
} else if _, err := io.Copy(mf, mr); err != nil {
mf.Close()
return err
} else {
return mf.Close()
}
}(); err != nil {
fmt.Fprintf(os.Stderr, "Error: generate zlib.h: %v\n", err)
os.Exit(1)
return
}
}
func hzutil(files map[string][]byte, version string) (io.Reader, error) {
marisaH, err := resolve(files, []string{
"zutil.h",
})
if err != nil {
return nil, err
}
fmt.Printf("Generating zutil.h\n")
return io.MultiReader(
// A custom header.
strings.NewReader("// AUTOMATICALLY GENERATED, DO NOT EDIT!\n"),
strings.NewReader("// merged from sortix libz "+version+".\n"),
// Include the header.
bytes.NewReader(marisaH),
), nil
}
func hzlib(files map[string][]byte, version string) (io.Reader, error) {
marisaH, err := resolve(files, []string{
"zlib.h",
})
if err != nil {
return nil, err
}
fmt.Printf("Generating zlib.h\n")
return io.MultiReader(
// A custom header.
strings.NewReader("// AUTOMATICALLY GENERATED, DO NOT EDIT!\n"),
strings.NewReader("// merged from sortix libz "+version+".\n"),
// Include the header.
bytes.NewReader(marisaH),
), nil
}
// libzlib 处理文件 zlib.c,替换相关文件内容,生成文件
func libzlib(files map[string][]byte, version string) (io.Reader, error) {
dfiles := map[string][]byte{}
for fn, b := range files {
dfiles[fn] = b
// fix used identifier from gzgutsneeded by inf*
if fn == "infback.c" {
dfiles[fn] = append([]byte("#undef COPY\n"), dfiles[fn]...)
}
// fix identical func redeclarations
if fn == "deflate.c" {
dfiles[fn] = bytes.ReplaceAll(dfiles[fn], []byte("static unsigned long saturateAddBound"), []byte("__attribute__((unused)) static unsigned long saturateAddBound_"))
}
if fn == "inflate.c" {
dfiles[fn] = bytes.ReplaceAll(dfiles[fn], []byte("static void fixedtables"), []byte("__attribute__((unused)) static void fixedtables_"))
}
// fix identical macro redeclarations
if fn == "inflate.c" {
dfiles[fn] = bytes.ReplaceAll(dfiles[fn], []byte("#define PULLBYTE"), []byte("#undef PULLBYTE\n#define PULLBYTE"))
dfiles[fn] = bytes.ReplaceAll(dfiles[fn], []byte("#define DROPBITS"), []byte("#undef DROPBITS\n#define DROPBITS"))
}
// we don't need endian.h to check endianness (and it isn't available on Windows)
dfiles[fn] = bytes.ReplaceAll(dfiles[fn], []byte("#include <endian.h>"), []byte("#ifndef ZLIBGEN_ENDIAN_SHIM_H\n#define ZLIBGEN_ENDIAN_SHIM_H\n#ifndef BYTE_ORDER\n#define BYTE_ORDER __BYTE_ORDER__\n#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__\n#define BIG_ENDIAN __ORDER_BIG_ENDIAN__\n#endif\n#endif\n"))
// add header guards
if strings.HasSuffix(fn, ".h") && fn != "inffixed.h" {
hn := "ZLIBGEN_" + strings.ToUpper(strings.TrimSuffix(fn, ".h")) + "_H"
dfiles[fn] = append([]byte("#ifndef "+hn+"\n#define "+hn+"\n"), append(b, []byte("#endif")...)...)
}
}
zlib, err := resolve(dfiles, []string{
"zconf.h",
"adler32.c",
"compress.c",
"crc32.c",
"deflate.c",
"gzclose.c",
"gzlib.c",
"gzread.c",
"gzwrite.c",
"infback.c",
"inffast.c",
"inflate.c",
"inftrees.c",
"trees.c",
"uncompr.c",
"zutil.c",
})
if err != nil {
return nil, err
}
fmt.Printf("Generating zlib.c\n")
return io.MultiReader(
// A custom header.
strings.NewReader("// AUTOMATICALLY GENERATED, DO NOT EDIT!\n"),
strings.NewReader("// merged from sortix zlib "+version+".\n"),
// Include the defines
strings.NewReader("#define _GNU_SOURCE\n"),
strings.NewReader("#define Z_INSIDE_LIBZ\n"),
// Include the warnings from the Makefile.in CFLAGS.
// - Note that Clang also recognizes the GCC pragmas.
strings.NewReader("#pragma GCC diagnostic warning \"-Wall\"\n"),
strings.NewReader("#pragma GCC diagnostic warning \"-Wextra\"\n"),
strings.NewReader("#pragma GCC diagnostic ignored \"-Wimplicit-fallthrough\"\n"),
// Include the libs themselves.
bytes.NewReader(zlib),
// Show info about the generated file.
strings.NewReader("#line 1 \"zlib_generate.go\"\n"),
strings.NewReader("#pragma GCC warning \"Using generated built-in sortix zlib "+version+".\"\n"),
), nil
}
func tarball(url string) (map[string][]byte, error) {
fmt.Printf("Downloading tarball from %s\n", url)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
zr, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, err
}
var pfx string
files := map[string][]byte{}
tr := tar.NewReader(zr)
for {
fh, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if fh.Name == "pax_global_header" || fh.FileInfo().IsDir() {
continue
}
if pfx == "" {
if strings.HasPrefix(fh.Name, "./") {
pfx = "./" + strings.Split(fh.Name, "/")[1] + "/"
} else {
pfx = strings.Split(fh.Name, "/")[0] + "/"
}
}
if !strings.HasPrefix(fh.Name, pfx) {
return nil, fmt.Errorf("extract file %#v: doesn't have common prefix %#v", fh.Name, pfx)
}
buf, err := ioutil.ReadAll(tr)
if err != nil {
return nil, fmt.Errorf("extract file %#v: %w", fh.Name, err)
}
fn := strings.TrimPrefix(fh.Name, pfx)
files[fn] = buf
fmt.Printf(" [D] %s\n", fn) // downloaded
}
return files, nil
}
func resolve(files map[string][]byte, filenames []string, includePath ...string) (resolvedFile []byte, err error) {
fmt.Printf("Resolving C* source files %s (against:%s) (I = included, S = preserved because not found, R = skipped because already included)\n", filenames, includePath)
var resolveFn func(indent string, files map[string][]byte, filename string, buf []byte, done []string, includePath []string) (resolvedFile []byte, err error)
resolveFn = func(indent string, files map[string][]byte, filename string, buf []byte, done []string, includePath []string) (resolvedFile []byte, err error) {
defer func() {
if rerr := recover(); rerr != nil {
resolvedFile, err = nil, rerr.(error)
}
}()
resolvedFile = regexp.MustCompile(`(?m)^\s*#\s*include\s+["'<][^"'>]+["'>]$`).ReplaceAllFunc(buf, func(importBuf []byte) []byte {
fn := string(regexp.MustCompile(`["'<]([^"'>]+)["'>]`).FindSubmatch(importBuf)[1])
for _, ip := range includePath {
ifn := path.Join(ip, fn)
for _, dfn := range done {
if m, _ := path.Match(dfn, ifn); m {
fmt.Printf("%s[R] %s\n", indent, fn) // already included
return nil
}
}
ibuf, ok := files[ifn]
if ok {
fmt.Printf("%s[I] %s => %s\n", indent, fn, ifn) // include
ibuf, err := resolveFn(indent+" ", files, ifn, ibuf, append(done, ifn), append(includePath, path.Dir(ifn)))
if err != nil {
panic(fmt.Errorf("resolve %#v: %w", ifn, err))
}
return append(append([]byte{'\n', '\n'}, ibuf...), '\n', '\n')
}
}
fmt.Printf("%s[S] %s\n", indent, fn) // preserve
return importBuf
})
return
}
for _, fn := range filenames {
if buf, ok := files[fn]; !ok {
return nil, fmt.Errorf("file %#v: not found", fn)
} else if buf, err := resolveFn(" ", files, fn, buf, []string{fn}, append(includePath, path.Dir(fn))); err != nil {
return nil, fmt.Errorf("file %v: %w", fn, err)
} else {
resolvedFile = append(resolvedFile, buf...)
resolvedFile = append(resolvedFile, '\n', '\n')
}
}
return resolvedFile, nil
}