1#!/usr/bin/env python3
2import sys
3import os
4import subprocess
5import resource
6
7env = os.environ.copy()
8args = sys.argv[1:]
9targettype = args.pop(0)
10
11if targettype == "user":
12    qemuargs = os.environ.get("QEMU_OPTIONS", "").split()
13    if not os.path.exists(qemuargs[0]):
14        # ensure qemu args has a valid absolute path
15        for i in os.environ.get("PATH", "").split(":"):
16            if os.path.exists(os.path.join(i, qemuargs[0])):
17                qemuargs[0] = os.path.join(i, qemuargs[0])
18                break
19    sysroot = os.environ.get("QEMU_SYSROOT", None)
20    if not sysroot:
21        sys.exit(-1)
22    libpaths = [sysroot + "/usr/lib", sysroot + "/lib"]
23
24    if args[0] == "env":
25        args.pop(0)
26        if len(args) == 0:
27            args = ["env"]
28        else:
29            # process options
30            while args[0].startswith("-"):
31                opt = args.pop(0).lstrip("-")
32                if "i" in opt:
33                    env.clear()
34            # process environment vars
35            while "=" in args[0]:
36                key, val = args.pop(0).split("=", 1)
37                if key == "LD_LIBRARY_PATH":
38                    libpaths += val.split(":")
39                else:
40                    env[key] = val
41    if args[0] == "cp":
42        # ignore copies, the filesystem is the same
43        sys.exit(0)
44
45    qemuargs += ["-L", sysroot]
46    qemuargs += ["-E", "LD_LIBRARY_PATH={}".format(":".join(libpaths))]
47    command = qemuargs + args
48
49    # We've seen qemu-arm using up all system memory for some glibc
50    # tests e.g. nptl/tst-pthread-timedlock-lockloop
51    # Cap at 8GB since no test should need more than that
52    # (5GB adds 7 failures for qemuarm glibc test run)
53    limit = 8*1024*1024*1024
54    resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
55
56elif targettype == "ssh":
57    host = os.environ.get("SSH_HOST", None)
58    user = os.environ.get("SSH_HOST_USER", None)
59    port = os.environ.get("SSH_HOST_PORT", None)
60
61    command = ["ssh", "-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no", "-o", "LogLevel=quiet"]
62    if port:
63        command += ["-p", str(port)]
64    if not host:
65        sys.exit(-1)
66    command += ["{}@{}".format(user, host) if user else host]
67
68    # wrap and replace quotes for correct transformation on ssh
69    wrapped = " ".join(["'{0}'".format(i.replace("'", r"'\''")) for i in ["cd", os.getcwd()]]) + "; "
70    wrapped += " ".join(["'{0}'".format(i.replace("'", r"'\''")) for i in args])
71    command += ["sh", "-c", "\"{}\"".format(wrapped)]
72else:
73    sys.exit(-1)
74
75try:
76    r = subprocess.run(command, timeout = 1800, env = env)
77    sys.exit(r.returncode)
78except subprocess.TimeoutExpired:
79    sys.exit(-1)
80
81