Repository: amenzhinsky/go-memexec Branch: main Commit: d27e26edbf40 Files: 13 Total size: 24.8 KB Directory structure: gitextract_rtw5rwam/ ├── .github/ │ └── workflows/ │ └── test.yml ├── LICENSE ├── README.md ├── cmd/ │ └── memexec-gen/ │ └── main.go ├── go.mod ├── go.sum ├── memexec.go ├── memexec_all.go ├── memexec_linux.go ├── memexec_linux_test.go ├── memexec_test.go └── testdata/ ├── .gitignore └── main.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/test.yml ================================================ name: Test and Lint on: push: branches: - main pull_request: branches: - main jobs: test: name: Test strategy: matrix: platform: - ubuntu-latest - macos-latest - windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v3 with: go-version: 1.19 - name: Run Tests run: go test -v ./... lint: name: Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v3 with: go-version: 1.19 - name: Run golangci-lint uses: golangci/golangci-lint-action@v3 with: version: v1.52.0 args: --enable=gofumpt,goimports,whitespace,gocritic,exportloopref,unconvert,prealloc ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # go-memexec Small library that executes binaries from the memory. ## Usage ## Static Binary Running static binaries is quite simple, it's only needed to embed it into the app and pass its content to `memexec.New`: ```go import ( _ "embed" "github.com/amenzhinsky/go-memexec" ) // go:embed path-to-binary var mybinary []byte exe, err := memexec.New(mybinary) if err != nil { return err } defer exe.Close() cmd := exe.Command(argv...) cmd.Output() // cmd is a `*exec.Cmd` from the standard library ``` ## Dynamic Binary (Linux only) With dynamic linked binaries things get more complicated, it's needed to embed all dependencies along with the executable. At the runtime deps are copied to a temp dir and executable receives the corresponding `LD_LIBRARY_PATH` that forces the dynamic linker to use the copied libraries. The dynamic linker must be the same on both building and running machines since it's not included in the resulting binary (there's no interoperability between musl and GNU systems). The following script helps generating packages, say `python3`: ```sh go install github.com/amenzhinsky/go-memexec/cmd/memexec-gen@latest PATH=$(go env GOPATH)/bin:$PATH memexec-gen /usr/bin/python3 ``` It produces `python3` directory with binaries are to embed and `gen.go` file, that is a go package: ```go import "mypackagename/python3" exe, err := python3.New() if err != nil { return err } defer exe.Close() b, err := exe.Command("-c", "print('Hello World')").CombinedOutput() if err != nil { return err } ``` ================================================ FILE: cmd/memexec-gen/main.go ================================================ //go:build linux package main import ( "debug/elf" "flag" "fmt" "io" "os" "path/filepath" "runtime" "strings" ) var ( destFlag string packageFlag string ) func main() { flag.Usage = func() { fmt.Fprint(os.Stderr, `Usage: memexec-gen PATH Environment variables: LD_LIBRARY_PATH list of directories where to search libraries, see 'man 7 ld.so' Options: `) flag.PrintDefaults() } flag.StringVar(&destFlag, "dest", "", "`path` where binaries and go file are written to, defaults to PATH basename", ) flag.StringVar(&packageFlag, "package", "", "generated package `name`, defaults to PATH basename", ) flag.Parse() if flag.NArg() != 1 { flag.Usage() os.Exit(2) } if err := run(flag.Arg(0)); err != nil { fmt.Fprintf(os.Stderr, "error: %s\n", err) os.Exit(127) } } func run(bin string) error { base := filepath.Base(bin) if destFlag == "" { destFlag = base } if packageFlag == "" { packageFlag = base } err := os.MkdirAll(destFlag, 0o755) if err != nil && !os.IsExist(err) { return err } output, err = os.OpenFile( filepath.Join(destFlag, "memexec.go"), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644, ) if err != nil { return err } libs := map[string]string{} if err := ldd(libs, bin, func(name string) (string, error) { return name, nil }); err != nil { return err } for name, path := range libs { src, err := os.Open(path) if err != nil { return err } if name == bin { name = base } dst, err := os.OpenFile( filepath.Join(destFlag, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755, ) if err != nil { return err } if _, err := io.Copy(dst, src); err != nil { return err } if err := dst.Close(); err != nil { return err } if err := src.Close(); err != nil { return err } } out("// Code generated by memexec-gen. DO NOT EDIT.") out("package ", packageFlag) out() out("import (") out(` _ "embed"`) out(` "os"`) out(` "os/exec"`) out(` "path/filepath"`) out() out(` "github.com/amenzhinsky/go-memexec"`) out(")") out() for name := range libs { if name == bin { name = base } out("//go:embed ", name) out("var ", goName(name), " []byte") out() } out("func New(opts ...memexec.Option) (*memexec.Exec, error) {") out(` temp, err := os.MkdirTemp("", "")`) out(" if err != nil {") out(" return nil, err") out(" }") for name := range libs { if name == bin { continue } out(` if err := os.WriteFile(filepath.Join(temp, "`, name, `"), `, goName(name), ", 0o755); err != nil {") out(" return nil, err") out(" }") } out(" return memexec.New(", goName(base), ", append([]memexec.Option{") out(" memexec.WithPrepare(func(exe *exec.Cmd) {") out(` exe.Env = append(exe.Env, "LD_LIBRARY_PATH="+temp)`) out(" }),") out(" memexec.WithCleanup(func() error {") out(" return os.RemoveAll(temp)") out(" }),") out(" }, opts...)...)") out("}") return nil } var output io.Writer func out(strs ...string) { for _, str := range strs { if _, err := fmt.Fprint(output, str); err != nil { panic(err) } } if _, err := fmt.Fprintln(output); err != nil { panic(err) } } func goName(name string) string { name = strings.ReplaceAll(name, ".", "_") name = strings.ReplaceAll(name, "-", "_") return "memexec_" + name } func ldd( deps map[string]string, name string, look func(name string) (string, error), ) error { path, err := look(name) if err != nil { return err } deps[name] = path e, err := elf.Open(path) if err != nil { return err } l, err := e.ImportedLibraries() if err != nil { return err } rpaths, err := e.DynString(elf.DT_RPATH) if err != nil { return err } runpaths, err := e.DynString(elf.DT_RUNPATH) if err != nil { return err } if err := e.Close(); err != nil { return err } for _, lib := range l { if _, ok := deps[lib]; ok { continue } if err := ldd(deps, lib, func(name string) (string, error) { return lookLibrary(name, rpaths, runpaths) }); err != nil { return err } } return nil } var ldPaths = []string{"/lib", "/usr/local/lib", "/usr/lib"} func init() { // TODO: os.ReadFile(fmt.Sprintf("/etc/ld-musl-$(ARCH).path")) switch runtime.GOARCH { case "amd64": ldPaths = append(ldPaths, "/lib64", "/usr/lib64", "/usr/local/lib/x86_64-linux-gnu", "/lib/x86_64-linux-gnu", "/usr/lib/x86_64-linux-gnu", ) case "arm64": ldPaths = append(ldPaths, "/usr/local/lib/aarch64-linux-gnu", "/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", ) } if s := os.Getenv("LD_LIBRARY_PATH"); s != "" { ldPaths = append(ldPaths, filepath.SplitList(s)...) } } func lookLibrary(name string, rpaths, runpaths []string) (string, error) { for _, dir := range append(rpaths, append(ldPaths, runpaths...)...) { path := filepath.Join(dir, name) stat, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { continue } return "", err } if !stat.IsDir() { return path, nil } } return "", fmt.Errorf("dynamic library %s not found", name) } ================================================ FILE: go.mod ================================================ module github.com/amenzhinsky/go-memexec go 1.19 require golang.org/x/sys v0.0.0-20210903071746-97244b99971b ================================================ FILE: go.sum ================================================ golang.org/x/sys v0.0.0-20210903071746-97244b99971b h1:3Dq0eVHn0uaQJmPO+/aYPI/fRMqdrVDbu7MQcku54gg= golang.org/x/sys v0.0.0-20210903071746-97244b99971b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= ================================================ FILE: memexec.go ================================================ package memexec import ( "context" "os" "os/exec" ) type Option func(e *Exec) // Exec is an in-memory executable code unit. type Exec struct { f *os.File opts []func(cmd *exec.Cmd) clean func() error } // WithPrepare configures cmd with default values such as Env, Dir, etc. func WithPrepare(fn func(cmd *exec.Cmd)) Option { return func(e *Exec) { e.opts = append(e.opts, fn) } } // WithCleanup is executed right after Exec.Close. func WithCleanup(fn func() error) Option { return func(e *Exec) { e.clean = fn } } // New creates new memory execution object that can be // used for executing commands on a memory based binary. func New(b []byte, opts ...Option) (*Exec, error) { f, err := open(b) if err != nil { return nil, err } e := &Exec{f: f} for _, opt := range opts { opt(e) } return e, nil } // Command is an equivalent of `exec.Command`, // except that the path to the executable is being omitted. func (m *Exec) Command(args ...string) *exec.Cmd { return m.CommandContext(context.Background(), args...) } // CommandContext is an equivalent of `exec.CommandContext`, // except that the path to the executable is being omitted. func (m *Exec) CommandContext(ctx context.Context, args ...string) *exec.Cmd { exe := exec.CommandContext(ctx, m.f.Name(), args...) for _, opt := range m.opts { opt(exe) } return exe } // Close closes Exec object. // // Any further command will fail, it's client's responsibility // to control the flow by using synchronization algorithms. func (m *Exec) Close() error { if err := clean(m.f); err != nil { if m.clean != nil { _ = m.clean() } return err } if m.clean == nil { return nil } return m.clean() } ================================================ FILE: memexec_all.go ================================================ //go:build !linux // +build !linux package memexec import ( "os" "runtime" ) func open(b []byte) (*os.File, error) { pattern := "go-memexec-" if runtime.GOOS == "windows" { pattern = "go-memexec-*.exe" } f, err := os.CreateTemp("", pattern) if err != nil { return nil, err } defer func() { if err != nil { _ = clean(f) } }() if err = os.Chmod(f.Name(), 0o500); err != nil { return nil, err } if _, err = f.Write(b); err != nil { return nil, err } if err = f.Close(); err != nil { return nil, err } return f, nil } func clean(f *os.File) error { return os.Remove(f.Name()) } ================================================ FILE: memexec_linux.go ================================================ //go:build linux // +build linux package memexec import ( "fmt" "os" "golang.org/x/sys/unix" ) func open(b []byte) (*os.File, error) { fd, err := unix.MemfdCreate("", unix.MFD_CLOEXEC) if err != nil { return nil, err } f := os.NewFile(uintptr(fd), fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), fd)) if _, err := f.Write(b); err != nil { _ = f.Close() return nil, err } return f, nil } func clean(f *os.File) error { return f.Close() } ================================================ FILE: memexec_linux_test.go ================================================ //go:build linux package memexec import ( "os/exec" "testing" ) func TestGenLinux(t *testing.T) { e := exec.Command("go", "run", "../cmd/memexec-gen", "/usr/bin/python3") e.Dir = "testdata" _ = runCommand(t, e) e = exec.Command("go", "run", ".", "-c", "print(42)") e.Dir = "testdata" if have := runCommand(t, e); have != "42" { t.Fatalf("output mismatch:\n\thave: %s\n\twant: %s", have, "42") } } ================================================ FILE: memexec_test.go ================================================ package memexec import ( "bytes" "context" "os" "os/exec" "runtime" "strings" "testing" "time" ) func TestCommand(t *testing.T) { exe := newEchoExec(t) defer func() { if err := exe.Close(); err != nil { t.Fatalf("close error: %s", err) } }() c := exe.Command("test") if have := runCommand(t, c); !strings.HasPrefix(have, "test") { t.Errorf("command output = %q doesn't contain %q", have, "test") } } func TestCommand_Shell(t *testing.T) { if runtime.GOOS == "windows" { return } exe, err := New([]byte("#!/bin/sh\necho hello")) if err != nil { panic(err) } defer exe.Close() b, err := exe.Command().CombinedOutput() if err != nil { t.Fatalf("err = %v, output = %q", err, b) } if !bytes.Equal(b, []byte("hello\n")) { t.Fatalf("output = %q, want %q", string(b), []byte("hello\n")) } } func TestCommandContext(t *testing.T) { // the test is failing on windows, probably due to missing sleep command, // unfortunately I have no windows machines around to fix this if runtime.GOOS == "windows" { return } exe := newSleepExec(t) defer func() { if err := exe.Close(); err != nil { t.Fatalf("close error: %s", err) } }() ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500) defer cancel() c := exe.CommandContext(ctx, "1") start := time.Now() if err := c.Start(); err != nil { t.Fatalf("start failed: %s", err) } if err := c.Wait(); err != nil && err.Error() != "signal: killed" { t.Fatalf("command execution failed: %s", err) } stop := time.Now() if delta := stop.Sub(start); delta > time.Millisecond*600 || delta < time.Millisecond*500 { t.Fatalf("unexpected command execution time: delta=%s", delta) } } func BenchmarkCommand(b *testing.B) { exe := newEchoExec(b) defer func() { if err := exe.Close(); err != nil { b.Fatalf("close error: %s", err) } }() for i := 0; i < b.N; i++ { cmd := exe.Command("test") if _, err := cmd.Output(); err != nil { b.Fatal(err) } } } func newExec(t testing.TB, name string) *Exec { path, err := exec.LookPath(name) if err != nil { t.Fatal(err) } b, err := os.ReadFile(path) if err != nil { t.Fatal(err) } exe, err := New(b) if err != nil { t.Fatal(err) } return exe } func newEchoExec(t testing.TB) *Exec { // lookup echo binary that is provided on all unix systems // and it's not a built-in opposed to `ls` and `type` return newExec(t, "echo") } func newSleepExec(t testing.TB) *Exec { return newExec(t, "sleep") } func runCommand(t *testing.T, cmd *exec.Cmd) string { t.Helper() b, err := cmd.CombinedOutput() if err != nil { if b != nil { t.Fatalf("failed to run: %q", string(b)) } t.Fatal(err) } return string(b) } ================================================ FILE: testdata/.gitignore ================================================ python3 ================================================ FILE: testdata/main.go ================================================ package main import ( "fmt" "os" "strings" "github.com/amenzhinsky/go-memexec/testdata/python3" ) func main() { exe, err := python3.New() if err != nil { panic(err) } c := exe.Command(os.Args[1:]...) c.Stdin = os.Stdin b, err := c.CombinedOutput() if err != nil { panic(err) } fmt.Print(strings.TrimSpace(string(b))) }