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