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
|
// Copyright (c) 2020-2022, Sylabs Inc. All rights reserved.
// Copyright (c) 2020, Control Command Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
//go:build singularity_engine
package unpacker
import (
"bufio"
"bytes"
"debug/elf"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/sylabs/singularity/v4/internal/pkg/buildcfg"
"github.com/sylabs/singularity/v4/pkg/sylog"
)
func init() {
cmdFunc = unsquashfsSandboxCmd
}
// libBind represents a library bind mount required by an elf binary
// that will be run in a contained minimal filesystem.
type libBind struct {
// source is the path to bind from, on the host.
source string
// dest is the path to bind to, inside the minimal filesystem.
dest string
}
// getLibraryBinds returns the library bind mounts required by an elf binary.
// The binary path must be absolute.
func getLibraryBinds(binary string) ([]libBind, error) {
exe, err := elf.Open(binary)
if err != nil {
return nil, err
}
defer exe.Close()
interp := ""
// look for the interpreter
for _, p := range exe.Progs {
if p.Type != elf.PT_INTERP {
continue
}
buf := make([]byte, 4096)
n, err := p.ReadAt(buf, 0)
if err != nil && err != io.EOF {
return nil, err
} else if n > cap(buf) {
return nil, fmt.Errorf("buffer too small to store interpreter")
}
// trim null byte to avoid an execution failure with
// an invalid argument error
interp = string(bytes.Trim(buf, "\x00"))
}
// this is a static binary, nothing to do
if interp == "" {
return []libBind{}, nil
}
// run interpreter to list library dependencies for the
// corresponding binary, eg:
// /lib64/ld-linux-x86-64.so.2 --list <program>
// /lib/ld-musl-x86_64.so.1 --list <program>
errBuf := new(bytes.Buffer)
buf := new(bytes.Buffer)
cmd := exec.Command(interp, "--list", binary)
cmd.Stdout = buf
cmd.Stderr = errBuf
// set an empty environment as LD_LIBRARY_PATH
// may mix dependencies, just rely only on the library
// cache or its own lookup mechanism, see issue:
// https://github.com/hpcng/singularity/issues/5666
cmd.Env = []string{}
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("while getting library dependencies: %s\n%s", err, errBuf.String())
}
return parseLibraryBinds(buf)
}
// parseLibrary binds parses `ld-linux-x86-64.so.2 --list <binary>` output.
// Returns a list of source->dest bind mounts required to run the binary
// in a minimal contained filesystem.
func parseLibraryBinds(buf io.Reader) ([]libBind, error) {
libs := make([]libBind, 0)
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 2 {
continue
}
// /lib64/ld64.so.2 (0x00007fff96c60000)
// Absolute path in 1st field - bind directly dest=source
if filepath.IsAbs(fields[0]) {
libs = append(libs, libBind{
source: fields[0],
dest: fields[0],
})
continue
}
// libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fff96a20000)
// .. or with glibc-hwcaps ..
// libpthread.so.0 => /lib64/glibc-hwcaps/power9/libpthread-2.28.so (0x00007fff96a20000)
//
// Bind resolved lib to same dir, but with .so filename from 1st field.
// e.g. source is: /lib64/glibc-hwcaps/power9/libpthread-2.28.so
// dest is : /lib64/glibc-hwcaps/power9/libpthread.so.0
if len(fields) >= 3 && fields[1] == "=>" && filepath.IsAbs(fields[2]) {
destDir := filepath.Dir(fields[2])
dest := filepath.Join(destDir, fields[0])
libs = append(libs, libBind{
source: fields[2],
dest: dest,
})
}
// linux-vdso64.so.1 (0x00007fff96c40000)
// linux-vdso64.so.1 => (0x00007fff96c40000)
// .. or anything else
// No absolute path = nothing to bind
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("while parsing library dependencies: %v", err)
}
return libs, nil
}
// unsquashfsSandboxCmd is the command instance for executing unsquashfs command
// in a sandboxed environment with singularity.
func unsquashfsSandboxCmd(unsquashfs string, dest string, filename string, filter string, opts ...string) (*exec.Cmd, error) {
const (
// will contain both dest and filename inside the sandbox
rootfsImageDir = "/image"
)
// create the sandbox temporary directory
tmpdir := filepath.Dir(dest)
rootfs, err := os.MkdirTemp(tmpdir, "tmp-rootfs-")
if err != nil {
return nil, fmt.Errorf("failed to create chroot directory: %s", err)
}
overwrite := false
// remove the destination directory if any, if the directory is
// not empty (typically during image build), the unsafe option -f is
// set, this is unfortunately required by image build
if err := os.Remove(dest); err != nil && !os.IsNotExist(err) {
if !os.IsExist(err) {
return nil, fmt.Errorf("failed to remove %s: %s", dest, err)
}
overwrite = true
}
// map destination into the sandbox
rootfsDest := filepath.Join(rootfsImageDir, filepath.Base(dest))
// sandbox required directories
rootfsDirs := []string{
// unsquashfs get available CPU from /sys/devices/system/cpu/online
filepath.Join(rootfs, "/sys"),
filepath.Join(rootfs, "/dev"),
filepath.Join(rootfs, rootfsImageDir),
}
for _, d := range rootfsDirs {
if err := os.Mkdir(d, 0o700); err != nil {
return nil, fmt.Errorf("while creating %s: %s", d, err)
}
}
// the decision to use user namespace is left to singularity
// which will detect automatically depending of the configuration
// what workflow it could use
args := []string{
"exec",
"--no-home",
"--no-nv",
"--no-rocm",
"-C",
"--no-init",
"--writable",
"-B", fmt.Sprintf("%s:%s", tmpdir, rootfsImageDir),
}
if filename != stdinFile {
filename = filepath.Join(rootfsImageDir, filepath.Base(filename))
}
roFiles := []string{
unsquashfs,
}
// get the library dependencies of unsquashfs
libs, err := getLibraryBinds(unsquashfs)
if err != nil {
return nil, err
}
// Handle binding of files
for _, b := range roFiles {
// Ensure parent dir and file exist in container
rootfsFile := filepath.Join(rootfs, b)
rootfsDir := filepath.Dir(rootfsFile)
if err := os.MkdirAll(rootfsDir, 0o700); err != nil {
return nil, fmt.Errorf("while creating %s: %s", rootfsDir, err)
}
if err := os.WriteFile(rootfsFile, []byte(""), 0o600); err != nil {
return nil, fmt.Errorf("while creating %s: %s", rootfsFile, err)
}
// Simple read-only bind, dest in container same as source on host
args = append(args, "-B", fmt.Sprintf("%s:%s:ro", b, b))
}
// Handle binding of libs and generate LD_LIBRARY_PATH
libraryPath := make([]string, 0)
for _, l := range libs {
// Ensure parent dir and file exist in container
rootfsFile := filepath.Join(rootfs, l.dest)
rootfsDir := filepath.Dir(rootfsFile)
if err := os.MkdirAll(rootfsDir, 0o700); err != nil {
return nil, fmt.Errorf("while creating %s: %s", rootfsDir, err)
}
if err := os.WriteFile(rootfsFile, []byte(""), 0o600); err != nil {
return nil, fmt.Errorf("while creating %s: %s", rootfsFile, err)
}
// Read only bind, dest in container may not match source on host due
// to .so symlinking (see getLibraryBinds comments).
args = append(args, "-B", fmt.Sprintf("%s:%s:ro", l.source, l.dest))
// If dir of lib not already in the LD_LIBRARY_PATH, add it.
has := false
libraryDir := filepath.Dir(l.dest)
for _, lp := range libraryPath {
if lp == libraryDir {
has = true
break
}
}
if !has {
libraryPath = append(libraryPath, libraryDir)
}
}
// singularity sandbox
args = append(args, rootfs)
// unsquashfs execution arguments
args = append(args, unsquashfs)
args = append(args, opts...)
if overwrite {
args = append(args, "-f")
}
args = append(args, "-d", rootfsDest, filename)
if filter != "" {
args = append(args, filter)
}
sylog.Debugf("Calling wrapped unsquashfs: singularity %v", args)
cmd := exec.Command(filepath.Join(buildcfg.BINDIR, "singularity"), args...)
cmd.Dir = "/"
cmd.Env = []string{
fmt.Sprintf("SINGULARITYENV_LD_LIBRARY_PATH=%s", strings.Join(libraryPath, string(os.PathListSeparator))),
fmt.Sprintf("SINGULARITY_DEBUG=%s", os.Getenv("SINGULARITY_DEBUG")),
}
return cmd, nil
}
|