Пример #1
0
    def _compile(self, md, ars):
        mcp = md.Compile()
        smsg = mcp.get_name()
        try:
            cflgs = self._cpp_compiler_flags
            if cflgs is not None:
                if utils.is_windows():
                    mcp.set_cpp_compiler_flags("windows", cflgs)
                elif utils.is_linux():
                    mcp.set_cpp_compiler_flags("linux", cflgs)
                elif utils.is_mac():
                    mcp.set_cpp_compiler_flags("mac", cflgs)

            lflgs = self._linker_flags
            if lflgs is not None:
                if utils.is_windows():
                    mcp.set_linker_flags("windows", lflgs)
                elif utils.is_linux():
                    mcp.set_linker_flags("linux", lflgs)
                elif utils.is_mac():
                    mcp.set_linker_flags("mac", lflgs)

            mcp.run()
            smsg += " - OK!"
            ars.append(smsg)
        except Exception as e:
            smsg += " - ERROR: " + utils.exception_to_string(e)
            ars.append(smsg)
            raise e
    def __init__(self, reference_folder=None, screenshot_folder=None,
                 keyword_on_failure='ImageHorizonLibrary.Take A Screenshot'):
        '''ImageHorizonLibrary can be imported with several options.

        ``reference_folder`` is path to the folder where all reference images
        are stored. It must be a _valid absolute path_. As the library
        is suite-specific (ie. new instance is created for every suite),
        different suites can have different folders for it's reference images.

        ``screenshot_folder`` is path to the folder where screenshots are
        saved. If not given, screenshots are saved to the current working
        directory.

        ``keyword_on_failure`` is the keyword to be run, when location-related
        keywords fail. If you wish to not take screenshots, use for example
        `BuiltIn.No Operation`. Keyword must however be a valid keyword.
        '''

        self.reference_folder = reference_folder
        self.screenshot_folder = screenshot_folder
        self.keyword_on_failure = keyword_on_failure
        self.open_applications = OrderedDict()
        self.screenshot_counter = 1
        self.is_windows = utils.is_windows()
        self.is_mac = utils.is_mac()
        self.is_linux = utils.is_linux()
Пример #3
0
class TestRemoveSection(TestCase):
    def setUp(self):
        self.logger = logging.getLogger(__name__)
        self.tmp_dir = tempfile.mkdtemp(suffix='_lief_test_section')
        self.logger.debug("temp dir: {}".format(self.tmp_dir))

    @unittest.skipUnless(is_linux() and is_x86_64(), "requires Linux x86-64")
    @unittest.skipUnless(has_recent_glibc(), "Need a recent GLIBC version")
    def test_simple(self):
        sample_path = get_sample('ELF/ELF64_x86-64_binary_ls.bin')
        output = os.path.join(self.tmp_dir, "ls.section")

        ls = lief.parse(sample_path)
        ls.remove_section(".text", clear=False)
        ls.write(output)

        st = os.stat(output)
        os.chmod(output, st.st_mode | stat.S_IEXEC)

        p = Popen([output, "--help"],
                  stdout=subprocess.PIPE,
                  stderr=subprocess.STDOUT)
        stdout, _ = p.communicate()
        self.logger.debug(stdout.decode("utf8"))
        self.assertIsNotNone(re.search(r'GNU coreutils',
                                       stdout.decode("utf8")))

    def tearDown(self):
        # Delete it
        if os.path.isdir(self.tmp_dir):
            shutil.rmtree(self.tmp_dir)
Пример #4
0
 def __init__(self, agent_main):
     self._agent_main=agent_main
     if utils.is_windows():
         self._osnative = Windows(self._agent_main)
     elif utils.is_linux():
         self._osnative = Linux()
     elif utils.is_mac():
         self._osnative = Mac()
Пример #5
0
def log_environment_info():
    if utils.is_linux():
        logger.info("Xorg running:        %s" % test_utils.is_xorg_running())
    logger.info("Platform identifier: %s" % utils.platform_identifier)
    logger.info("Bare metal:          %s" % utils.is_bare_metal_system())
    logger.info("Running as user:     %s" % getpass.getuser())

    rawVersionInfo = dcgm_agent.dcgmVersionInfo()
    logger.info("Build info:          %s" % rawVersionInfo.rawBuildInfoString)
    logger.info("Mig:                 %s" % test_utils.is_mig_mode_enabled())
    logger.debug("ENV : %s" %
                 string.join(map(str, sorted(os.environ.items())), "\n"))
Пример #6
0
def initialize_sdk(fileName):
    
    sdk_executable = sdk_path + fileName
    
    if utils.is_linux():
        if os.path.exists(sdk_executable):
            # On linux, for binaries inside the package (not just commands in the path) test that they have +x
            # e.g. if package is extracted on windows and copied to Linux, the +x privileges will be lost
            assert os.access(sdk_executable, os.X_OK), \
                "SDK binary %s is not executable! Make sure that the testing archive has been correctly extracted." \
                % sdk_executable
    
    return subprocess.Popen( sdk_executable, stdout=PIPE, stdin=PIPE)
Пример #7
0
    def start(self, timeout=default_timeout):
        """
        Begin executing the application.
        The application may block if stdout/stderr buffers become full.
        This should be followed by self.terminate() or self.wait() to finish execution.
        Execution will be forcefully terminated if the timeout expires.
        If timeout is None, then this app will never timeout.
        """
        assert self._subprocess is None

        logger.debug("Starting " + str(self))
        
        env = self._create_subprocess_env()
        if utils.is_linux():
            if os.path.exists(self.executable):
                # On linux, for binaries inside the package (not just commands in the path) test that they have +x
                # e.g. if package is extracted on windows and copied to Linux, the +x privileges will be lost
                assert os.access(self.executable, os.X_OK), "Application binary %s is not executable! Make sure that the testing archive has been correctly extracted." % (self.executable)
        self.startTime = datetime.datetime.now()
        self._subprocess = subprocess.Popen(
                [self.executable] + self.args, 
                stdin=None, 
                stdout=subprocess.PIPE, 
                stderr=subprocess.PIPE,
                cwd=self.cwd,
                env=env)
        AppRunner._processes.append(self) # keep track of running processe
        # Start timeout if we want one
        self._timer = None
        if timeout is not None:
            self._timer = threading.Timer(timeout, self._trigger_timeout)
            self._timer.start()

        if not test_utils.noLogging:
            def args_to_fname(args):
                # crop each argument to 16 characters and make sure the output string is no longer than 50 chars
                # Long file names are hard to read (hard to find the extension of the file)
                # Also python sometimes complains about file names being too long.
                #   IOError: [Errno 36] File name too long
                return "_".join([utils.string_to_valid_file_name(x)[:16] for x in self.args])[:50]
            shortname = os.path.basename(self.executable) + "_" + args_to_fname(self.args)
            stdout_fname = os.path.relpath(os.path.join(
                logger.log_dir, "app_%03d_%s_stdout.txt" % (self.process_nb, shortname)))
            stderr_fname = os.path.relpath(os.path.join(
                logger.log_dir, "app_%03d_%s_stderr.txt" % (self.process_nb, shortname)))
            # If the app fails, this message will get printed. If it succeeds it'll get popped in _process_finish
            self._info_message = logger.info("Starting %s...\nstdout in %s\nstderr in %s" % (
                str(self)[:64], # cut the string to make it more readable
                stdout_fname, stderr_fname), defer=True)
            self._logfile_stdout = open(stdout_fname, "w", encoding='utf-8')
            self._logfile_stderr = open(stderr_fname, "w", encoding='utf-8')
Пример #8
0
class TestGOTPatch(TestCase):
    def setUp(self):
        self.logger = logging.getLogger(__name__)
        self.tmp_dir = tempfile.mkdtemp(suffix='_lief_test_466')
        self.logger.debug("temp dir: {}".format(self.tmp_dir))

    @unittest.skipUnless(is_linux() and is_x86_64(), "requires Linux x86-64")
    @unittest.skipUnless(has_recent_glibc(), "Need a recent GLIBC version")
    def test_freebl(self):
        libfreebl3_path = get_sample('ELF/ELF64_x86-64_library_libfreebl3.so')
        output_ls = os.path.join(self.tmp_dir, "ls.new")
        output_libfreebl3 = os.path.join(self.tmp_dir, "libfreebl3.so")

        libfreebl3 = lief.parse(libfreebl3_path)
        ls = lief.parse("/usr/bin/ls")

        if lief.ELF.DYNAMIC_TAGS.FLAGS_1 in ls and ls[
                lief.ELF.DYNAMIC_TAGS.FLAGS_1].has(
                    lief.ELF.DYNAMIC_FLAGS_1.PIE):
            ls[lief.ELF.DYNAMIC_TAGS.FLAGS_1].remove(
                lief.ELF.DYNAMIC_FLAGS_1.PIE)

        ls.add_library("libfreebl3.so")

        ls += lief.ELF.DynamicEntryRunPath("$ORIGIN")
        libfreebl3 += lief.ELF.DynamicEntryRunPath("$ORIGIN")

        ls.write(output_ls)
        libfreebl3.write(output_libfreebl3)

        st = os.stat(output_ls)
        os.chmod(output_ls, st.st_mode | stat.S_IEXEC)

        st = os.stat(output_libfreebl3)
        os.chmod(output_libfreebl3, st.st_mode | stat.S_IEXEC)

        p = Popen([output_ls, "--version"],
                  stdout=subprocess.PIPE,
                  stderr=subprocess.STDOUT)
        stdout, _ = p.communicate()
        self.logger.debug(stdout.decode("utf8"))
        self.assertIsNotNone(
            re.search(r'ls \(GNU coreutils\) ', stdout.decode("utf8")))
        self.assertEqual(p.returncode, 0)

    def tearDown(self):
        # Delete it
        if os.path.isdir(self.tmp_dir):
            shutil.rmtree(self.tmp_dir)
Пример #9
0
class TestEmptyGNUHash(TestCase):
    SYMBOLS = {
        "myinstance": 0x1159,
        "myinit": 0x1175,
        "mycalc": 0x1199,
        "mydelete": 0x1214,
    }

    def setUp(self):
        self.logger = logging.getLogger(__name__)
        self.tmp_dir = tempfile.mkdtemp(suffix='_lief_test_empty_gnu_hash')
        self.logger.debug("temp dir: {}".format(self.tmp_dir))

    @unittest.skipUnless(is_linux() and is_x86_64(), "requires Linux x86-64")
    @unittest.skipUnless(has_recent_glibc(), "Need a recent GLIBC version")
    def test_export(self):
        target_path = get_sample('ELF/ELF64_x86-64_binary_empty-gnu-hash.bin')
        output = os.path.join(self.tmp_dir, "libnoempty.so")

        binary = lief.parse(target_path)

        binary[lief.ELF.DYNAMIC_TAGS.FLAGS_1].remove(
            lief.ELF.DYNAMIC_FLAGS_1.PIE)

        for name, addr in TestEmptyGNUHash.SYMBOLS.items():
            binary.add_exported_function(addr, name)
        binary.write(output)

        st = os.stat(output)
        os.chmod(output, st.st_mode | stat.S_IEXEC)

        lib = ctypes.cdll.LoadLibrary(output)
        # Raise 'AttributeError' if not exported
        print(lib.myinstance)
        self.assertIsNotNone(lib.myinstance)

    def tearDown(self):
        # Delete it
        if os.path.isdir(self.tmp_dir):
            shutil.rmtree(self.tmp_dir)
Пример #10
0
OUTPUT_MOVIE_FORMAT = '.mp4'

POINT2_TAG = 'point2'
POINT3_TAG = 'point3'
LINE2_TAG = 'line2'
LINE3_TAG = 'line3'
GRID2_TAG = 'grid2'
GRID3_TAG = 'grid3'
ISO_TAG = 'iso'
X_TAG = 'x'
Y_TAG = 'y'
Z_TAG = 'z'

video_writer = 'ffmpeg'
video_extra_args = ['-vcodec', 'libx264', '-pix_fmt', 'yuv420p']
if utils.is_linux():
    video_writer = 'mencoder'
    video_extra_args = []

def remove_ext(filename):
    return filename[:-len(INPUT_ARRAY_FORMAT)]

def parse_tags(filename):
    tokens = remove_ext(filename).split('#')
    if len(tokens) > 1:
        return tokens[1].split(',')
    else:
        return []

def is_animation(tags):
    for tag in tags: