bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def action(self, discriminator, callable=None, args=(), kw=None, order=0): """ Register an action which will be executed when :meth:`pyramid.config.Configuration.commit` is called (or executed immediately if ``autocommit`` is ``True``).
def action(self, discriminator, callable=None, args=(), kw=None, order=0): """ Register an action which will be executed when :meth:`pyramid.config.Configuration.commit` is called (or executed immediately if ``autocommit`` is ``True``).
476,900
def commit(self): """ Commit any pending configuration actions added. If a configuration conflict has occurred, this method will raise a :exc:`ConfigurationConflictError`; within the traceback of this error will be information about the source of the conflict, usually including file names and line numbers of the cause of the configuration conflicts.""" if self._ctx is None: return self._ctx.execute_actions() # unwrap and reset the context self._ctx = None
def commit(self): """ Commit any pending configuration actions. If a configuration conflict is detected in the pending configuration actins, this method will raise a :exc:`ConfigurationConflictError`; within the traceback of this error will be information about the source of the conflict, usually including file names and line numbers of the cause of the configuration conflicts.""" if self._ctx is None: return self._ctx.execute_actions() # unwrap and reset the context self._ctx = None
476,901
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
476,902
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
476,903
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
476,904
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
def main(global_config, **settings): config = Configurator() config.include('myapp.myconfig.configure')
476,905
def test_spec_notyetregistered(self): import os from pyramid import tests module_name = tests.__name__ relpath = 'test_renderers.py' renderer = {} factory = DummyFactory(renderer) spec = '%s:%s' % (module_name, relpath) info = DummyRendererInfo({ 'name':spec, 'package':None, 'registry':self.config.registry, 'settings':{}, 'type':'type', }) result = self._callFUT(info, factory) self.failUnless(result is renderer) path = os.path.abspath(__file__) if path.endswith('pyc'): # pragma: no cover path = path[:-1] self.assertEqual(factory.path, path) self.assertEqual(factory.kw, {})
def test_spec_notyetregistered(self): import os from pyramid import tests module_name = tests.__name__ relpath = 'test_renderers.py' renderer = {} factory = DummyFactory(renderer) spec = '%s:%s' % (module_name, relpath) info = DummyRendererInfo({ 'name':spec, 'package':None, 'registry':self.config.registry, 'settings':{}, 'type':'type', }) result = self._callFUT(info, factory) self.failUnless(result is renderer) path = os.path.abspath(__file__) if path.endswith('pyc'): # pragma: no cover path = path[:-1] self.assertEqual(factory.path, path) self.assertEqual(factory.kw, {})
476,906
def get_app(config_file, name, loadapp=loadapp): """ Return the WSGI application named ``name`` in the PasteDeploy config file ``config_file``""" config_name = 'config:%s' % config_file here_dir = os.getcwd() app = loadapp(config_name, name=name, relative_to=here_dir) return app
def get_app(config_file, name, loadapp=loadapp): """ Return the WSGI application named ``name`` in the PasteDeploy config file ``config_file``""" config_name = 'config:%s' % config_file here_dir = os.getcwd() app = loadapp(config_name, name=name, relative_to=here_dir) return app
476,907
def route_path(route_name, request, *elements, **kw): """Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a named :app:`Pyramid` :term:`route configuration`. .. note:: Calling :meth:`pyramid.Request.route_path` can be used to achieve the same result as :func:`pyramid.url.route_path`. This function accepts the same argument as :func:`pyramid.url.route_url` and performs the same duty. It just omits the host, port, and scheme information in the return value; only the path, query parameters, and anchor data are present in the returned string. For example, if you've defined a route named 'foobar' with the path ``/:foo/:bar``, this call to ``route_path``:: route_path('foobar', request, foo='1', bar='2') Will return the string ``/1/2``. .. note:: Calling ``route_path('route', request)`` is the same as calling ``route_url('route', request, _app_url='')``. ``route_path`` is, in fact, implemented in terms of ``route_url`` in just this way. As a result, passing ``_app_url`` within the ``**kw`` values passed to ``route_path`` will result in an exception. """ return route_url(route_name, request, *elements, _app_url='', **kw)
def route_path(route_name, request, *elements, **kw): """Generates a path (aka a 'relative URL', a URL minus the host, scheme, and port) for a named :app:`Pyramid` :term:`route configuration`. .. note:: Calling :meth:`pyramid.Request.route_path` can be used to achieve the same result as :func:`pyramid.url.route_path`. This function accepts the same argument as :func:`pyramid.url.route_url` and performs the same duty. It just omits the host, port, and scheme information in the return value; only the path, query parameters, and anchor data are present in the returned string. For example, if you've defined a route named 'foobar' with the path ``/:foo/:bar``, this call to ``route_path``:: route_path('foobar', request, foo='1', bar='2') Will return the string ``/1/2``. .. note:: Calling ``route_path('route', request)`` is the same as calling ``route_url('route', request, _app_url='')``. ``route_path`` is, in fact, implemented in terms of ``route_url`` in just this way. As a result, any ``_app_url`` pass within the ``**kw`` values to ``route_path`` will be ignored. """ kw['_app_url'] = '' return route_url(route_name, request, *elements, **kw)
476,908
def register(): config = Configurator(reg, package=_context.package) config.add_view( permission=permission, context=context, view=view, name=name, request_type=request_type, route_name=route_name, request_method=request_method, request_param=request_param, containment=containment, attr=attr, renderer=renderer, wrapper=wrapper, xhr=xhr, accept=accept, header=header, path_info=path_info, match_val=match_val, custom_predicates=custom_predicates, _info=_context.info)
def register(): config = Configurator(reg, package=_context.package) config.add_view( permission=permission, context=context, view=view, name=name, request_type=request_type, route_name=route_name, request_method=request_method, request_param=request_param, containment=containment, attr=attr, renderer=renderer, wrapper=wrapper, xhr=xhr, accept=accept, header=header, path_info=path_info, match_val=match_val, custom_predicates=custom_predicates, _info=_context.info)
476,909
def test_setup_registry_locale_negotiator(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import ILocaleNegotiator reg = Registry() config = self._makeOne(reg) config.setup_registry(locale_negotiator='abc') utility = reg.getUtility(ILocaleNegotiator) self.assertEqual(utility, 'abc')
def test_setup_registry_locale_negotiator(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import ILocaleNegotiator reg = Registry() config = self._makeOne(reg) negotiator = object() config.setup_registry(locale_negotiator=negotiator) utility = reg.getUtility(ILocaleNegotiator) self.assertEqual(utility, 'abc')
476,910
def test_setup_registry_locale_negotiator(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import ILocaleNegotiator reg = Registry() config = self._makeOne(reg) config.setup_registry(locale_negotiator='abc') utility = reg.getUtility(ILocaleNegotiator) self.assertEqual(utility, 'abc')
def test_setup_registry_locale_negotiator(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import ILocaleNegotiator reg = Registry() config = self._makeOne(reg) config.setup_registry(locale_negotiator='abc') utility = reg.getUtility(ILocaleNegotiator) self.assertEqual(utility, 'abc')
476,911
def test_setup_registry_request_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRequestFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(request_factory='abc') utility = reg.getUtility(IRequestFactory) self.assertEqual(utility, 'abc')
def test_setup_registry_request_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRequestFactory reg = Registry() config = self._makeOne(reg) factory = object() config.setup_registry(request_factory=factory) utility = reg.getUtility(IRequestFactory) self.assertEqual(utility, 'abc')
476,912
def test_setup_registry_request_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRequestFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(request_factory='abc') utility = reg.getUtility(IRequestFactory) self.assertEqual(utility, 'abc')
def test_setup_registry_request_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRequestFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(request_factory='abc') utility = reg.getUtility(IRequestFactory) self.assertEqual(utility, 'abc')
476,913
def test_setup_registry_renderer_globals_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRendererGlobalsFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(renderer_globals_factory='abc') utility = reg.getUtility(IRendererGlobalsFactory) self.assertEqual(utility, 'abc')
def test_setup_registry_renderer_globals_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRendererGlobalsFactory reg = Registry() config = self._makeOne(reg) factory = object() config.setup_registry(renderer_globals_factory=factory) utility = reg.getUtility(IRendererGlobalsFactory) self.assertEqual(utility, 'abc')
476,914
def test_setup_registry_renderer_globals_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRendererGlobalsFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(renderer_globals_factory='abc') utility = reg.getUtility(IRendererGlobalsFactory) self.assertEqual(utility, 'abc')
def test_setup_registry_renderer_globals_factory(self): from repoze.bfg.registry import Registry from repoze.bfg.interfaces import IRendererGlobalsFactory reg = Registry() config = self._makeOne(reg) config.setup_registry(renderer_globals_factory='abc') utility = reg.getUtility(IRendererGlobalsFactory) self.assertEqual(utility, 'abc')
476,915
def test_set_request_factory(self): from repoze.bfg.interfaces import IRequestFactory config = self._makeOne() config.set_request_factory('abc') self.assertEqual(config.registry.getUtility(IRequestFactory), 'abc')
def test_set_request_factory(self): from repoze.bfg.interfaces import IRequestFactory config = self._makeOne() config.set_request_factory('abc') self.assertEqual(config.registry.getUtility(IRequestFactory), 'abc')
476,916
def forget(self, request): return []
def forget(self, request): return []
476,917
def renderer_factory(info): path = info.name registry = info.registry settings = info.settings lookup = registry.queryUtility(IMakoLookup) if lookup is None: reload_templates = settings.get('reload_templates', False) directories = settings.get('mako.directories') module_directory = settings.get('mako.module_directory') input_encoding = settings.get('mako.input_encoding', 'utf-8') error_handler = settings.get('mako.error_handler', None) default_filters = settings.get('mako.default_filters', []) imports = settings.get('mako.imports', []) if directories is None: raise ConfigurationError( 'Mako template used without a ``mako.directories`` setting') directories = directories.splitlines() directories = [ abspath_from_resource_spec(d) for d in directories ] lookup = PkgResourceTemplateLookup(directories=directories, module_directory=module_directory, input_encoding=input_encoding, error_handler=error_handler, default_filters=default_filters, imports=imports, filesystem_checks=reload_templates) registry_lock.acquire() try: registry.registerUtility(lookup, IMakoLookup) finally: registry_lock.release() return MakoLookupTemplateRenderer(path, lookup)
def renderer_factory(info): path = info.name registry = info.registry settings = info.settings lookup = registry.queryUtility(IMakoLookup) if lookup is None: reload_templates = settings.get('reload_templates', False) directories = settings.get('mako.directories') module_directory = settings.get('mako.module_directory') input_encoding = settings.get('mako.input_encoding', 'utf-8') error_handler = settings.get('mako.error_handler', None) default_filters = settings.get('mako.default_filters', None) imports = settings.get('mako.imports', []) if directories is None: raise ConfigurationError( 'Mako template used without a ``mako.directories`` setting') directories = directories.splitlines() directories = [ abspath_from_resource_spec(d) for d in directories ] lookup = PkgResourceTemplateLookup(directories=directories, module_directory=module_directory, input_encoding=input_encoding, error_handler=error_handler, default_filters=default_filters, imports=imports, filesystem_checks=reload_templates) registry_lock.acquire() try: registry.registerUtility(lookup, IMakoLookup) finally: registry_lock.release() return MakoLookupTemplateRenderer(path, lookup)
476,918
def template_renderer_factory(spec, impl): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) reg.registerUtility(renderer, ITemplateRenderer, name=spec) else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template reg.registerUtility(renderer, ITemplateRenderer, name=spec) return renderer
registry_lock = threading.Lock() def template_renderer_factory(spec, impl, lock=registry_lock): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) reg.registerUtility(renderer, ITemplateRenderer, name=spec) else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template reg.registerUtility(renderer, ITemplateRenderer, name=spec) return renderer
476,919
def template_renderer_factory(spec, impl): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) reg.registerUtility(renderer, ITemplateRenderer, name=spec) else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template reg.registerUtility(renderer, ITemplateRenderer, name=spec) return renderer
def template_renderer_factory(spec, impl): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) try: lock.acquire() reg.registerUtility(renderer, ITemplateRenderer, name=spec) finally: lock.release() else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template try: lock.acquire() reg.registerUtility(renderer, ITemplateRenderer, name=spec) finally: lock.release() return renderer
476,920
def template_renderer_factory(spec, impl): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) reg.registerUtility(renderer, ITemplateRenderer, name=spec) else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template reg.registerUtility(renderer, ITemplateRenderer, name=spec) return renderer
def template_renderer_factory(spec, impl): reg = get_current_registry() if os.path.isabs(spec): # 'spec' is an absolute filename if not os.path.exists(spec): raise ValueError('Missing template file: %s' % spec) renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: renderer = impl(spec) try: lock.acquire() reg.registerUtility(renderer, ITemplateRenderer, name=spec) finally: lock.release() else: # spec is a package:relpath resource spec renderer = reg.queryUtility(ITemplateRenderer, name=spec) if renderer is None: try: package_name, filename = spec.split(':', 1) except ValueError: # pragma: no cover # somehow we were passed a relative pathname; this # should die package_name = caller_package(4).__name__ filename = spec abspath = pkg_resources.resource_filename(package_name, filename) if not pkg_resources.resource_exists(package_name, filename): raise ValueError( 'Missing template resource: %s (%s)' % (spec, abspath)) renderer = impl(abspath) if not _reload_resources(): # cache the template try: lock.acquire() reg.registerUtility(renderer, ITemplateRenderer, name=spec) finally: lock.release() return renderer
476,921
def __call__(self, request): environ = request.environ try: # empty if mounted under a path in mod_wsgi, for example path = environ['PATH_INFO'] or '/' except KeyError: path = '/'
def __call__(self, request): environ = request.environ try: # empty if mounted under a path in mod_wsgi, for example path = environ['PATH_INFO'] or '/' except KeyError: path = '/'
476,922
def test_directories_list(self): from pyramid.mako_templating import IMakoLookup settings = {'mako.directories':['a', 'b']} info = DummyRendererInfo({ 'name':'helloworld.mak', 'package':None, 'registry':self.config.registry, 'settings':settings, }) self._callFUT(info) lookup = self.config.registry.getUtility(IMakoLookup) self.assertEqual(lookup.directories, ['a', 'b'])
def test_directories_list(self): from pyramid.mako_templating import IMakoLookup settings = {'mako.directories':['a', 'b']} info = DummyRendererInfo({ 'name':'helloworld.mak', 'package':None, 'registry':self.config.registry, 'settings':settings, }) self._callFUT(info) lookup = self.config.registry.getUtility(IMakoLookup) self.assertEqual(lookup.directories, ['a', 'b'])
476,923
def caller_package(level=2, caller_module=caller_module): # caller_module in arglist for tests module = caller_module(level+1) if '__init__.py' in getattr(module, '__file__', ''): # empty at >>> # Module is a package return module # Go up one level to get package package_name = module.__name__.rsplit('.', 1)[0] return sys.modules[package_name]
def caller_package(level=2, caller_module=caller_module): # caller_module in arglist for tests module = caller_module(level+1) f = getattr(module, '__file__', '') if (('__init__.py' in f) or ('__init__$py' in f)): # empty at >>> # Module is a package return module # Go up one level to get package package_name = module.__name__.rsplit('.', 1)[0] return sys.modules[package_name]
476,924
def pre(self, command, output_dir, vars): # pragma: no cover vars['random_string'] = os.urandom(20).encode('hex') return Template.pre(self, command, output_dir, vars)
def pre(self, command, output_dir, vars): # pragma: no cover vars['random_string'] = os.urandom(20).encode('hex') return Template.pre(self, command, output_dir, vars)
476,925
def restore_point(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] return mysqldump_command ("-u%s %s%s --add-drop-table --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db))
def restore_point(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] host = config["db_host"] return mysqldump_command ("-u%s %s%s %s --add-drop-table --default-character-set=utf8 %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db))
476,926
def dump(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] return mysqldump_command ("--no-data --compact -u%s %s%s --default-character-set=utf8 %s" % (user, "-p" if password else "", password, db))
def dump(): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] host = config["db_host"] return mysqldump_command ("--no-data --add-lock=false --compact -u%s %s%s %s --default-character-set=utf8 %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db))
476,927
def load (sql): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] tempfile = ".temp-mygrate-%s" % str(datetime.time()).replace (':', '_') f = open (tempfile, 'w') f.write (sql) f.close() (output, errors) = mysql_command ("-u%s %s%s --default-character-set=utf8 %s < %s" % (user, "-p" if password else "", password, db, tempfile)) os.unlink(tempfile) if errors: raise SQLLoadError (sql = sql, errors = errors) return True
def load (sql): config = cmds.init.config() user = config["db_user"] password = config["db_pass"] db = config["db_db"] tempfile = ".temp-mygrate-%s" % str(datetime.time()).replace (':', '_') f = open (tempfile, 'w') f.write (sql) f.close() (output, errors) = mysql_command ("-u%s %s%s %s --default-character-set=utf8 %s < %s" % (user, "-p" if password else "", password, "-h"+host if host <> 'localhost' else "", db, tempfile)) os.unlink(tempfile) if errors: raise SQLLoadError (sql = sql, errors = errors) return True
476,928
def _toText(self): if self.type == OPERAND_IMMEDIATE: if self.value >= 0: return "0x%x" % self.value else: return "-0x%x" % abs(self.value) elif self.type == OPERAND_REGISTER: return self.GetName() elif self.type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self.disp elif self.type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self.seg), hex(self.off)) elif (self.type == OPERAND_MEMORY): result = "[" if self.base != None: result += Registers[self.base] + "+" if self.index != None: result += Registers[self.index] if self.scale > 1: result += "*%d" % self.scale if self.disp >= 0: result += "+0x%x" % self.disp else: result += "-0x%x" % abs(self.disp) return result + "]"
def _toText(self): if self.type == OPERAND_IMMEDIATE: if self.value >= 0: return "0x%x" % self.value else: return "-0x%x" % abs(self.value) elif self.type == OPERAND_REGISTER: return self.name elif self.type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self.disp elif self.type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self.seg), hex(self.off)) elif (self.type == OPERAND_MEMORY): result = "[" if self.base != None: result += Registers[self.base] + "+" if self.index != None: result += Registers[self.index] if self.scale > 1: result += "*%d" % self.scale if self.disp >= 0: result += "+0x%x" % self.disp else: result += "-0x%x" % abs(self.disp) return result + "]"
476,929
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code_buf = create_string_buffer(code) p_code = byref(code_buf) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
476,930
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(code_buf, instruction_off) codeLen = codeLen - delta
476,931
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code_buf = create_string_buffer(code) p_code = byref(code_buf) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
476,932
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(code_buf, instruction_off) codeLen = codeLen - delta
476,933
def init_INTEGER(self): Set = lambda *args: self.SetCallback(ISetClass.INTEGER, *args)
def init_INTEGER(self): Set = lambda *args: self.SetCallback(ISetClass.INTEGER, *args)
476,934
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
def _toText(self): if self.type == OPERAND_IMMEDIATE: if self.value >= 0: return "0x%x" % self.value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
476,935
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self.value) elif self.type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
476,936
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self.type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self.disp elif self.type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self.seg), hex(self.off)) elif (self.type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
476,937
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self.base != None: result += Registers[self.base] + "+" if self.index != None: result += Registers[self.index] if self.scale > 1: result += "*%d" % self.scale if self.disp >= 0: result += "+0x%x" % self.disp else: result += "-0x%x" % abs(self._disp) return result + "]"
476,938
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self._disp) return result + "]"
def _toText(self): if self._type == OPERAND_IMMEDIATE: if self._value >= 0: return "0x%x" % self._value else: return "-0x%x" % abs(self._value) elif self._type == OPERAND_REGISTER: return self.GetName() elif self._type == OPERAND_ABSOLUTE_ADDRESS: return '[0x%x]' % self._disp elif self._type == OPERAND_FAR_MEMORY: return '%s:%s' % (hex(self._seg), hex(self._off)) elif (self._type == OPERAND_MEMORY): result = "[" if self._base != None: result += Registers[self._base] + "+" if self._index != None: result += Registers[self._index] if self._scale > 1: result += "*%d" % self._scale if self._disp >= 0: result += "+0x%x" % self._disp else: result += "-0x%x" % abs(self.disp) return result + "]"
476,939
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = '%s %s' % (di.mnemonic.p, di.operands.p) pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,940
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = '%s %s' % (di.mnemonic.p, di.operands.p) pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = '%s %s' % (di.mnemonic.p, di.operands.p) pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,941
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self.type = type self.index = None self.name = "" self.size = 0 self.value = 0 self.disp = 0 self.dispSize = 0 self.base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,942
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self.value = int(args[0]) self.size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,943
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self.index = args[0] self.size = args[1] self.name = Registers[self.index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,944
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self.base = args[0] if args[0] != R_NONE else None self.index = args[1] self.size = args[2] self.scale = args[3] if args[3] > 1 else 1 self.disp = int(args[4]) self.dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,945
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self.size = args[0] self.disp = int(args[1]) self.dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,946
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
def __init__(self, type, *args): self._type = type self._index = None self._name = "" self._size = 0 self._value = 0 self._disp = 0 self._dispSize = 0 self._base = 0 if type == OPERAND_IMMEDIATE: self._value = int(args[0]) self._size = args[1] elif type == OPERAND_REGISTER: self._index = args[0] self._size = args[1] self._name = Registers[self._index] elif type == OPERAND_MEMORY: self._base = args[0] if args[0] != R_NONE else None self._index = args[1] self._size = args[2] self._scale = args[3] if args[3] > 1 else 1 self._disp = int(args[4]) self._dispSize = args[5] elif type == OPERAND_ABSOLUTE_ADDRESS: self._size = args[0] self._disp = int(args[1]) self._dispSize = args[2] elif type == OPERAND_FAR_MEMORY: self._seg = args[0] self._off = args[1]
476,947
def __init__(self, di): "Expects a filled _DInst structure" self.opcode = di.opcode self.operands = [] self.flags = [] self.instructionClass = _getISC(0) self.flowControl = _getFC(0) self.address = di.addr self.size = di.size flags = di.flags
def __init__(self, di, instructionBytes): "Expects a filled _DInst structure, and the corresponding byte code of the whole instruction" flags = di.flags self.instructionBytes = instructionBytes self.opcode = di.opcode self.operands = [] self.flags = [] self.instructionClass = _getISC(0) self.flowControl = _getFC(0) self.address = di.addr self.size = di.size flags = di.flags
476,948
def __init__(self, di): "Expects a filled _DInst structure" self.opcode = di.opcode self.operands = [] self.flags = [] self.instructionClass = _getISC(0) self.flowControl = _getFC(0) self.address = di.addr self.size = di.size flags = di.flags
def __init__(self, di): "Expects a filled _DInst structure" self.opcode = di.opcode self.operands = [] self.flags = [] self.instructionClass = _getISC(0) self.flowControl = _getFC(0) self.address = di.addr self.size = di.size flags = di.flags
476,949
def _toText(self): opcodeFmt = "%-10s %s" paramsText = ", ".join(["%s" % i for i in self.operands]) return opcodeFmt % (self.mnemonic, paramsText)
def _toText(self): opcodeFmt = "%-10s %s" paramsText = ", ".join(["%s" % i for i in self.operands]) return opcodeFmt % (self.mnemonic, paramsText)
476,950
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] delta += di.size yield Instruction(di) if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
defyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) DecomposeGenerator(codeOffset,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) code,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) dt):yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) """yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @typeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffset:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) longyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @paramyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffset:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Memoryyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) addressyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) whereyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) theyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) isyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) located.yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Thisyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) isyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) B{not}yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) anyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) offsetyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) intoyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) theyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) code!yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) It'syield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) theyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) actualyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) memoryyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) addressyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) whereyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ityield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) wasyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) readyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) from.yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @typeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) code:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) stryield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @paramyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) code:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) toyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) disassemble.yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @typeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) dt:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) intyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @paramyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) dt:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Disassemblyyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) type.yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Canyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) beyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) oneyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ofyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) theyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) following:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) *yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) L{Decode16Bits}:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 80286yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) decodingyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) *yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) L{Decode32Bits}:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) IA-32yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) decodingyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) *yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) L{Decode64Bits}:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) AMD64yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) decodingyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @rtype:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) generatoryield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ofyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) TODOyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @return:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Generatoryield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ofyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) TODOyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) @raiseyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ValueError:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Invalidyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) arguments.yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) """yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) notyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) code:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) returnyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) notyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffset:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffsetyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 0yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) dtyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) notyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) inyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) (Decode16Bits,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Decode32Bits,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Decode64Bits):yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) raiseyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ValueError("Invalidyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) decodeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) typeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) value:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) %r"yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) %yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) (dt,))yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeLenyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) len(code)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) create_string_buffer(code)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) addressof(code)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) resultyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) (_DInstyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) *yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) MAX_INSTRUCTIONS)()yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_resultyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) byref(result)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeInfoyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) _CodeInfo(_OffsetType(codeOffset),yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_code,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeLen,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) dt,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 0)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) whileyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeLenyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) >yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 0:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) usedInstructionsCountyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) c_uint(0)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) statusyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) internal_decompose(byref(codeInfo),yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_result,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) MAX_INSTRUCTIONS,yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) byref(usedInstructionsCount))yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) statusyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ==yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) DECRES_INPUTERR:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) raiseyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ValueError("Invalidyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) argumentsyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) passedyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) toyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) distorm_decode()")yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) usedyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) usedInstructionsCount.valueyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) notyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) used:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) breakyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 0yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) foryield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) indexyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) inyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) xrange(used):yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) diyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) result[index]yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) +=yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) di.sizeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yieldyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) Instruction(di)yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) ifyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) <=yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) 0:yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) breakyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffsetyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeOffsetyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) +yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) p_codeyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) +yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeLenyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) =yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) codeLenyield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) -yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) deltayield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size])
476,951
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] delta += di.size yield Instruction(di) if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,952
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
476,953
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) instruction_off += di.size yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
476,954
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = byref(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
476,955
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = pointer(create_string_buffer(code[instruction_off:])) codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) p_code = pointer(create_string_buffer(code)) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), cast(p_code, c_char_p), codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size], dt) delta += di.size instruction_off += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = byref(create_string_buffer(code), instruction_off) codeLen = codeLen - delta
476,956
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecodeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of tuple( long, int, str, str ) @return: Generator of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DecodedInst * MAX_INSTRUCTIONS)() p_result = byref(result) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decode(_OffsetType(codeOffset), p_code, codeLen, dt, p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break for index in xrange(used): di = result[index] asm = di.mnemonic.p if len(di.operands.p): asm += " " + di.operands.p pydi = ( di.offset, di.size, asm, di.instructionHex.p ) yield pydi di = result[used - 1] delta = di.offset - codeOffset + result[used -1].size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,957
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) scode = create_string_buffer(code) p_code = addressof(scode) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,958
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() instruction_off = 0 while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,959
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) status = internal_decompose(byref(codeInfo), byref(result), MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,960
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[codeOffset + delta : codeOffset + delta + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
def DecomposeGenerator(codeOffset, code, dt): """ @type codeOffset: long @param codeOffset: Memory address where the code is located. This is B{not} an offset into the code! It's the actual memory address where it was read from. @type code: str @param code: Code to disassemble. @type dt: int @param dt: Disassembly type. Can be one of the following: * L{Decode16Bits}: 80286 decoding * L{Decode32Bits}: IA-32 decoding * L{Decode64Bits}: AMD64 decoding @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits, Decode32Bits, Decode64Bits): raise ValueError("Invalid decode type value: %r" % (dt,)) codeLen = len(code) code = create_string_buffer(code) p_code = addressof(code) result = (_DInst * MAX_INSTRUCTIONS)() p_result = byref(result) codeInfo = _CodeInfo(_OffsetType(codeOffset), _OffsetType(0), p_code, codeLen, dt, 0) while codeLen > 0: usedInstructionsCount = c_uint(0) status = internal_decompose(byref(codeInfo), p_result, MAX_INSTRUCTIONS, byref(usedInstructionsCount)) if status == DECRES_INPUTERR: raise ValueError("Invalid arguments passed to distorm_decode()") used = usedInstructionsCount.value if not used: break delta = 0 for index in xrange(used): di = result[index] yield Instruction(di, code[instruction_off : instruction_off + di.size]) delta += di.size if delta <= 0: break codeOffset = codeOffset + delta p_code = p_code + delta codeLen = codeLen - delta
476,961
def get_sources(): """Returns a list of C source files that should be compiled to create the libdistorm3 library. """ return glob('src/*.c') + glob('include/*.c')
def get_sources(): """Returns a list of C source files that should be compiled to create the libdistorm3 library. """ return glob('src/*.c')
476,962
def nn(self, pts, qpts, num_neighbors = 1, **kwargs): """ Returns the num_neighbors nearest points in dataset for each point in testset. """ if not pts.dtype.type in allowed_types: raise FLANNException("Cannot handle type: %s"%pts.dtype)
def nn(self, pts, qpts, num_neighbors = 1, **kwargs): """ Returns the num_neighbors nearest points in dataset for each point in testset. """ if not pts.dtype.type in allowed_types: raise FLANNException("Cannot handle type: %s"%pts.dtype)
476,963
def ensure_2d_array(array, flags, **kwargs): array = require(array, requirements = flags, **kwargs) if len(array.shape) == 1: array.shape = (-1,array.size) return array
def ensure_2d_array(array, flags, **kwargs): array = require(array, requirements = flags, **kwargs) if len(array.shape) == 1: array = array.reshape(-1,array.size) return array
476,964
def load_flann_library(): root_dir = os.path.abspath(os.path.dirname(__file__)) libname = 'libflann' if sys.platform == 'win32': libname = 'flann' flann = None loaded = False while (not loaded) and root_dir!="/": try: flann = load_library(libname, os.path.join(root_dir,'lib')) loaded = True except: root_dir = os.path.dirname(root_dir) return flann
def load_flann_library(): root_dir = os.path.abspath(os.path.dirname(__file__)) libname = 'libflann' if sys.platform == 'win32': libname = 'flann' flann = None loaded = False while (not loaded) and root_dir!="/": try: flann = load_library(libname, os.path.join(root_dir,'lib')) loaded = True except Exception as e: print e root_dir = os.path.dirname(root_dir) return flann
476,965
def kmeans(self, pts, num_clusters, centers_init = "random", max_iterations = None, dtype = None, **kwargs): """ Runs kmeans on pts with num_clusters centroids. Returns a numpy array of size num_clusters x dim.
def kmeans(self, pts, num_clusters, max_iterations = None, dtype = None, **kwargs): """ Runs kmeans on pts with num_clusters centroids. Returns a numpy array of size num_clusters x dim.
476,966
def import_to_global(modname, attrs=None, math=False): """ import_to_global(modname, (a,b,c,...), math): like "from modname import a,b,c,...", but imports to global namespace (__main__). If math==True, also registers functions with QtiPlot's math function list. """ import sys import os sys.path.append(os.path.dirname(__file__)) mod = __import__(modname) for submod in modname.split(".")[1:]: mod = getattr(mod, submod) if attrs==None: attrs=dir(mod) for name in attrs: f = getattr(mod, name) setattr(__main__, name, f) # make functions available in QtiPlot's math function list if math and callable(f): qti.mathFunctions[name] = f
def import_to_global(modname, attrs=None, math=False): """ import_to_global(modname, (a,b,c,...), math): like "from modname import a,b,c,...", but imports to global namespace (__main__). If math==True, also registers functions with QtiPlot's math function list. """ import sys import os sys.path.append(os.path.dirname(__file__)) mod = __import__(modname) for submod in modname.split(".")[1:]: mod = getattr(mod, submod) if attrs==None: attrs=dir(mod) for name in attrs: f = getattr(mod, name) setattr(__main__, name, f) # make functions available in QtiPlot's math function list if math and callable(f): qti.mathFunctions[name] = f
476,967
def __init__(self, base_path=None, template_path=None, script_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
def __init__(self, base_path=None, template_path=None, script_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
476,968
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,969
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,970
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,971
def __init__(self, base_path=None, template_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True, capture_temp=False, assert_no_temp=False): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
def __init__(self, base_path=None, template_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True, capture_temp=False, assert_no_temp=False, split_cmd=True): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
476,972
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,973
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,974
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,975
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,976
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,977
def __init__(self, base_path=None, template_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True, capture_temp=False, assert_no_temp=False): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
def __init__(self, base_path=None, template_path=None, environ=None, cwd=None, start_clear=True, ignore_paths=None, ignore_hidden=True, capture_temp=False, assert_no_temp=False, split_cmd=True): """ Creates an environment. ``base_path`` is used as the current working directory, and generally where changes are looked for. If not given, it will be the directory of the calling script plus ``test-output/``.
476,978
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
def run(self, script, *args, **kw): """ Run the command, with the given arguments. The ``script`` argument can have space-separated arguments, or you can use the positional arguments.
476,979
def main(): try: fetch_threads = [] parser = OptionParser(usage="Usage: %prog [options] url") parser.add_option("-s", "--max-speed", dest="max_speed", help="Specifies maximum speed (bytes per second)." " Useful if you don't want the program to suck up" " all of your bandwidth", metavar="SPEED") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4, help="You can specify an alternative number of" " connections here.", metavar="NUM") parser.add_option("-o", "--output", dest="output_file", help="By default, data does to a local file of " "the same name. If this option is used, downloaded" " data will go to this file.") (options, args) = parser.parse_args() print "Options: ", options print "args: ", args if len(args) != 1: parser.print_help() sys.exit(1) # General configuration urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPCookieProcessor())) socket.setdefaulttimeout(120) # 2 minutes url = args[0] output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) print "Need to fetch %s\n" % report_bytes(filesize) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() #create output file out_fd = os.open(output_file, os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) # Blank spaces trail below to erase previous output. TODO: Need to # do this better. pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file os.remove(state_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True
def main(): try: fetch_threads = [] parser = OptionParser(usage="Usage: %prog [options] url") parser.add_option("-s", "--max-speed", dest="max_speed", help="Specifies maximum speed (bytes per second)." " Useful if you don't want the program to suck up" " all of your bandwidth", metavar="SPEED") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4, help="You can specify an alternative number of" " connections here.", metavar="NUM") parser.add_option("-o", "--output", dest="output_file", help="By default, data does to a local file of " "the same name. If this option is used, downloaded" " data will go to this file.") (options, args) = parser.parse_args() print "Options: ", options print "args: ", args if len(args) != 1: parser.print_help() sys.exit(1) # General configuration urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPCookieProcessor())) socket.setdefaulttimeout(120) # 2 minutes url = args[0] output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) print "Need to fetch %s\n" % report_bytes(filesize) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() #create output file out_fd = os.open(output_file, os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) # Blank spaces trail below to erase previous output. TODO: Need to # do this better. pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file os.remove(state_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True
476,980
def main(): try: fetch_threads = [] parser = OptionParser(usage="Usage: %prog [options] url") parser.add_option("-s", "--max-speed", dest="max_speed", help="Specifies maximum speed (bytes per second)." " Useful if you don't want the program to suck up" " all of your bandwidth", metavar="SPEED") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4, help="You can specify an alternative number of" " connections here.", metavar="NUM") parser.add_option("-o", "--output", dest="output_file", help="By default, data does to a local file of " "the same name. If this option is used, downloaded" " data will go to this file.") (options, args) = parser.parse_args() print "Options: ", options print "args: ", args if len(args) != 1: parser.print_help() sys.exit(1) # General configuration urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPCookieProcessor())) socket.setdefaulttimeout(120) # 2 minutes url = args[0] output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) print "Need to fetch %s\n" % report_bytes(filesize) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() #create output file out_fd = os.open(output_file, os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) # Blank spaces trail below to erase previous output. TODO: Need to # do this better. pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file os.remove(state_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True
def main(): try: fetch_threads = [] parser = OptionParser(usage="Usage: %prog [options] url") parser.add_option("-s", "--max-speed", dest="max_speed", help="Specifies maximum speed (bytes per second)." " Useful if you don't want the program to suck up" " all of your bandwidth", metavar="SPEED") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-n", "--num-connections", dest="num_connections", type="int", default=4, help="You can specify an alternative number of" " connections here.", metavar="NUM") parser.add_option("-o", "--output", dest="output_file", help="By default, data does to a local file of " "the same name. If this option is used, downloaded" " data will go to this file.") (options, args) = parser.parse_args() print "Options: ", options print "args: ", args if len(args) != 1: parser.print_help() sys.exit(1) # General configuration urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())) urllib2.install_opener(urllib2.build_opener( urllib2.HTTPCookieProcessor())) socket.setdefaulttimeout(120) # 2 minutes url = args[0] output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) print "Need to fetch %s\n" % report_bytes(filesize) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() #create output file out_fd = os.open(output_file, os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) # Blank spaces trail below to erase previous output. TODO: Need to # do this better. pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file os.remove(state_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True
476,981
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,982
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,983
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,984
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,985
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,986
def download(url, options): fetch_threads = [] try: output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() print "Need to fetch %s\n" % report_bytes(conn_state.filesize - sum(conn_state.progress)) #create output file with a .part extension to indicate partial download out_fd = os.open(output_file+".part", os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / options.max_speed * \ 1024 - conn_state.elapsed_time pbar.display_progress() time.sleep(1) pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file and move the dwnld to output file from .part file os.remove(state_file) os.rename(output_file+".part", output_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True except Exception, e: # TODO: handle other types of errors too. print e for thread in fetch_threads: thread._need_to_quit = True
def download(url, options): fetch_threads = [] try: output_file = url.rsplit("/", 1)[1] # basename of the url if options.output_file != None: output_file = options.output_file if output_file == "": print "Invalid URL" sys.exit(1) print "Destination = ", output_file filesize = get_file_size(url) conn_state = ConnectionState(options.num_connections, filesize) pbar = ProgressBar(options.num_connections, conn_state) # Checking if we have a partial download available and resume state_file = output_file + ".st" try: os.stat(state_file) except OSError, o: #statefile is missing for all practical purposes pass else: state_fd = file(state_file, "r") conn_state.resume_state(state_fd) state_fd.close() print "Need to fetch %s\n" % report_bytes(conn_state.filesize - sum(conn_state.progress)) #create output file with a .part extension to indicate partial download out_fd = os.open(output_file+".part", os.O_CREAT | os.O_WRONLY) start_offset = 0 start_time = time.time() for i in range(options.num_connections): # each iteration should spawn a thread. # print start_offset, len_list[i] current_thread = FetchData(i, url, output_file, state_file, start_offset + conn_state.progress[i], conn_state) fetch_threads.append(current_thread) current_thread.start() start_offset += conn_state.chunks[i] while threading.active_count() > 1: #print "\n",progress end_time = time.time() conn_state.update_time_taken(end_time - start_time) start_time = end_time dwnld_sofar = conn_state.download_sofar() if options.max_speed != None and \ (dwnld_sofar / conn_state.elapsed_time) > \ (options.max_speed * 1024): for th in fetch_threads: th.need_to_sleep = True th.sleep_timer = dwnld_sofar / (options.max_speed * \ 1024 - conn_state.elapsed_time) pbar.display_progress() time.sleep(1) pbar.display_progress() # at this point we are sure dwnld completed and can delete the # state file and move the dwnld to output file from .part file os.remove(state_file) os.rename(output_file+".part", output_file) except KeyboardInterrupt, k: for thread in fetch_threads: thread.need_to_quit = True except Exception, e: # TODO: handle other types of errors too. print e for thread in fetch_threads: thread._need_to_quit = True
476,987
def main(options, args): try: general_configuration() url = args[0] download(url, options) except KeyboardInterrupt, k: sys.exit(1) except Exception, e: # TODO: handle other types of errors too. print e pass
def main(options, args): try: general_configuration() url = args[0] download(url, options) except KeyboardInterrupt, k: sys.exit(1) except Exception, e: # TODO: handle other types of errors too. print e pass
476,988
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
def run(self): # Ready the url object # print "Running thread with %d-%d" % (self.start_offset, self.length) request = urllib2.Request(url, None, std_headers) request.add_header('Range','bytes=%d-%d' % (self.start_offset, self.start_offset+self.length)) data = urllib2.urlopen(request)
476,989
def _build(self): return self.sys_log("HDF5_DIR=%s make -j%s" % (self.blddir, jobs(self.name)))
def _build(self): return self.sys_log("HDF5_DIR=%s make -j%s" % (self.blddir, jobs(self.name)))
476,990
def find_cgal_vers(self, installed=False, in_build=False): v = '' f = self.find_cgal_inc(installed, in_build) if f: while True: line = f.readline() if not line: break v = re.findall(r'#define CGAL_VERSION ([^\r\n]*)', line) if v: v = v[0] break verbose(2, 'CGAL version=%s' % v) f.close() return v
def find_cgal_vers(self, installed=False, in_build=False): v = '' f = self.find_cgal_inc(installed, in_build) if f: while True: line = f.readline() if not line: break v = re.findall(r'#define CGAL_VERSION ([^\r\n]*)', line) if v: v = v[0] break verbose(2, 'CGAL version=%s' % v) return v
476,991
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
476,992
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
def usage(): print "Usage: %s filebase [outfilename]" % sys.argv[0] print "Where filebase.cas is a Fluent case file." print "Output will be in filebase-prism.dat if it is not specified." sys.exit(1)
476,993
def __init__(self, cname, topdir, make_path): # create build directories cwd = os.getcwd() self.topdir = topdir self.blddir = os.path.join(os.getcwd(), "build-%s" % cname) self.logdir = os.path.join(self.blddir, "log") self.bindir = os.path.join(self.blddir, "bin") self.libdir = os.path.join(self.blddir, "lib") for p in [self.blddir, self.logdir, self.libdir, self.bindir ]: if not os.path.isdir(p): try: os.makedirs(p) except: fatal("error creating directory " + p)
def __init__(self, cname, topdir, make_path): # create build directories cwd = os.getcwd() topdir = os.path.abspath(topdir) self.topdir = topdir self.blddir = os.path.join(os.getcwd(), "build-%s" % cname) self.logdir = os.path.join(self.blddir, "log") self.bindir = os.path.join(self.blddir, "bin") self.libdir = os.path.join(self.blddir, "lib") for p in [self.blddir, self.logdir, self.libdir, self.bindir ]: if not os.path.isdir(p): try: os.makedirs(p) except: fatal("error creating directory " + p)
476,994
def __init__(self, cname, topdir, make_path): # create build directories cwd = os.getcwd() self.topdir = topdir self.blddir = os.path.join(os.getcwd(), "build-%s" % cname) self.logdir = os.path.join(self.blddir, "log") self.bindir = os.path.join(self.blddir, "bin") self.libdir = os.path.join(self.blddir, "lib") for p in [self.blddir, self.logdir, self.libdir, self.bindir ]: if not os.path.isdir(p): try: os.makedirs(p) except: fatal("error creating directory " + p)
def __init__(self, cname, topdir, make_path): # create build directories cwd = os.getcwd() self.topdir = topdir self.blddir = os.path.join(os.getcwd(), "build-%s" % cname) self.logdir = os.path.join(self.blddir, "log") self.bindir = os.path.join(self.blddir, "bin") self.libdir = os.path.join(self.blddir, "lib") for p in [self.blddir, self.logdir, self.libdir, self.bindir ]: if not os.path.isdir(p): try: os.makedirs(p) except: fatal("error creating directory " + p)
476,995
def generate(env): cppTool.generate(env) if not env.get('CXXVERSION'): try: line = os.popen("/bin/bash -c 'gcc --version 2>&1'").readline() env['CXXVERSION'] = re.compile(r'[^(]*[^)]*\) ([^\n ]*)').findall(line)[0] except: env['CXXVERSION'] = '4.2.1' env['COMPILER'] = 'gcc-' + env['CXXVERSION'] env['CXXFLAGS'] = CLVar('-Wall -fno-strict-aliasing -Woverloaded-virtual -ftemplate-depth-200 -frounding-math') if is64Bit(): env.Append(CPPDEFINES=CLVar('OS_64BIT')) if env['DEBUG']: env.Append(CXXFLAGS=['-g', '-O0']) else: env.Append(CXXFLAGS=['-O3', '-finline-limit=500']) if env['OPENMP']: env.Append(CXXFLAGS=['-fopenmp']) if env['PARALLEL']: env['CXX'] = 'mpicxx' env.Append(CXXFLAGS=['-DFVM_PARALLEL']) #bug fix for mpich env.Append(CXXFLAGS=['-DMPICH_IGNORE_CXX_SEEK']) else: env['CXX'] = 'cxx' env['CCFLAGS'] = env['CXXFLAGS'] env['SHCXXFLAGS'] = CLVar('$CXXFLAGS -fPIC')
def generate(env): cppTool.generate(env) if not env.get('CXXVERSION'): try: line = os.popen("/bin/bash -c 'gcc --version 2>&1'").readline() env['CXXVERSION'] = re.compile(r'[^(]*[^)]*\) ([^\n ]*)').findall(line)[0] except: env['CXXVERSION'] = '4.2.1' env['COMPILER'] = 'gcc-' + env['CXXVERSION'] env['CXXFLAGS'] = CLVar('-Wall -fno-strict-aliasing -Woverloaded-virtual -ftemplate-depth-200 -frounding-math') if is64Bit(): env.Append(CPPDEFINES=CLVar('OS_64BIT')) if env['DEBUG']: env.Append(CXXFLAGS=['-g', '-O0']) else: env.Append(CXXFLAGS=['-O3', '-finline-limit=500']) if env['OPENMP']: env.Append(CXXFLAGS=['-fopenmp']) if env['PARALLEL']: env['CXX'] = 'mpicxx' env.Append(CXXFLAGS=['-DFVM_PARALLEL']) #bug fix for mpich env.Append(CXXFLAGS=['-DMPICH_IGNORE_CXX_SEEK']) else: env['CXX'] = 'c++' env['CCFLAGS'] = env['CXXFLAGS'] env['SHCXXFLAGS'] = CLVar('$CXXFLAGS -fPIC')
476,996
def _build(self): return self.sys_log("make -j%s" % jobs(self.name))
def _build(self): return self.sys_log("make -j%s" % jobs(self.name))
476,997
def sys_log(self, cmd, show=False): "Execute a system call and log the result." # get configuration variable e = config(self.name, self.state) e = e.replace('BUILDDIR', self.blddir) e = e.replace('SRCDIR', self.sdir) e = e.replace('TMPBDIR', self.bdir) e = e.replace('LOGDIR', self.logdir) cmd = cmd + " " + e debug(cmd) f = None if self.logfile != '': f = open(self.logfile, 'a') print >> f, "EXECUTING:", cmd p = Popen(cmd, shell=True, stderr=PIPE, stdout=PIPE) pid = p.pid plist = [p.stdout, p.stderr] done = 0 while not done: rr, wr, er = select.select(plist, [], plist) if er: print 'er=',er for fd in rr: data = os.read(fd.fileno(), 1024) if data == '': plist.remove(fd) if plist == []: done = 1 else: if fd == p.stderr: print >>f, data, if show: cprint('DYELLOW', data, False) else: if show: print data, print >>f, data, if f: f.close() try: return os.waitpid(pid, 0)[1] except: return 0
def sys_log(self, cmd, show=False): "Execute a system call and log the result." # get configuration variable e = config(self.name, self.state) e = e.replace('BUILDDIR', self.blddir) e = e.replace('SRCDIR', self.sdir) e = e.replace('TMPBDIR', self.bdir) e = e.replace('LOGDIR', self.logdir) cmd = cmd + " " + e debug(cmd) f = None if self.logfile != '': f = open(self.logfile, 'a') print >> f, "EXECUTING:", cmd p = Popen(cmd, shell=True, stderr=PIPE, stdout=PIPE) pid = p.pid plist = [p.stdout, p.stderr] done = 0 while not done: rr, wr, er = select(plist, [], plist) if er: print 'er=',er for fd in rr: data = os.read(fd.fileno(), 1024) if data == '': plist.remove(fd) if plist == []: done = 1 else: if fd == p.stderr: print >>f, data, if show: cprint('DYELLOW', data, False) else: if show: print data, print >>f, data, if f: f.close() try: return os.waitpid(pid, 0)[1] except: return 0
476,998
def write_env(bld, cwd, cname): # write out env.csh for people who haven't yet learned bash env_name = os.path.join(cwd, 'env.csh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "setenv LD_LIBRARY_PATH " + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "setenv PYTHONPATH " + os.environ['PYTHONPATH'] except: pass print >> f, "setenv PATH %s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "setenv MEMOSA_CONFNAME %s" % cname f.close() # write out env.sh env_name = os.path.join(cwd, 'env.sh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "export LD_LIBRARY_PATH=" + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "export PYTHONPATH=" + os.environ['PYTHONPATH'] except: pass print >> f, "export PATH=%s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "export MEMOSA_CONFNAME=%s" % cname f.close() return env_name
def write_env(bld, cwd, cname): # write out env.csh for people who haven't yet learned bash env_name = os.path.join(cwd, 'env.csh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): exp = re.findall(r'export (\S+)=(\S+)', cmd) if exp: f.write('setenv %s %s\n' % (exp[0][0], exp[0][1])) else: f.write('%s\n' % cmd) print >> f, "setenv LD_LIBRARY_PATH " + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "setenv PYTHONPATH " + os.environ['PYTHONPATH'] except: pass print >> f, "setenv PATH %s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "setenv MEMOSA_CONFNAME %s" % cname f.close() # write out env.sh env_name = os.path.join(cwd, 'env.sh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): exp = re.findall(r'export (\S+)=(\S+)', cmd) if exp: f.write('setenv %s %s\n' % (exp[0][0], exp[0][1])) else: f.write('%s\n' % cmd) print >> f, "export LD_LIBRARY_PATH=" + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "export PYTHONPATH=" + os.environ['PYTHONPATH'] except: pass print >> f, "export PATH=%s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "export MEMOSA_CONFNAME=%s" % cname f.close() return env_name
476,999