def first_entry_point(group, name=None):
    def __init__(self):
    def elapsed(self):
def s2ms(seconds):
def ms2s(miliseconds):
def ceil_ms2s(miliseconds):
    def __init__(self, fname):
    def __enter__(self):
    def __exit__(self, exc_type, exc_value, traceback):
def rmtree(path):
    def remove_readonly(fn, path, excinfo):
def tempcwd(path=None):
    def __init__(self, inner_directory=None):
    def __enter__(self):
    def __exit__(self, exc_type, exc_value, traceback):
def path_join_abs(base, subpath):
def replace_invalid_UTF(a_string):
    def default(self, obj):
def json_dumps(obj, **kwargs):
def decode_fields(fields):
    def _decode_decorator(func):
        def _wrapper(*args, **kwargs):
def null_ctx_manager():
    def dummy():
    def __init__(cls, class_name, bases, new_attrs):
    def __classinit__(cls):
    def __classinit__(cls):
        def find_superclass(cls):
class PerfTimer(object):
class Writable(object):
class TemporaryCwd(object):
class CompatibleJSONEncoder(json.JSONEncoder):
class ClassInitMeta(type):
class ClassInitBase(six.with_metaclass(ClassInitMeta, object)):
class RegisteredSubclassesBase(ClassInitBase): EXT = '.old_elf_loader'
def _get_unpatched_name(path):
def _patch_elf_loader(path): def get_sandbox(name):
    """Constructs a :class:`Sandbox` with the given ``name``.

    If a :class:`Sandbox` instance for the given ``name`` is already
    created, returns that instance.

    Only this function should be used to creating or getting
    :class:`Sandbox` instances.
    """
    return Sandbox._instance(name) def ceil_ms2s(miliseconds):
    """Returns first integer count of seconds not less that ``miliseconds``.

    >>> ceil_ms2s(1000)
    1
    >>> ceil_ms2s(1001)
    2
    """
    return int((miliseconds + 999) / 1000) def decode_fields(fields):
    def _decode_decorator(func):
        def _wrapper(*args, **kwargs):
            result_dict = func(*args, **kwargs)
            for field in fields:
                if not isinstance(result_dict[field], six.string_types):
                    result_dict[field] = result_dict[field].decode()
            return result_dict

        return _wrapper

    return _decode_decorator def ms2s(miliseconds):
    """Converts ``miliseconds`` to seconds and returns float.

    >>> '%.2f' % ms2s(1190)
    '1.19'
    """
    return miliseconds / 1000.0 def s2ms(seconds):
    """Converts ``seconds`` to miliseconds

    >>> s2ms(1.95)
    1950
    """
    return int(1000 * seconds) def path_join_abs(base, subpath):
    """Joins two absolute paths making ``subpath`` relative to ``base``.

    >>> import os.path
    >>> os.path.join('/usr', '/bin/sh')
    '/bin/sh'

    >>> path_join_abs('/usr', '/bin/sh')
    '/usr/bin/sh'
    """
    return os.path.join(base, subpath.strip(os.sep)) def null_ctx_manager():
    def dummy():
        yield

    return contextmanager(dummy)() def tempcwd(path=None):
    # Someone might call tempcwd twice, i.e. tempcwd(tempcwd('something'))
    # Do nothing in this case.
    if path is not None and os.path.isabs(path):
        return path
    d = threadlocal_dir.tmpdir
    if path:
        return os.path.join(d, path)
    else:
        return d
import os
import subprocess
import tempfile
import signal
import logging
import re
import sys
import traceback
import six
from threading import Timer
from os import path
from sio.workers import util, elf_loader_patch
from sio.workers.sandbox import get_sandbox
from sio.workers.util import (
    ceil_ms2s,
    decode_fields,
    ms2s,
    s2ms,
    path_join_abs,
    null_ctx_manager,
    tempcwd,
)
from six.moves import map
        else:
            raise RuntimeError(
                'Could not find output of time program. ' 'Captured output: %s' % output
            )

        if (
            kwargs['time_limit'] is not None
            and renv['time_used'] >= 0.95 * kwargs['time_limit']
        ):
            renv['result_string'] = 'time limit exceeded'
            renv['result_code'] = 'TLE'
        elif 'real_time_killed' in renv:
            renv['result_string'] = 'real time limit exceeded'
            renv['result_code'] = 'TLE'
        elif renv['return_code'] == 0:
            renv['result_string'] = 'ok'
            renv['result_code'] = 'OK'
        elif renv['return_code'] > 128:  # os.WIFSIGNALED(1) returns True
            renv['result_string'] = 'program exited due to signal %d' % os.WTERMSIG(
                renv['return_code']
            )
            renv['result_code'] = 'RE'
        else:
            renv['result_string'] = 'program exited with code %d' % renv['return_code']
            renv['result_code'] = 'RE'

        renv['mem_used'] = 0
        renv['num_syscalls'] = 0

        return renv


class SandboxExecutor(UnprotectedExecutor):
    """SandboxedExecutor is intended to run programs delivered in ``sandbox`` package.

    This executor accepts following extra arguments in ``__call__``:
       ``use_path`` If false (default) and first argument of command is
                    relative then it's prepended with sandbox path.

     .. note:: Sandbox does not mean isolation, it's just part of filesytem.

     ..
    """

    def __enter__(self):
        self.sandbox.__enter__()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.sandbox.__exit__(exc_type, exc_value, traceback)

    def __init__(self, sandbox):
        """``sandbox`` has to be a sandbox name."""
        self.sandbox = get_sandbox(sandbox)

    def __str__(self):
        return 'SandboxExecutor(%s)' % (self.sandbox,)

    @property
    def rpath(self):
        """Contains path to sandbox root as visible during command execution."""
        return self.sandbox.path

    @property
    def path(self):
        """Contains real, absolute path to sandbox root."""
        return self.sandbox.path

    def _env_paths(self, suffix):
        return "%s:%s" % (
            path.join(self.path, suffix),
            path.join(self.path, 'usr', suffix),
        )

    def _execute(self, command, **kwargs):
        if not kwargs.get('use_path', False) and command[0][0] != '/':
            command[0] = os.path.join(self.path, command[0])

        env = kwargs.get('env')
        env['PATH'] = '%s:%s' % (self._env_paths('bin'), env['PATH'])

        if not self.sandbox.has_fixup('elf_loader_patch'):
            env['LD_LIBRARY_PATH'] = self._env_paths('lib')

        return super(SandboxExecutor, self)._execute(command, **kwargs)


class _SIOSupervisedExecutor(SandboxExecutor):
    _supervisor_codes = {
        0: 'OK',
        120: 'OLE',
        121: 'RV',
        124: 'MLE',
        125: 'TLE',
    }

    def __init__(self, sandbox_name):
        super(_SIOSupervisedExecutor, self).__init__(sandbox_name)

    def _supervisor_result_to_code(self, result):
        return self._supervisor_codes.get(int(result), 'RE')

    @decode_fields(['result_string'])
    def _execute(self, command, **kwargs):
        env = kwargs.get('env')
        env.update(
            {
                'MEM_LIMIT': kwargs['mem_limit'] or 64 * 2 ** 10,
                'TIME_LIMIT': kwargs['time_limit'] or 30000,
                'OUT_LIMIT': kwargs['output_limit'] or 50 * 2 ** 20,
            }
        )

        if kwargs['real_time_limit']:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(kwargs['real_time_limit'])
        elif kwargs['time_limit'] and kwargs['real_time_limit'] is None:
            env['HARD_LIMIT'] = 1 + ceil_ms2s(64 * kwargs['time_limit'])

        if 'HARD_LIMIT' in env:
            # Limiting outside supervisor

            kwargs['real_time_limit'] = 2 * s2ms(env['HARD_LIMIT'])