forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 2
/
uroot.go
369 lines (329 loc) · 11.2 KB
/
uroot.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright 2015-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uroot
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/u-root/u-root/pkg/cpio"
"github.com/u-root/u-root/pkg/golang"
"github.com/u-root/u-root/pkg/ldd"
"github.com/u-root/u-root/pkg/uroot/builder"
"github.com/u-root/u-root/pkg/uroot/initramfs"
)
// These constants are used in DefaultRamfs.
const (
// This is the literal timezone file for GMT-0. Given that we have no
// idea where we will be running, GMT seems a reasonable guess. If it
// matters, setup code should download and change this to something
// else.
gmt0 = "TZif2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00GMT\x00\x00\x00TZif2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x04\xf8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00GMT\x00\x00\x00\nGMT0\n"
nameserver = "nameserver 8.8.8.8\n"
)
// DefaultRamfs are files that are contained in all u-root initramfs archives
// by default.
var DefaultRamfs = []cpio.Record{
cpio.Directory("tcz", 0755),
cpio.Directory("etc", 0755),
cpio.Directory("dev", 0755),
cpio.Directory("tmp", 0777),
cpio.Directory("ubin", 0755),
cpio.Directory("usr", 0755),
cpio.Directory("usr/lib", 0755),
cpio.Directory("var/log", 0777),
cpio.Directory("lib64", 0755),
cpio.Directory("bin", 0755),
cpio.CharDev("dev/console", 0600, 5, 1),
cpio.CharDev("dev/tty", 0666, 5, 0),
cpio.CharDev("dev/null", 0666, 1, 3),
cpio.CharDev("dev/port", 0640, 1, 4),
cpio.CharDev("dev/urandom", 0666, 1, 9),
cpio.StaticFile("etc/resolv.conf", nameserver, 0644),
cpio.StaticFile("etc/localtime", gmt0, 0644),
}
// Commands specifies a list of Golang packages to build with a builder, e.g.
// in busybox mode or source mode or binary mode.
//
// See Builder for an explanation of build modes.
type Commands struct {
// Builder is the Go compiler mode.
Builder builder.Builder
// Packages are the Go packages to compile and add to the archive.
//
// Currently allowed formats:
// - Go package imports; e.g. github.com/u-root/u-root/cmds/ls
// - Globs of Go package imports; e.g. github.com/u-root/u-root/cmds/*
// - Paths to Go package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
// - Globs of paths to Go package directories; e.g. ./cmds/*
Packages []string
// BinaryDir is the directory in which the resulting binaries are
// placed inside the initramfs.
BinaryDir string
}
// TargetDir returns the initramfs binary directory for these Commands.
func (c Commands) TargetDir() string {
if len(c.BinaryDir) != 0 {
return c.BinaryDir
}
return c.Builder.DefaultBinaryDir()
}
// Opts are the arguments to CreateInitramfs.
//
// Opts contains everything that influences initramfs creation such as the Go
// build environment.
//
//
type Opts struct {
// Env is the Golang build environment (GOOS, GOARCH, etc).
Env golang.Environ
// Commands specify packages to build using a specific builder.
Commands []Commands
// TempDir is a temporary directory for builders to store files in.
TempDir string
// ExtraFiles are files to add to the archive in addition to the Go
// packages.
//
// Shared library dependencies will automatically also be added to the
// archive using ldd.
ExtraFiles []string
// OutputFile is the archive output file.
OutputFile initramfs.Writer
// BaseArchive is an existing initramfs to include in the resulting
// initramfs.
BaseArchive initramfs.Reader
// UseExistingInit determines whether the existing init from
// BaseArchive should be used.
//
// If this is false, the "init" from BaseArchive will be renamed to
// "inito".
UseExistingInit bool
// InitCmd is the name of a command to link /init to.
//
// This can be an absolute path or the name of a command included in
// Commands.
//
// If this is empty, no init symlink will be created.
InitCmd string
// DefaultShell is the default shell to start after init.
//
// This can be an absolute path or the name of a command included in
// Commands.
//
// This must be specified to have a default shell.
DefaultShell string
}
// CreateInitramfs creates an initramfs built to opts' specifications.
func CreateInitramfs(opts Opts) error {
if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) {
return fmt.Errorf("temp dir %q must exist: %v", opts.TempDir, err)
}
if opts.OutputFile == nil {
return fmt.Errorf("must give output file")
}
files := initramfs.NewFiles()
// Expand commands.
for index, cmds := range opts.Commands {
importPaths, err := ResolvePackagePaths(opts.Env, cmds.Packages)
if err != nil {
return err
}
opts.Commands[index].Packages = importPaths
}
// Add each build mode's commands to the archive.
for _, cmds := range opts.Commands {
builderTmpDir, err := ioutil.TempDir(opts.TempDir, "builder")
if err != nil {
return err
}
// Build packages.
bOpts := builder.Opts{
Env: opts.Env,
Packages: cmds.Packages,
TempDir: builderTmpDir,
BinaryDir: cmds.TargetDir(),
}
if err := cmds.Builder.Build(files, bOpts); err != nil {
return fmt.Errorf("error building %#v: %v", bOpts, err)
}
}
// Open the target initramfs file.
archive := initramfs.Opts{
Files: files,
OutputFile: opts.OutputFile,
BaseArchive: opts.BaseArchive,
UseExistingInit: opts.UseExistingInit,
DefaultRecords: DefaultRamfs,
}
if len(opts.DefaultShell) > 0 {
if target, err := resolveCommandOrPath(opts.DefaultShell, opts.Commands); err != nil {
log.Printf("No default shell: %v", err)
} else if err := archive.AddRecord(cpio.Symlink("bin/defaultsh", target)); err != nil {
return err
}
}
if len(opts.InitCmd) > 0 {
if target, err := resolveCommandOrPath(opts.InitCmd, opts.Commands); err != nil {
return fmt.Errorf("could not find init: %v", err)
} else if err := archive.AddRecord(cpio.Symlink("init", target)); err != nil {
return err
}
}
if err := ParseExtraFiles(archive.Files, opts.ExtraFiles, true); err != nil {
return err
}
// Finally, write the archive.
if err := initramfs.Write(&archive); err != nil {
return fmt.Errorf("error archiving: %v", err)
}
return nil
}
// resolvePackagePath finds import paths for a single import path or directory string
func resolvePackagePath(env golang.Environ, pkg string) ([]string, error) {
// Search the current working directory, as well GOROOT and GOPATHs
prefixes := append([]string{""}, env.SrcDirs()...)
// Resolve file system paths to package import paths.
for _, prefix := range prefixes {
path := filepath.Join(prefix, pkg)
matches, err := filepath.Glob(path)
if len(matches) == 0 || err != nil {
continue
}
var importPaths []string
for _, match := range matches {
p, err := env.PackageByPath(match)
if err != nil {
log.Printf("Skipping package %q: %v", match, err)
} else if p.ImportPath == "." {
// TODO: I do not completely understand why
// this is triggered. This is only an issue
// while this function is run inside the
// process of a "go test".
importPaths = append(importPaths, pkg)
} else {
importPaths = append(importPaths, p.ImportPath)
}
}
return importPaths, nil
}
// No file import paths found. Check if pkg still resolves as a package name.
if _, err := env.Package(pkg); err != nil {
return nil, fmt.Errorf("%q is neither package or path/glob: %v", pkg, err)
}
return []string{pkg}, nil
}
func resolveCommandOrPath(cmd string, cmds []Commands) (string, error) {
if filepath.IsAbs(cmd) {
return cmd, nil
}
for _, c := range cmds {
for _, p := range c.Packages {
// Figure out which build mode the shell is in, and symlink to
// that build modee
if name := path.Base(p); name == cmd {
return path.Join("/", c.TargetDir(), cmd), nil
}
}
}
return "", fmt.Errorf("command or path %q not included in u-root build", cmd)
}
// ResolvePackagePaths takes a list of Go package import paths and directories
// and turns them into exclusively import paths.
//
// Currently allowed formats:
// Go package imports; e.g. github.com/u-root/u-root/cmds/ls
// Paths to Go package directories; e.g. $GOPATH/src/github.com/u-root/u-root/cmds/ls
// Globs of package imports, e.g. github.com/u-root/u-root/cmds/*
// Globs of paths to Go package directories; e.g. ./cmds/*
func ResolvePackagePaths(env golang.Environ, pkgs []string) ([]string, error) {
var importPaths []string
for _, pkg := range pkgs {
paths, err := resolvePackagePath(env, pkg)
if err != nil {
return nil, err
}
importPaths = append(importPaths, paths...)
}
return importPaths, nil
}
// ParseExtraFiles adds files from the extraFiles list to the archive.
//
// The following formats are allowed in the extraFiles list:
// - hostPath:archivePath adds the file from hostPath at the relative
// archivePath in the archive.
// - justAPath is added to the archive under justAPath.
//
// ParseExtraFiles will also add ldd-listed dependencies if lddDeps is true.
func ParseExtraFiles(archive initramfs.Files, extraFiles []string, lddDeps bool) error {
var err error
// Add files from command line.
for _, file := range extraFiles {
var src, dst string
parts := strings.SplitN(file, ":", 2)
if len(parts) == 2 {
// treat the entry with the new src:dst syntax
src = filepath.Clean(parts[0])
dst = filepath.Clean(parts[1])
} else {
// plain old syntax
// filepath.Clean interprets an empty string as CWD for no good reason.
if len(file) == 0 {
continue
}
src = filepath.Clean(file)
dst = src
if filepath.IsAbs(dst) {
dst, err = filepath.Rel("/", dst)
if err != nil {
return fmt.Errorf("cannot make path relative to /: %v: %v", dst, err)
}
}
}
src, err := filepath.Abs(src)
if err != nil {
return fmt.Errorf("couldn't find absolute path for %q: %v", src, err)
}
if err := archive.AddFile(src, dst); err != nil {
return fmt.Errorf("couldn't add %q to archive: %v", file, err)
}
if lddDeps {
// Pull dependencies in the case of binaries. If `path` is not
// a binary, `libs` will just be empty.
libs, err := ldd.List([]string{src})
if err != nil {
log.Printf("WARNING: couldn't add ldd dependencies for %q: %v", file, err)
return nil
}
for _, lib := range libs {
if err := archive.AddFile(lib, lib[1:]); err != nil {
log.Printf("WARNING: couldn't add ldd dependencies for %q: %v", lib, err)
}
}
}
}
return nil
}
// DefaultPackageImports returns a list of default u-root packages to include.
func DefaultPackageImports(env golang.Environ) ([]string, error) {
// Find u-root directory.
urootPkg, err := env.Package("github.com/u-root/u-root")
if err != nil {
return nil, fmt.Errorf("Couldn't find u-root src directory: %v", err)
}
matches, err := filepath.Glob(filepath.Join(urootPkg.Dir, "cmds/*"))
if err != nil {
return nil, fmt.Errorf("couldn't find u-root cmds: %v", err)
}
pkgs := make([]string, 0, len(matches))
for _, match := range matches {
pkg, err := env.PackageByPath(match)
if err == nil {
pkgs = append(pkgs, pkg.ImportPath)
}
}
return pkgs, nil
}