Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bbmain to correctly handle #! files #51

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ templates:
(cd test/requestconflict/mod6 && go build ./...)
(cd test/nested && go build ./...)
(cd test/nested/nestedmod && go build ./...)
(cd test/invoke/mod && go build ./...)
- run:
name: tests
command: ./gobuilds.sh
Expand Down Expand Up @@ -305,6 +306,7 @@ jobs:
(cd test/requestconflict/mod6 && go mod tidy && go mod verify)
(cd test/nested && go mod tidy && go mod verify)
(cd test/nested/nestedmod && go mod tidy && go mod verify)
(cd test/invoke/mod && go mod tidy && go mod verify)
git status
if [[ -n "$(git status --porcelain .)" ]]; then
echo 'go.mod/go.sum is out-of-date: run `go mod tidy` in the right module directories (see git status) and then check in the changes'
Expand All @@ -328,6 +330,7 @@ jobs:
(cd test/requestconflict/mod6 && go vet ./...)
(cd test/nested && go vet ./...)
(cd test/nested/nestedmod && go vet ./...)
(cd test/invoke/mod && go vet ./...)
- run:
name: gofmt
command: |
Expand Down
8 changes: 5 additions & 3 deletions gobuilds.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ set -eux

# This one hasn't been migrated to the go test yet.
(cd ./test/requestconflict && ./test.sh)

(cd ./src/cmd/makebb && GO111MODULE=on go build .)
(cd ./test && go test --makebb=../src/cmd/makebb/makebb -v)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests are not shell files anymore, they're now a Go test in ./test directory -- add your new kind of test there instead of as a shell file

(cd ./test/nested && ./test.sh)
(cd ./test/implicitimport && ./test.sh)
(cd ./test/nameconflict && ./test.sh)
(cd ./test/12-fancy-cmd && ./test.sh)
(cd ./test/invoke && ./test.sh)
74 changes: 74 additions & 0 deletions src/pkg/bb/bbmain/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,77 @@ func main() {

run()
}

// A gobusybox has 3 possible ways of invocation:
//
// ## Direct
//
// ./bb ls -l
//
// For the gobusybox, argv in this case is ["./bb", "ls", "-l"] on all OS.
//
//
// ## Symlink
//
// ln -s bb ls
// ./ls
//
// For the gobusybox, argv in this case is ["./ls"] on all OS.
//
//
// ## Interpreted
//
// This way exists because Plan 9 does not have symlinks. Some Linux file
// system such as VFAT also do not support symlinks.
//
// echo "#!/bin/bb #!gobb!#" >> /tmp/ls
// /tmp/ls
//
// For the gobusybox, argv depends on the OS:
//
// Plan 9: ["ls", "#!gobb!#", "/tmp/ls"]
// Linux/Unix: ["/bin/bb", "#!gobb!#", "/tmp/ls"]
//
// Unix and Plan 9 evaluate arguments in a #! file differently, and, further,
// invoke the arguments in a different way.
//
// (1) The absolute path for /bin/bb is required, else Linux will throw an
// error as bb is not in the list of allowed interpreters.
//
// (2) On Plan 9, the arguments following the interpreter are tokenized (split
// on space) and on Linux, they are not. That means we should restrict
// ourselves to only ever using one argument in the she-bang line (#!).
//
// (3) Which gobusybox tool to use is always in argv[2].
//
// (4) Because of the differences in how arguments are presented to #! on
// different kernels, there should be a reasonably unique magic value so
// that bb can have confidence that it is running as an interpreter, rather
// than on the command-line in direct mode.
//
// The code needs to change the arguments to look like an exec: ["/tmp/ls", ...]
//
// In each case, the second arg must be "#!gobb!#", which is extremely
// unlikely to appear in any other context (save testing files, of course).
//
// The result is that the kernel, given a path to a #!gobb#! file, will
// read that file, then exec bin with the argument from argv[2] and any
// additional arguments from the exec.
func init() {
// Interpreted mode: If this has been run from a #!gobb!# file, it
// will have at least 3 args, and os.Args needs to be reconstructed.
if len(os.Args) > 2 && os.Args[1] == "#!gobb!#" {
os.Args = os.Args[2:]
}

m := func() {
if len(os.Args) == 1 {
log.Fatalf("Invalid busybox command: %q", os.Args)
}
// Use argv[1] as the name.
os.Args = os.Args[1:]
run()
}
bbmain.Register("bbdiagnose", bbmain.Noop, bbmain.ListCmds)
bbmain.RegisterDefault(bbmain.Noop, m)
}
2 changes: 1 addition & 1 deletion src/pkg/bb/bbmain_src.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package bb

var bbMainSource = []byte("// Copyright 2018 the u-root Authors. All rights reserved\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Package main is the busybox main.go template.\npackage main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/u-root/gobusybox/src/pkg/bb/bbmain\"\n\t// There MUST NOT be any other dependencies here.\n\t//\n\t// It is preferred to copy minimal code necessary into this file, as\n\t// dependency management for this main file is... hard.\n)\n\n// AbsSymlink returns an absolute path for the link from a file to a target.\nfunc AbsSymlink(originalFile, target string) string {\n\tif !filepath.IsAbs(originalFile) {\n\t\tvar err error\n\t\toriginalFile, err = filepath.Abs(originalFile)\n\t\tif err != nil {\n\t\t\t// This should not happen on Unix systems, or you're\n\t\t\t// already royally screwed.\n\t\t\tlog.Fatalf(\"could not determine absolute path for %v: %v\", originalFile, err)\n\t\t}\n\t}\n\t// Relative symlinks are resolved relative to the original file's\n\t// parent directory.\n\t//\n\t// E.g. /bin/defaultsh -> ../bbin/elvish\n\tif !filepath.IsAbs(target) {\n\t\treturn filepath.Join(filepath.Dir(originalFile), target)\n\t}\n\treturn target\n}\n\n// IsTargetSymlink returns true if a target of a symlink is also a symlink.\nfunc IsTargetSymlink(originalFile, target string) bool {\n\ts, err := os.Lstat(AbsSymlink(originalFile, target))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn (s.Mode() & os.ModeSymlink) == os.ModeSymlink\n}\n\n// ResolveUntilLastSymlink resolves until the last symlink.\n//\n// This is needed when we have a chain of symlinks and want the last\n// symlink, not the file pointed to (which is why we don't use\n// filepath.EvalSymlinks)\n//\n// I.e.\n//\n// /foo/bar -> ../baz/foo\n// /baz/foo -> bla\n//\n// ResolveUntilLastSymlink(/foo/bar) returns /baz/foo.\nfunc ResolveUntilLastSymlink(p string) string {\n\tfor target, err := os.Readlink(p); err == nil && IsTargetSymlink(p, target); target, err = os.Readlink(p) {\n\t\tp = AbsSymlink(p, target)\n\t}\n\treturn p\n}\n\nfunc run() {\n\tname := filepath.Base(os.Args[0])\n\terr := bbmain.Run(name)\n\tif errors.Is(err, bbmain.ErrNotRegistered) {\n\t\tif len(os.Args) > 1 {\n\t\t\tos.Args = os.Args[1:]\n\t\t\terr = bbmain.Run(filepath.Base(os.Args[0]))\n\t\t}\n\t}\n\tif errors.Is(err, bbmain.ErrNotRegistered) {\n\t\tlog.SetFlags(0)\n\t\tlog.Printf(\"Failed to run command: %v\", err)\n\n\t\tlog.Printf(\"Supported commands are:\")\n\t\tfor _, cmd := range bbmain.ListCmds() {\n\t\t\tlog.Printf(\" - %s\", cmd)\n\t\t}\n\t\tos.Exit(1)\n\t} else if err != nil {\n\t\tlog.SetFlags(0)\n\t\tlog.Fatalf(\"Failed to run command: %v\", err)\n\t}\n}\n\nfunc main() {\n\tos.Args[0] = ResolveUntilLastSymlink(os.Args[0])\n\n\trun()\n}\n")
var bbMainSource = []byte("// Copyright 2018 the u-root Authors. All rights reserved\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Package main is the busybox main.go template.\npackage main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/u-root/gobusybox/src/pkg/bb/bbmain\"\n\t// There MUST NOT be any other dependencies here.\n\t//\n\t// It is preferred to copy minimal code necessary into this file, as\n\t// dependency management for this main file is... hard.\n)\n\n// AbsSymlink returns an absolute path for the link from a file to a target.\nfunc AbsSymlink(originalFile, target string) string {\n\tif !filepath.IsAbs(originalFile) {\n\t\tvar err error\n\t\toriginalFile, err = filepath.Abs(originalFile)\n\t\tif err != nil {\n\t\t\t// This should not happen on Unix systems, or you're\n\t\t\t// already royally screwed.\n\t\t\tlog.Fatalf(\"could not determine absolute path for %v: %v\", originalFile, err)\n\t\t}\n\t}\n\t// Relative symlinks are resolved relative to the original file's\n\t// parent directory.\n\t//\n\t// E.g. /bin/defaultsh -> ../bbin/elvish\n\tif !filepath.IsAbs(target) {\n\t\treturn filepath.Join(filepath.Dir(originalFile), target)\n\t}\n\treturn target\n}\n\n// IsTargetSymlink returns true if a target of a symlink is also a symlink.\nfunc IsTargetSymlink(originalFile, target string) bool {\n\ts, err := os.Lstat(AbsSymlink(originalFile, target))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn (s.Mode() & os.ModeSymlink) == os.ModeSymlink\n}\n\n// ResolveUntilLastSymlink resolves until the last symlink.\n//\n// This is needed when we have a chain of symlinks and want the last\n// symlink, not the file pointed to (which is why we don't use\n// filepath.EvalSymlinks)\n//\n// I.e.\n//\n// /foo/bar -> ../baz/foo\n// /baz/foo -> bla\n//\n// ResolveUntilLastSymlink(/foo/bar) returns /baz/foo.\nfunc ResolveUntilLastSymlink(p string) string {\n\tfor target, err := os.Readlink(p); err == nil && IsTargetSymlink(p, target); target, err = os.Readlink(p) {\n\t\tp = AbsSymlink(p, target)\n\t}\n\treturn p\n}\n\nfunc run() {\n\tname := filepath.Base(os.Args[0])\n\terr := bbmain.Run(name)\n\tif errors.Is(err, bbmain.ErrNotRegistered) {\n\t\tif len(os.Args) > 1 {\n\t\t\tos.Args = os.Args[1:]\n\t\t\terr = bbmain.Run(filepath.Base(os.Args[0]))\n\t\t}\n\t}\n\tif errors.Is(err, bbmain.ErrNotRegistered) {\n\t\tlog.SetFlags(0)\n\t\tlog.Printf(\"Failed to run command: %v\", err)\n\n\t\tlog.Printf(\"Supported commands are:\")\n\t\tfor _, cmd := range bbmain.ListCmds() {\n\t\t\tlog.Printf(\" - %s\", cmd)\n\t\t}\n\t\tos.Exit(1)\n\t} else if err != nil {\n\t\tlog.SetFlags(0)\n\t\tlog.Fatalf(\"Failed to run command: %v\", err)\n\t}\n}\n\nfunc main() {\n\tos.Args[0] = ResolveUntilLastSymlink(os.Args[0])\n\n\trun()\n}\n\n// A gobusybox has 3 possible ways of invocation:\n//\n// ## Direct\n//\n// ./bb ls -l\n//\n// For the gobusybox, argv in this case is [\"./bb\", \"ls\", \"-l\"] on all OS.\n//\n//\n// ## Symlink\n//\n// ln -s bb ls\n// ./ls\n//\n// For the gobusybox, argv in this case is [\"./ls\"] on all OS.\n//\n//\n// ## Interpreted\n//\n// This way exists because Plan 9 does not have symlinks. Some Linux file\n// system such as VFAT also do not support symlinks.\n//\n// echo \"#!/bin/bb #!gobb!#\" >> /tmp/ls\n// /tmp/ls\n//\n// For the gobusybox, argv depends on the OS:\n//\n// Plan 9: [\"ls\", \"#!gobb!#\", \"/tmp/ls\"]\n// Linux/Unix: [\"/bin/bb\", \"#!gobb!#\", \"/tmp/ls\"]\n//\n// Unix and Plan 9 evaluate arguments in a #! file differently, and, further,\n// invoke the arguments in a different way.\n//\n// (1) The absolute path for /bin/bb is required, else Linux will throw an\n// error as bb is not in the list of allowed interpreters.\n//\n// (2) On Plan 9, the arguments following the interpreter are tokenized (split\n// on space) and on Linux, they are not. That means we should restrict\n// ourselves to only ever using one argument in the she-bang line (#!).\n//\n// (3) Which gobusybox tool to use is always in argv[2].\n//\n// (4) Because of the differences in how arguments are presented to #! on\n// different kernels, there should be a reasonably unique magic value so\n// that bb can have confidence that it is running as an interpreter, rather\n// than on the command-line in direct mode.\n//\n// The code needs to change the arguments to look like an exec: [\"/tmp/ls\", ...]\n//\n// In each case, the second arg must be \"#!gobb!#\", which is extremely\n// unlikely to appear in any other context (save testing files, of course).\n//\n// The result is that the kernel, given a path to a #!gobb#! file, will\n// read that file, then exec bin with the argument from argv[2] and any\n// additional arguments from the exec.\nfunc init() {\n\t// Interpreted mode: If this has been run from a #!gobb!# file, it\n\t// will have at least 3 args, and os.Args needs to be reconstructed.\n\tif len(os.Args) > 2 && os.Args[1] == \"#!gobb!#\" {\n\t\tos.Args = os.Args[2:]\n\t}\n\n\tm := func() {\n\t\tif len(os.Args) == 1 {\n\t\t\tlog.Fatalf(\"Invalid busybox command: %q\", os.Args)\n\t\t}\n\t\t// Use argv[1] as the name.\n\t\tos.Args = os.Args[1:]\n\t\trun()\n\t}\n\tbbmain.Register(\"bbdiagnose\", bbmain.Noop, bbmain.ListCmds)\n\tbbmain.RegisterDefault(bbmain.Noop, m)\n}\n")
5 changes: 5 additions & 0 deletions test/invoke/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/bb
/bb-on
/bb-auto
/bb2
/makebb
1 change: 1 addition & 0 deletions test/invoke/mod/cmd/helloworld/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
helloworld
9 changes: 9 additions & 0 deletions test/invoke/mod/cmd/helloworld/hello.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package main

import (
"fmt"
)

func main() {
fmt.Println("hello world")
}
3 changes: 3 additions & 0 deletions test/invoke/mod/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/u-root/gobusybox/test/invoke/mod

go 1.13
30 changes: 30 additions & 0 deletions test/invoke/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/bin/bash
set -eux

(cd ../../src/cmd/makebb && GO111MODULE=on go build .)
MAKEBB=../../src/cmd/makebb/makebb

for GO111MODULE in on auto;
do
GO111MODULE=$GO111MODULE $MAKEBB -o bb-$GO111MODULE ./mod/cmd/helloworld
test -f ./bb-$GO111MODULE

HW=$(./bb-$GO111MODULE helloworld);
test "$HW" == "hello world" || (echo "hello world not right: direct invocation failed" && exit 1)

ln -s bb-$GO111MODULE helloworld
HW=$(./helloworld)
test "$HW" == "hello world" || (echo "hello world not right: symlink invocation failed" && exit 1)
unlink helloworld

# add an interpreter file that contains #!/bin/bb #!gobb#!
echo "#!$(pwd)/bb-$GO111MODULE #!gobb!#" > helloworld
chmod +x helloworld
HW=$(./helloworld)
test "$HW" == "hello world" || (echo "hello world not right: interpreter invocation failed" && exit 1)
unlink helloworld
done

# check reproducible
cmp bb-on bb-auto
rm bb-on bb-auto