forked from tv42/alone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (78 loc) · 1.4 KB
/
main.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
package main
import (
"compress/gzip"
"debug/elf"
"io"
"log"
"os"
"github.com/surma/gocpio"
)
func getSize(r io.Seeker) (int64, error) {
var size int64
var err error
size, err = r.Seek(0, os.SEEK_END)
if err != nil {
return 0, err
}
_, err = r.Seek(0, os.SEEK_SET)
if err != nil {
return size, err
}
return size, nil
}
func writeCpio(w io.Writer, init io.ReadSeeker) error {
var size int64
var err error
size, err = getSize(init)
if err != nil {
return err
}
archive := cpio.NewWriter(w)
err = archive.WriteHeader(&cpio.Header{
Mode: 0755,
Size: size,
Type: cpio.TYPE_REG,
Name: "init",
})
if err != nil {
return err
}
_, err = io.Copy(archive, init)
if err != nil {
return err
}
return archive.Close()
}
func isStatic(r io.ReaderAt) (bool, error) {
f, err := elf.NewFile(r)
if err != nil {
return false, err
}
libs, err := f.ImportedLibraries()
if err != nil {
return false, err
}
if len(libs) > 0 {
return false, nil
}
return true, nil
}
func main() {
static, err := isStatic(os.Stdin)
if err != nil {
log.Fatalf("cannot decode ELF header: %v", err)
}
if !static {
log.Fatal("input binary must be statically linked")
}
w := gzip.NewWriter(os.Stdout)
w.Header.Name = "initramfs.cpio"
err = writeCpio(w, os.Stdin)
if err != nil {
log.Fatalf("cpio failed: %v", err)
}
err = w.Close()
if err != nil {
log.Fatalf("gzip failed: %v", err)
}
}