signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@property<EOL><INDENT>def verbosity(self):<DEDENT> | raise NotImplementedError<EOL> | Verbosity level.
0: no output
1: error and warning messages only
2: normal output
3: full output | f14907:c4:m2 |
@property<EOL><INDENT>def timeout(self):<DEDENT> | raise NotImplementedError<EOL> | Timeout parameter (seconds). | f14907:c4:m4 |
@property<EOL><INDENT>def presolve(self):<DEDENT> | raise NotImplementedError<EOL> | Turn pre-processing on or off. Set to 'auto' to only use presolve if no optimal solution can be found. | f14907:c4:m6 |
def _tolerance_functions(self): | return {}<EOL> | This should be implemented in child classes. Must return a dict, where keys are available tolerance parameters
and values are tuples of (getter_function, setter_function).
The getter functions must be callable with no arguments and the setter functions must be callable with the
new value as the only argument | f14907:c4:m9 |
@property<EOL><INDENT>def presolve(self):<DEDENT> | raise NotImplementedError<EOL> | If the presolver should be used (if available). | f14907:c5:m1 |
@classmethod<EOL><INDENT>def clone(cls, model, use_json=True, use_lp=False):<DEDENT> | model.update()<EOL>interface = sys.modules[cls.__module__]<EOL>if use_lp:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL>new_model = cls.from_lp(model.to_lp())<EOL>new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)<EOL>return new_model<EOL><DEDENT>if use_json:<EOL><INDENT>new_model = cls.from_json(model.to_json())<EOL>new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)<EOL>return new_model<EOL><DEDENT>new_model = cls()<EOL>for variable in model.variables:<EOL><INDENT>new_variable = interface.Variable.clone(variable)<EOL>new_model._add_variable(new_variable)<EOL><DEDENT>for constraint in model.constraints:<EOL><INDENT>new_constraint = interface.Constraint.clone(constraint, model=new_model)<EOL>new_model._add_constraint(new_constraint)<EOL><DEDENT>if model.objective is not None:<EOL><INDENT>new_model.objective = interface.Objective.clone(model.objective, model=new_model)<EOL><DEDENT>new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)<EOL>return new_model<EOL> | Make a copy of a model. The model being copied can be of the same type or belong to
a different solver interface. This is the preferred way of copying models.
Example
----------
>>> new_model = Model.clone(old_model) | f14907:c7:m0 |
@property<EOL><INDENT>def interface(self):<DEDENT> | return sys.modules[self.__module__]<EOL> | Provides access to the solver interface the model belongs to
Returns a Python module, for example optlang.glpk_interface | f14907:c7:m2 |
@property<EOL><INDENT>def objective(self):<DEDENT> | return self._objective<EOL> | The model's objective function. | f14907:c7:m3 |
@property<EOL><INDENT>def variables(self):<DEDENT> | self.update()<EOL>return self._variables<EOL> | The model variables. | f14907:c7:m5 |
@property<EOL><INDENT>def constraints(self):<DEDENT> | self.update()<EOL>return self._constraints<EOL> | The model constraints. | f14907:c7:m6 |
@property<EOL><INDENT>def status(self):<DEDENT> | return self._status<EOL> | The solver status of the model. | f14907:c7:m7 |
def _get_variables_names(self): | return [variable.name for variable in self.variables]<EOL> | The names of model variables.
Returns
-------
list | f14907:c7:m8 |
@property<EOL><INDENT>def primal_values(self):<DEDENT> | return collections.OrderedDict(<EOL>zip(self._get_variables_names(), self._get_primal_values())<EOL>)<EOL> | The primal values of model variables.
The primal values are rounded to the bounds.
Returns
-------
collections.OrderedDict | f14907:c7:m9 |
def _get_primal_values(self): | <EOL>return [variable.primal for variable in self.variables]<EOL> | The primal values of model variables.
Returns
-------
list | f14907:c7:m10 |
@property<EOL><INDENT>def reduced_costs(self):<DEDENT> | return collections.OrderedDict(<EOL>zip(self._get_variables_names(), self._get_reduced_costs())<EOL>)<EOL> | The reduced costs/dual values of all variables.
Returns
-------
collections.OrderedDict | f14907:c7:m11 |
def _get_reduced_costs(self): | <EOL>return [variable.dual for variable in self.variables]<EOL> | The reduced costs/dual values of all variables.
Returns
-------
list | f14907:c7:m12 |
def _get_constraint_names(self): | return [constraint.name for constraint in self.constraints]<EOL> | The names of model constraints.
Returns
-------
list | f14907:c7:m13 |
@property<EOL><INDENT>def constraint_values(self):<DEDENT> | return collections.OrderedDict(<EOL>zip(self._get_constraint_names(), self._get_constraint_values())<EOL>)<EOL> | The primal values of all constraints.
Returns
-------
collections.OrderedDict | f14907:c7:m14 |
def _get_constraint_values(self): | <EOL>return [constraint.primal for constraint in self.constraints]<EOL> | The primal values of all constraints.
Returns
-------
list | f14907:c7:m15 |
@property<EOL><INDENT>def shadow_prices(self):<DEDENT> | return collections.OrderedDict(<EOL>zip(self._get_constraint_names(), self._get_shadow_prices())<EOL>)<EOL> | The shadow prices of model (dual values of all constraints).
Returns
-------
collections.OrderedDict | f14907:c7:m16 |
def _get_shadow_prices(self): | <EOL>return [constraint.dual for constraint in self.constraints]<EOL> | The shadow prices of model (dual values of all constraints).
Returns
-------
collections.OrderedDict | f14907:c7:m17 |
def add(self, stuff, sloppy=False): | if self._pending_modifications.toggle == '<STR_LIT>':<EOL><INDENT>self.update()<EOL>self._pending_modifications.toggle = '<STR_LIT>'<EOL><DEDENT>if isinstance(stuff, collections.Iterable):<EOL><INDENT>for elem in stuff:<EOL><INDENT>self.add(elem, sloppy=sloppy)<EOL><DEDENT><DEDENT>elif isinstance(stuff, Variable):<EOL><INDENT>if stuff.__module__ != self.__module__:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>stuff, stuff.__module__, self.__module__))<EOL><DEDENT>self._pending_modifications.add_var.append(stuff)<EOL><DEDENT>elif isinstance(stuff, Constraint):<EOL><INDENT>if stuff.__module__ != self.__module__:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>stuff, stuff.__module__, self.__module__))<EOL><DEDENT>if sloppy is True:<EOL><INDENT>self._pending_modifications.add_constr_sloppy.append(stuff)<EOL><DEDENT>else:<EOL><INDENT>self._pending_modifications.add_constr.append(stuff)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % stuff)<EOL><DEDENT> | Add variables and constraints.
Parameters
----------
stuff : iterable, Variable, Constraint
Either an iterable containing variables and constraints or a single variable or constraint.
sloppy : bool
Check constraints for variables that are not part of the model yet.
Returns
-------
None | f14907:c7:m20 |
def remove(self, stuff): | if self._pending_modifications.toggle == '<STR_LIT>':<EOL><INDENT>self.update()<EOL>self._pending_modifications.toggle = '<STR_LIT>'<EOL><DEDENT>if isinstance(stuff, str):<EOL><INDENT>try:<EOL><INDENT>variable = self.variables[stuff]<EOL>self._pending_modifications.rm_var.append(variable)<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>constraint = self.constraints[stuff]<EOL>self._pending_modifications.rm_constr.append(constraint)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise LookupError(<EOL>"<STR_LIT>" % stuff)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(stuff, Variable):<EOL><INDENT>self._pending_modifications.rm_var.append(stuff)<EOL><DEDENT>elif isinstance(stuff, Constraint):<EOL><INDENT>self._pending_modifications.rm_constr.append(stuff)<EOL><DEDENT>elif isinstance(stuff, collections.Iterable):<EOL><INDENT>for elem in stuff:<EOL><INDENT>self.remove(elem)<EOL><DEDENT><DEDENT>elif isinstance(stuff, Objective):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % stuff)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % stuff)<EOL><DEDENT> | Remove variables and constraints.
Parameters
----------
stuff : iterable, str, Variable, Constraint
Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names).
Returns
-------
None | f14907:c7:m21 |
def update(self, callback=int): | <EOL>add_var = self._pending_modifications.add_var<EOL>if len(add_var) > <NUM_LIT:0>:<EOL><INDENT>self._add_variables(add_var)<EOL>self._pending_modifications.add_var = []<EOL><DEDENT>callback()<EOL>add_constr = self._pending_modifications.add_constr<EOL>if len(add_constr) > <NUM_LIT:0>:<EOL><INDENT>self._add_constraints(add_constr)<EOL>self._pending_modifications.add_constr = []<EOL><DEDENT>add_constr_sloppy = self._pending_modifications.add_constr_sloppy<EOL>if len(add_constr_sloppy) > <NUM_LIT:0>:<EOL><INDENT>self._add_constraints(add_constr_sloppy, sloppy=True)<EOL>self._pending_modifications.add_constr_sloppy = []<EOL><DEDENT>var_lb = self._pending_modifications.var_lb<EOL>var_ub = self._pending_modifications.var_ub<EOL>if len(var_lb) > <NUM_LIT:0> or len(var_ub) > <NUM_LIT:0>:<EOL><INDENT>self._set_variable_bounds_on_problem(var_lb, var_ub)<EOL>self._pending_modifications.var_lb = []<EOL>self._pending_modifications.var_ub = []<EOL><DEDENT>rm_var = self._pending_modifications.rm_var<EOL>if len(rm_var) > <NUM_LIT:0>:<EOL><INDENT>self._remove_variables(rm_var)<EOL>self._pending_modifications.rm_var = []<EOL><DEDENT>callback()<EOL>rm_constr = self._pending_modifications.rm_constr<EOL>if len(rm_constr) > <NUM_LIT:0>:<EOL><INDENT>self._remove_constraints(rm_constr)<EOL>self._pending_modifications.rm_constr = []<EOL><DEDENT> | Process all pending model modifications. | f14907:c7:m22 |
def optimize(self): | self.update()<EOL>status = self._optimize()<EOL>if status != OPTIMAL and self.configuration.presolve == "<STR_LIT>":<EOL><INDENT>self.configuration.presolve = True<EOL>status = self._optimize()<EOL>self.configuration.presolve = "<STR_LIT>"<EOL><DEDENT>self._status = status<EOL>return status<EOL> | Solve the optimization problem using the relevant solver back-end.
The status returned by this method tells whether an optimal solution was found,
if the problem is infeasible etc. Consult optlang.statuses for more elaborate explanations
of each status.
The objective value can be accessed from 'model.objective.value', while the solution can be
retrieved by 'model.primal_values'.
Returns
-------
status: str
Solution status. | f14907:c7:m23 |
def to_json(self): | json_obj = {<EOL>"<STR_LIT:name>": self.name,<EOL>"<STR_LIT>": [var.to_json() for var in self.variables],<EOL>"<STR_LIT>": [const.to_json() for const in self.constraints],<EOL>"<STR_LIT>": self.objective.to_json()<EOL>}<EOL>return json_obj<EOL> | Returns a json-compatible object from the model that can be saved using the json module.
Variables, constraints and objective contained in the model will be saved. Configurations
will not be saved.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(model.to_json(), outfile) | f14907:c7:m34 |
@classmethod<EOL><INDENT>def from_json(cls, json_obj):<DEDENT> | model = cls()<EOL>model._init_from_json(json_obj)<EOL>return model<EOL> | Constructs a Model from the provided json-object.
Example
--------
>>> import json
>>> with open("path_to_file.json") as infile:
>>> model = Model.from_json(json.load(infile)) | f14907:c7:m35 |
def read_table(filename, usecols=(<NUM_LIT:0>, <NUM_LIT:1>), sep='<STR_LIT:\t>', comment='<STR_LIT:#>', encoding='<STR_LIT:utf-8>', skip=<NUM_LIT:0>): | with io.open(filename, '<STR_LIT:r>', encoding=encoding) as f:<EOL><INDENT>for _ in range(skip):<EOL><INDENT>next(f)<EOL><DEDENT>lines = (line for line in f if not line.startswith(comment))<EOL>d = dict()<EOL>for line in lines:<EOL><INDENT>columns = line.split(sep)<EOL>key = columns[usecols[<NUM_LIT:0>]].lower()<EOL>value = columns[usecols[<NUM_LIT:1>]].rstrip('<STR_LIT:\n>')<EOL>d[key] = value<EOL><DEDENT><DEDENT>return d<EOL> | Parse data files from the data directory
Parameters
----------
filename: string
Full path to file
usecols: list, default [0, 1]
A list of two elements representing the columns to be parsed into a dictionary.
The first element will be used as keys and the second as values. Defaults to
the first two columns of `filename`.
sep : string, default '\t'
Field delimiter.
comment : str, default '#'
Indicates remainder of line should not be parsed. If found at the beginning of a line,
the line will be ignored altogether. This parameter must be a single character.
encoding : string, default 'utf-8'
Encoding to use for UTF when reading/writing (ex. `utf-8`)
skip: int, default 0
Number of lines to skip at the beginning of the file
Returns
-------
A dictionary with the same length as the number of lines in `filename` | f14919:m1 |
def build_index(): | nationalities = read_table(get_data_path('<STR_LIT>'), sep='<STR_LIT::>')<EOL>countries = read_table(<EOL>get_data_path('<STR_LIT>'), usecols=[<NUM_LIT:4>, <NUM_LIT:0>], skip=<NUM_LIT:1>)<EOL>cities = read_table(get_data_path('<STR_LIT>'), usecols=[<NUM_LIT:1>, <NUM_LIT:8>])<EOL>city_patches = read_table(get_data_path('<STR_LIT>'))<EOL>cities.update(city_patches)<EOL>Index = namedtuple('<STR_LIT>', '<STR_LIT>')<EOL>return Index(nationalities, cities, countries)<EOL> | Load information from the data directory
Returns
-------
A namedtuple with three fields: nationalities cities countries | f14919:m2 |
def cleanup(temp_name): | for filename in iglob(temp_name + '<STR_LIT:*>' if temp_name else temp_name):<EOL><INDENT>try:<EOL><INDENT>os.remove(filename)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT> | Tries to remove temp files by filename wildcard path. | f14923:m2 |
@run_once<EOL>def get_tesseract_version(): | try:<EOL><INDENT>return LooseVersion(<EOL>subprocess.check_output(<EOL>[tesseract_cmd, '<STR_LIT>'], stderr=subprocess.STDOUT<EOL>).decode('<STR_LIT:utf-8>').split()[<NUM_LIT:1>].lstrip(string.printable[<NUM_LIT:10>:])<EOL>)<EOL><DEDENT>except OSError:<EOL><INDENT>raise TesseractNotFoundError()<EOL><DEDENT> | Returns LooseVersion object of the Tesseract version | f14923:m11 |
def image_to_string(image,<EOL>lang=None,<EOL>config='<STR_LIT>',<EOL>nice=<NUM_LIT:0>,<EOL>output_type=Output.STRING): | args = [image, '<STR_LIT>', lang, config, nice]<EOL>return {<EOL>Output.BYTES: lambda: run_and_get_output(*(args + [True])),<EOL>Output.DICT: lambda: {'<STR_LIT:text>': run_and_get_output(*args)},<EOL>Output.STRING: lambda: run_and_get_output(*args),<EOL>}[output_type]()<EOL> | Returns the result of a Tesseract OCR run on the provided image to string | f14923:m12 |
def image_to_pdf_or_hocr(image,<EOL>lang=None,<EOL>config='<STR_LIT>',<EOL>nice=<NUM_LIT:0>,<EOL>extension='<STR_LIT>'): | if extension not in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(extension))<EOL><DEDENT>args = [image, extension, lang, config, nice, True]<EOL>return run_and_get_output(*args)<EOL> | Returns the result of a Tesseract OCR run on the provided image to pdf/hocr | f14923:m13 |
def image_to_boxes(image,<EOL>lang=None,<EOL>config='<STR_LIT>',<EOL>nice=<NUM_LIT:0>,<EOL>output_type=Output.STRING): | config += '<STR_LIT>'<EOL>args = [image, '<STR_LIT>', lang, config, nice]<EOL>return {<EOL>Output.BYTES: lambda: run_and_get_output(*(args + [True])),<EOL>Output.DICT: lambda: file_to_dict(<EOL>'<STR_LIT>' + run_and_get_output(*args),<EOL>'<STR_LIT:U+0020>',<EOL><NUM_LIT:0>),<EOL>Output.STRING: lambda: run_and_get_output(*args),<EOL>}[output_type]()<EOL> | Returns string containing recognized characters and their box boundaries | f14923:m14 |
def image_to_data(image,<EOL>lang=None,<EOL>config='<STR_LIT>',<EOL>nice=<NUM_LIT:0>,<EOL>output_type=Output.STRING): | if get_tesseract_version() < '<STR_LIT>':<EOL><INDENT>raise TSVNotSupported()<EOL><DEDENT>config = '<STR_LIT>'.format('<STR_LIT>', config.strip()).strip()<EOL>args = [image, '<STR_LIT>', lang, config, nice]<EOL>return {<EOL>Output.BYTES: lambda: run_and_get_output(*(args + [True])),<EOL>Output.DATAFRAME: lambda: get_pandas_output(args + [True]),<EOL>Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '<STR_LIT:\t>', -<NUM_LIT:1>),<EOL>Output.STRING: lambda: run_and_get_output(*args),<EOL>}[output_type]()<EOL> | Returns string containing box boundaries, confidences,
and other information. Requires Tesseract 3.05+ | f14923:m16 |
def image_to_osd(image,<EOL>lang='<STR_LIT>',<EOL>config='<STR_LIT>',<EOL>nice=<NUM_LIT:0>,<EOL>output_type=Output.STRING): | config = '<STR_LIT>'.format(<EOL>'<STR_LIT>' if get_tesseract_version() < '<STR_LIT>' else '<STR_LIT:->',<EOL>config.strip()<EOL>).strip()<EOL>args = [image, '<STR_LIT>', lang, config, nice]<EOL>return {<EOL>Output.BYTES: lambda: run_and_get_output(*(args + [True])),<EOL>Output.DICT: lambda: osd_to_dict(run_and_get_output(*args)),<EOL>Output.STRING: lambda: run_and_get_output(*args),<EOL>}[output_type]()<EOL> | Returns string containing the orientation and script detection (OSD) | f14923:m17 |
def run(self, host, port=<NUM_LIT>, with_ssl=False): | try:<EOL><INDENT>dns_rec = self._lookup(host, port)<EOL>self._connect(dns_rec)<EOL>if with_ssl:<EOL><INDENT>self._wrap_ssl()<EOL><DEDENT>banner = self._get_banner()<EOL>self._check_banner(banner)<EOL><DEDENT>except Exception:<EOL><INDENT>exc_type, exc_value, exc_tb = sys.exc_info()<EOL>self.results['<STR_LIT>'] = str(exc_type.__name__)<EOL>self.results['<STR_LIT>'] = str(exc_value)<EOL>self.results['<STR_LIT>'] = repr(traceback.format_exc())<EOL><DEDENT>finally:<EOL><INDENT>self._close(with_ssl)<EOL><DEDENT> | Executes a single health check against a remote host and port. This
method may only be called once per object.
:param host: The hostname or IP address of the SMTP server to check.
:type host: str
:param port: The port number of the SMTP server to check.
:type port: int
:param with_ssl: If ``True``, SSL will be initiated before attempting
to get the banner message.
:type with_ssl: bool | f14927:c4:m7 |
def output(self, stream): | for key, val in self.results.items():<EOL><INDENT>if isinstance(val, basestring):<EOL><INDENT>print >> stream, '<STR_LIT>'.format(key, val)<EOL><DEDENT>elif isinstance(val, float):<EOL><INDENT>print >> stream, '<STR_LIT>'.format(key, val)<EOL><DEDENT>elif val is None:<EOL><INDENT>print >> stream, '<STR_LIT>'.format(key)<EOL><DEDENT>else:<EOL><INDENT>print >> stream, '<STR_LIT>'.format(key, val)<EOL><DEDENT><DEDENT>if self.results['<STR_LIT>'] == '<STR_LIT:OK>':<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT> | Outputs the results of :meth:`.run` to the given stream. The results
are presented similarly to HTTP headers, where each line has a key and
value, separated by ``: ``. The ``Status`` key will always be available
in the output.
:param stream: The output file to write to.
:returns: A return code that would be appropriate to return to the
operating system, e.g. zero means success, non-zero means
failure.
:rtype: int | f14927:c4:m8 |
def tag_to_expr_class(tag): | try:<EOL><INDENT>return tag_to_expr_mapping[tag]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError('<STR_LIT>' % tag)<EOL><DEDENT> | Convert a tag string to the corresponding IRExpr class type.
:param str tag: The tag string.
:return: A class.
:rtype: type | f14937:m13 |
def enum_to_expr_class(tag_enum): | try:<EOL><INDENT>return enum_to_expr_mapping[tag_enum]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError("<STR_LIT>" % get_enum_from_int(tag_enum))<EOL><DEDENT> | Convert a tag enum to the corresponding IRExpr class.
:param int tag_enum: The tag enum.
:return: A class.
:rtype: type | f14937:m14 |
@property<EOL><INDENT>def child_expressions(self):<DEDENT> | expressions = [ ]<EOL>for k in self.__slots__:<EOL><INDENT>v = getattr(self, k)<EOL>if isinstance(v, IRExpr):<EOL><INDENT>expressions.append(v)<EOL>expressions.extend(v.child_expressions)<EOL><DEDENT><DEDENT>return expressions<EOL> | A list of all of the expressions that this expression ends up evaluating. | f14937:c0:m1 |
@property<EOL><INDENT>def constants(self):<DEDENT> | constants = [ ]<EOL>for k in self.__slots__:<EOL><INDENT>v = getattr(self, k)<EOL>if isinstance(v, IRExpr):<EOL><INDENT>constants.extend(v.constants)<EOL><DEDENT>elif isinstance(v, IRConst):<EOL><INDENT>constants.append(v)<EOL><DEDENT><DEDENT>return constants<EOL> | A list of all of the constants that this expression ends up using. | f14937:c0:m2 |
def replace_expression(self, expr, replacement): | for k in self.__slots__:<EOL><INDENT>v = getattr(self, k)<EOL>if v is expr:<EOL><INDENT>setattr(self, k, replacement)<EOL><DEDENT>elif type(v) is list:<EOL><INDENT>for i, expr_ in enumerate(v):<EOL><INDENT>if expr_ is expr:<EOL><INDENT>v[i] = replacement<EOL><DEDENT><DEDENT><DEDENT>elif type(v) is tuple:<EOL><INDENT>_lst = [ ]<EOL>replaced = False<EOL>for i, expr_ in enumerate(v):<EOL><INDENT>if expr_ is expr:<EOL><INDENT>_lst.append(replacement)<EOL>replaced = True<EOL><DEDENT>else:<EOL><INDENT>_lst.append(expr_)<EOL><DEDENT><DEDENT>if replaced:<EOL><INDENT>setattr(self, k, tuple(_lst))<EOL><DEDENT><DEDENT>elif isinstance(v, IRExpr):<EOL><INDENT>v.replace_expression(expr, replacement)<EOL><DEDENT><DEDENT> | Replace child expressions in-place.
:param IRExpr expr: The expression to look for.
:param IRExpr replacement: The expression to replace with.
:return: None | f14937:c0:m5 |
def data_ref_type_str(dref_enum): | if dref_enum == <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif dref_enum == <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>elif dref_enum == <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT> | Translate an ``enum DataRefTypes`` value into a string representation. | f14938:m0 |
@property<EOL><INDENT>def data_type_str(self):<DEDENT> | return data_ref_type_str(self.data_type)<EOL> | The data ref type as a string, "unknown" "integer" "fp" or "INVALID" | f14938:c0:m1 |
def _lift(self,<EOL>data,<EOL>bytes_offset=None,<EOL>max_bytes=None,<EOL>max_inst=None,<EOL>opt_level=<NUM_LIT:1>,<EOL>traceflags=None,<EOL>allow_arch_optimizations=None,<EOL>strict_block_end=None,<EOL>skip_stmts=False,<EOL>collect_data_refs=False): | irsb = IRSB.empty_block(self.arch, self.addr)<EOL>self.data = data<EOL>self.bytes_offset = bytes_offset<EOL>self.opt_level = opt_level<EOL>self.traceflags = traceflags<EOL>self.allow_arch_optimizations = allow_arch_optimizations<EOL>self.strict_block_end = strict_block_end<EOL>self.collect_data_refs = collect_data_refs<EOL>self.max_inst = max_inst<EOL>self.max_bytes = max_bytes<EOL>self.skip_stmts = skip_stmts<EOL>self.irsb = irsb<EOL>self.lift()<EOL>return self.irsb<EOL> | Wrapper around the `lift` method on Lifters. Should not be overridden in child classes.
:param data: The bytes to lift as either a python string of bytes or a cffi buffer object.
:param bytes_offset: The offset into `data` to start lifting at.
:param max_bytes: The maximum number of bytes to lift. If set to None, no byte limit is used.
:param max_inst: The maximum number of instructions to lift. If set to None, no instruction limit is used.
:param opt_level: The level of optimization to apply to the IR, 0-2. Most likely will be ignored in any lifter
other then LibVEX.
:param traceflags: The libVEX traceflags, controlling VEX debug prints. Most likely will be ignored in any
lifter other than LibVEX.
:param allow_arch_optimizations: Should the LibVEX lifter be allowed to perform lift-time preprocessing optimizations
(e.g., lookback ITSTATE optimization on THUMB)
Most likely will be ignored in any lifter other than LibVEX.
:param strict_block_end: Should the LibVEX arm-thumb split block at some instructions, for example CB{N}Z.
:param skip_stmts: Should the lifter skip transferring IRStmts from C to Python.
:param collect_data_refs: Should the LibVEX lifter collect data references in C. | f14941:c0:m1 |
def lift(self): | raise NotImplementedError()<EOL> | Lifts the data using the information passed into _lift. Should be overridden in child classes.
Should set the lifted IRSB to self.irsb.
If a lifter raises a LiftingException on the data, this signals that the lifter cannot lift this data and arch
and the lifter is skipped.
If a lifter can lift any amount of data, it should lift it and return the lifted block with a jumpkind of
Ijk_NoDecode, signalling to pyvex that other lifters should be used on the undecodable data. | f14941:c0:m2 |
@classmethod<EOL><INDENT>def Constant(cls, irsb_c, val, ty):<DEDENT> | assert not (isinstance(val, VexValue) or isinstance(val, IRExpr))<EOL>rdt = irsb_c.mkconst(val, ty)<EOL>return cls(irsb_c, rdt)<EOL> | Creates a constant as a VexValue
:param irsb_c: The IRSBCustomizer to use
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue | f14942:c0:m46 |
def __init__(self, bitstrm, arch, addr): | self.addr = addr<EOL>self.arch = arch<EOL>self.bitwidth = len(self.bin_format) <EOL>self.data = self.parse(bitstrm)<EOL> | Create an instance of the instruction
:param irsb_c: The IRSBCustomizer to put VEX instructions into
:param bitstrm: The bitstream to decode instructions from
:param addr: The address of the instruction to be lifted, used only for jumps and branches | f14944:c0:m0 |
def fetch_operands(self): | return []<EOL> | Get the operands out of memory or registers
Return a tuple of operands for the instruction | f14944:c0:m3 |
def lift(self, irsb_c, past_instructions, future_instructions): | self.irsb_c = irsb_c<EOL>self.mark_instruction_start()<EOL>inputs = self.fetch_operands()<EOL>retval = self.compute_result(*inputs)<EOL>vals = list(inputs) + [retval]<EOL>if retval is not None:<EOL><INDENT>self.commit_result(retval)<EOL><DEDENT>self.compute_flags(*vals)<EOL> | This is the main body of the "lifting" for the instruction.
This can/should be overriden to provide the general flow of how instructions in your arch work.
For example, in MSP430, this is:
- Figure out what your operands are by parsing the addressing, and load them into temporary registers
- Do the actual operation, and commit the result, if needed.
- Compute the flags | f14944:c0:m4 |
def commit_result(self, res): | pass<EOL> | This where the result of the operation is written to a destination.
This happens only if compute_result does not return None, and happens before compute_flags is called.
Override this to specify how to write out the result.
The results of fetch_operands can be used to resolve various addressing modes for the write outward.
A common pattern is to return a function from fetch_operands which will be called here to perform the write.
:param args: A tuple of the results of fetch_operands and compute_result | f14944:c0:m5 |
@abc.abstractmethod<EOL><INDENT>def compute_result(self, *args):<DEDENT> | pass<EOL> | This is where the actual operation performed by your instruction, excluding the calculation of flags, should be
performed. Return the VexValue of the "result" of the instruction, which may
be used to calculate the flags later.
For example, for a simple add, with arguments src and dst, you can simply write:
return src + dst:
:param args:
:return: A VexValue containing the "result" of the operation. | f14944:c0:m6 |
def compute_flags(self, *args): | pass<EOL> | Most CPU architectures have "flags" that should be computed for many instructions.
Override this to specify how that happens. One common pattern is to define this method to call specifi methods
to update each flag, which can then be overriden in the actual classes for each instruction. | f14944:c0:m7 |
def match_instruction(self, data, bitstrm): | return data<EOL> | Override this to extend the parsing functionality.
This is great for if your arch has instruction "formats" that have an opcode that has to match.
:param data:
:param bitstrm:
:return: data | f14944:c0:m8 |
def disassemble(self): | return self.addr, '<STR_LIT>', [self.rawbits]<EOL> | Return the disassembly of this instruction, as a string.
Override this in subclasses.
:return: The address (self.addr), the instruction's name, and a list of its operands, as strings | f14944:c0:m11 |
def load(self, addr, ty): | rdt = self.irsb_c.load(addr.rdt, ty)<EOL>return VexValue(self.irsb_c, rdt)<EOL> | Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue | f14944:c0:m12 |
def constant(self, val, ty): | if isinstance(val, VexValue) and not isinstance(val, IRExpr):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>rdt = self.irsb_c.mkconst(val, ty)<EOL>return VexValue(self.irsb_c, rdt)<EOL> | Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue | f14944:c0:m13 |
def get(self, reg, ty): | offset = self.lookup_register(self.irsb_c.irsb.arch, reg)<EOL>if offset == self.irsb_c.irsb.arch.ip_offset:<EOL><INDENT>return self.constant(self.addr, ty)<EOL><DEDENT>rdt = self.irsb_c.rdreg(offset, ty)<EOL>return VexValue(self.irsb_c, rdt)<EOL> | Load a value from a machine register into a VEX temporary register.
All values must be loaded out of registers before they can be used with operations, etc
and stored back into them when the instruction is over. See Put().
:param reg: Register number as an integer, or register string name
:param ty: The Type to use.
:return: A VexValue of the gotten value. | f14944:c0:m15 |
def put(self, val, reg): | offset = self.lookup_register(self.irsb_c.irsb.arch, reg)<EOL>self.irsb_c.put(val.rdt, offset)<EOL> | Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None | f14944:c0:m16 |
def put_conditional(self, cond, valiftrue, valiffalse, reg): | val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt)<EOL>offset = self.lookup_register(self.irsb_c.irsb.arch, reg)<EOL>self.irsb_c.put(val, offset)<EOL> | Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None | f14944:c0:m17 |
def store(self, val, addr): | self.irsb_c.store(addr.rdt, val.rdt)<EOL> | Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None | f14944:c0:m18 |
def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None): | to_addr_ty = None<EOL>if isinstance(to_addr, VexValue):<EOL><INDENT>to_addr_rdt = to_addr.rdt<EOL>to_addr_ty = to_addr.ty<EOL><DEDENT>elif isinstance(to_addr, int):<EOL><INDENT>to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type<EOL>to_addr = self.constant(to_addr, to_addr_ty) <EOL>to_addr_rdt = to_addr.rdt<EOL><DEDENT>elif isinstance(to_addr, RdTmp):<EOL><INDENT>to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type<EOL>to_addr_rdt = to_addr<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" + repr(type(to_addr)))<EOL><DEDENT>if not condition:<EOL><INDENT>self.irsb_c.irsb.jumpkind = jumpkind<EOL>self.irsb_c.irsb.next = to_addr_rdt<EOL><DEDENT>else:<EOL><INDENT>if ip_offset is None:<EOL><INDENT>ip_offset = self.arch.ip_offset<EOL><DEDENT>assert ip_offset is not None<EOL>negated_condition_rdt = self.ite(condition, self.constant(<NUM_LIT:0>, condition.ty), self.constant(<NUM_LIT:1>, condition.ty))<EOL>direct_exit_target = self.constant(self.addr + (self.bitwidth // <NUM_LIT:8>), to_addr_ty)<EOL>self.irsb_c.add_exit(negated_condition_rdt, direct_exit_target.rdt, jumpkind, ip_offset)<EOL>self.irsb_c.irsb.jumpkind = jumpkind<EOL>self.irsb_c.irsb.next = to_addr_rdt<EOL><DEDENT> | Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None | f14944:c0:m19 |
def ccall(self, ret_type, func_obj, args): | <EOL>from angr.engines.vex import ccall<EOL>list_args = list(args)<EOL>new_args = []<EOL>for arg in list_args:<EOL><INDENT>if isinstance(arg, VexValue):<EOL><INDENT>arg = arg.rdt<EOL><DEDENT>new_args.append(arg)<EOL><DEDENT>args = tuple(new_args)<EOL>if isinstance(func_obj, str):<EOL><INDENT>func_obj = getattr(ccall, func_obj)<EOL><DEDENT>else:<EOL><INDENT>if not hasattr(ccall, func_obj.__name__):<EOL><INDENT>setattr(ccall, func_obj.__name__, func_obj)<EOL><DEDENT><DEDENT>cc = self.irsb_c.op_ccall(ret_type, func_obj.__name__, args)<EOL>return VexValue(self.irsb_c, cc)<EOL> | Creates a CCall operation.
A CCall is a procedure that calculates a value at *runtime*, not at lift-time.
You can use these for flags, unresolvable jump targets, etc.
We caution you to avoid using them when at all possible though.
For an example of how to write and use a CCall, see gymrat/bf/lift_bf.py
:param ret_type: The return type of the CCall
:param func_obj: The function object to eventually call.
:param args: List of arguments to the function
:return: A VexValue of the result. | f14944:c0:m21 |
def irsb_postproc_flatten(irsb_old, irsb_new=None): | irsb_new = irsb_new if irsb_new is not None else IRSB(None, irsb_old.addr, irsb_old.arch)<EOL>irsb_c = IRSBCustomizer(irsb_new)<EOL>old_to_new_tmp = {}<EOL>for i, statement in enumerate(irsb_old.statements):<EOL><INDENT>if isinstance(statement, WrTmp):<EOL><INDENT>flat_expr = _flatten_and_get_expr(irsb_old, irsb_c, old_to_new_tmp, statement.data)<EOL>if isinstance(flat_expr, RdTmp):<EOL><INDENT>tmp_new = flat_expr.tmp<EOL><DEDENT>else:<EOL><INDENT>tmp_new = irsb_c.mktmp(flat_expr)<EOL><DEDENT>old_to_new_tmp[statement.tmp] = tmp_new <EOL><DEDENT>elif isinstance(statement, Put):<EOL><INDENT>flat_expr = _flatten_and_get_expr(irsb_old, irsb_c, old_to_new_tmp, statement.data)<EOL>irsb_c.put(flat_expr, statement.offset)<EOL><DEDENT>elif isinstance(statement, Store):<EOL><INDENT>flat_expr = _flatten_and_get_expr(irsb_old, irsb_c, old_to_new_tmp, statement.data)<EOL>irsb_c.store(statement.addr, flat_expr, statement.end)<EOL><DEDENT>elif isinstance(statement, IMark):<EOL><INDENT>irsb_c.imark(statement.addr, statement.len, statement.delta)<EOL><DEDENT>elif isinstance(statement, NoOp):<EOL><INDENT>irsb_c.noop()<EOL><DEDENT><DEDENT>irsb_new.next = irsb_old.next<EOL>irsb_new.jumpkind = irsb_old.jumpkind<EOL>assert irsb_new == irsb_c.irsb<EOL>assert irsb_new.typecheck()<EOL>return irsb_new<EOL> | :param irsb_old: The IRSB to be flattened
:type irsb_old: IRSB
:param irsb_new: the IRSB to rewrite the instructions of irsb_old to. If it is None a new empty IRSB will be created
:type irsb_new: IRSB
:return: the flattened IRSB
:rtype: IRSB | f14945:m1 |
def make_format_op_generator(fmt_string): | def gen(arg_types):<EOL><INDENT>converted_arg_types = list(map(get_op_format_from_const_ty, arg_types))<EOL>op = fmt_string.format(arg_t=converted_arg_types)<EOL>return op<EOL><DEDENT>return gen<EOL> | Return a function which generates an op format (just a string of the vex instruction)
Functions by formatting the fmt_string with the types of the arguments | f14946:m1 |
def add_exit(self, guard, dst, jk, ip): | self.irsb.statements.append(Exit(guard, dst.con, jk, ip))<EOL> | Add an exit out of the middle of an IRSB.
(e.g., a conditional jump)
:param guard: An expression, the exit is taken if true
:param dst: the destination of the exit (a Const)
:param jk: the JumpKind of this exit (probably Ijk_Boring)
:param ip: The address of this exit's source | f14946:c3:m8 |
def lift(data, addr, arch, max_bytes=None, max_inst=None, bytes_offset=<NUM_LIT:0>, opt_level=<NUM_LIT:1>, traceflags=<NUM_LIT:0>,<EOL>strict_block_end=True, inner=False, skip_stmts=False, collect_data_refs=False): | if max_bytes is not None and max_bytes <= <NUM_LIT:0>:<EOL><INDENT>raise PyVEXError("<STR_LIT>")<EOL><DEDENT>if not data:<EOL><INDENT>raise PyVEXError("<STR_LIT>")<EOL><DEDENT>if isinstance(data, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if isinstance(data, bytes):<EOL><INDENT>py_data = data<EOL>c_data = None<EOL>allow_arch_optimizations = False<EOL><DEDENT>else:<EOL><INDENT>if max_bytes is None:<EOL><INDENT>raise PyVEXError("<STR_LIT>")<EOL><DEDENT>c_data = data<EOL>py_data = None<EOL>allow_arch_optimizations = True<EOL><DEDENT>if opt_level < <NUM_LIT:0>:<EOL><INDENT>allow_arch_optimizations = False<EOL>opt_level = <NUM_LIT:0><EOL><DEDENT>for lifter in lifters[arch.name]:<EOL><INDENT>try:<EOL><INDENT>u_data = data<EOL>if lifter.REQUIRE_DATA_C:<EOL><INDENT>if c_data is None:<EOL><INDENT>u_data = ffi.new('<STR_LIT>' % (len(py_data) + <NUM_LIT:8>), py_data + b'<STR_LIT>' * <NUM_LIT:8>)<EOL>max_bytes = min(len(py_data), max_bytes) if max_bytes is not None else len(py_data)<EOL><DEDENT>else:<EOL><INDENT>u_data = c_data<EOL><DEDENT><DEDENT>elif lifter.REQUIRE_DATA_PY:<EOL><INDENT>if py_data is None:<EOL><INDENT>if max_bytes is None:<EOL><INDENT>l.debug('<STR_LIT>')<EOL>continue<EOL><DEDENT>u_data = ffi.buffer(c_data, max_bytes)[:]<EOL><DEDENT>else:<EOL><INDENT>u_data = py_data<EOL><DEDENT><DEDENT>try:<EOL><INDENT>final_irsb = lifter(arch, addr)._lift(u_data, bytes_offset, max_bytes, max_inst, opt_level, traceflags,<EOL>allow_arch_optimizations, strict_block_end, skip_stmts, collect_data_refs,<EOL>)<EOL><DEDENT>except SkipStatementsError:<EOL><INDENT>assert skip_stmts is True<EOL>final_irsb = lifter(arch, addr)._lift(u_data, bytes_offset, max_bytes, max_inst, opt_level, traceflags,<EOL>allow_arch_optimizations, strict_block_end, skip_stmts=False,<EOL>collect_data_refs=collect_data_refs,<EOL>)<EOL><DEDENT>break<EOL><DEDENT>except LiftingException as ex:<EOL><INDENT>l.debug('<STR_LIT>', str(ex))<EOL>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>final_irsb = IRSB.empty_block(arch,<EOL>addr,<EOL>size=<NUM_LIT:0>,<EOL>nxt=Const(const.vex_int_class(arch.bits)(addr)),<EOL>jumpkind='<STR_LIT>',<EOL>)<EOL>final_irsb.invalidate_direct_next()<EOL>return final_irsb<EOL><DEDENT>if final_irsb.size > <NUM_LIT:0> and final_irsb.jumpkind == '<STR_LIT>':<EOL><INDENT>nodecode_addr_expr = final_irsb.next<EOL>if type(nodecode_addr_expr) is Const:<EOL><INDENT>nodecode_addr = nodecode_addr_expr.con.value<EOL>next_irsb_start_addr = addr + final_irsb.size<EOL>if nodecode_addr != next_irsb_start_addr:<EOL><INDENT>final_irsb.jumpkind = '<STR_LIT>'<EOL>final_irsb.next = final_irsb.next<EOL>final_irsb.invalidate_direct_next()<EOL>return final_irsb<EOL><DEDENT><DEDENT>if skip_stmts:<EOL><INDENT>return lift(data, addr, arch,<EOL>max_bytes=max_bytes,<EOL>max_inst=max_inst,<EOL>bytes_offset=bytes_offset,<EOL>opt_level=opt_level,<EOL>traceflags=traceflags,<EOL>strict_block_end=strict_block_end,<EOL>skip_stmts=False,<EOL>collect_data_refs=collect_data_refs,<EOL>)<EOL><DEDENT>next_addr = addr + final_irsb.size<EOL>if max_bytes is not None:<EOL><INDENT>max_bytes -= final_irsb.size<EOL><DEDENT>if isinstance(data, (str, bytes)):<EOL><INDENT>data_left = data[final_irsb.size:]<EOL><DEDENT>else:<EOL><INDENT>data_left = data + final_irsb.size<EOL><DEDENT>if max_inst is not None:<EOL><INDENT>max_inst -= final_irsb.instructions<EOL><DEDENT>if (max_bytes is None or max_bytes > <NUM_LIT:0>) and (max_inst is None or max_inst > <NUM_LIT:0>) and data_left:<EOL><INDENT>more_irsb = lift(data_left, next_addr, arch,<EOL>max_bytes=max_bytes,<EOL>max_inst=max_inst,<EOL>bytes_offset=bytes_offset,<EOL>opt_level=opt_level,<EOL>traceflags=traceflags,<EOL>strict_block_end=strict_block_end,<EOL>inner=True,<EOL>skip_stmts=False,<EOL>collect_data_refs=collect_data_refs,<EOL>)<EOL>if more_irsb.size:<EOL><INDENT>final_irsb.extend(more_irsb)<EOL><DEDENT><DEDENT>elif max_bytes == <NUM_LIT:0>:<EOL><INDENT>if final_irsb.size > <NUM_LIT:0> and final_irsb.jumpkind == '<STR_LIT>':<EOL><INDENT>final_irsb.jumpkind = '<STR_LIT>'<EOL>final_irsb.next = Const(vex_int_class(arch.bits)(final_irsb.addr + final_irsb.size))<EOL><DEDENT><DEDENT><DEDENT>if not inner:<EOL><INDENT>for postprocessor in postprocessors[arch.name]:<EOL><INDENT>try:<EOL><INDENT>postprocessor(final_irsb).postprocess()<EOL><DEDENT>except NeedStatementsNotification:<EOL><INDENT>if not skip_stmts:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>postprocessor.__class__)<EOL><DEDENT>return lift(data, addr, arch,<EOL>max_bytes=max_bytes,<EOL>max_inst=max_inst,<EOL>bytes_offset=bytes_offset,<EOL>opt_level=opt_level,<EOL>traceflags=traceflags,<EOL>strict_block_end=strict_block_end,<EOL>inner=inner,<EOL>skip_stmts=False,<EOL>collect_data_refs=collect_data_refs,<EOL>)<EOL><DEDENT>except LiftingException:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>return final_irsb<EOL> | Recursively lifts blocks using the registered lifters and postprocessors. Tries each lifter in the order in
which they are registered on the data to lift.
If a lifter raises a LiftingException on the data, it is skipped.
If it succeeds and returns a block with a jumpkind of Ijk_NoDecode, all of the lifters are tried on the rest
of the data and if they work, their output is appended to the first block.
:param arch: The arch to lift the data as.
:type arch: :class:`archinfo.Arch`
:param addr: The starting address of the block. Effects the IMarks.
:param data: The bytes to lift as either a python string of bytes or a cffi buffer object.
:param max_bytes: The maximum number of bytes to lift. If set to None, no byte limit is used.
:param max_inst: The maximum number of instructions to lift. If set to None, no instruction limit is used.
:param bytes_offset: The offset into `data` to start lifting at.
:param opt_level: The level of optimization to apply to the IR, -1 through 2. -1 is the strictest
unoptimized level, 0 is unoptimized but will perform some lookahead/lookbehind
optimizations, 1 performs constant propogation, and 2 performs loop unrolling,
which honestly doesn't make much sense in the context of pyvex. The default is 1.
:param traceflags: The libVEX traceflags, controlling VEX debug prints.
.. note:: Explicitly specifying the number of instructions to lift (`max_inst`) may not always work
exactly as expected. For example, on MIPS, it is meaningless to lift a branch or jump
instruction without its delay slot. VEX attempts to Do The Right Thing by possibly decoding
fewer instructions than requested. Specifically, this means that lifting a branch or jump
on MIPS as a single instruction (`max_inst=1`) will result in an empty IRSB, and subsequent
attempts to run this block will raise `SimIRSBError('Empty IRSB passed to SimIRSB.')`.
.. note:: If no instruction and byte limit is used, pyvex will continue lifting the block until the block
ends properly or until it runs out of data to lift. | f14948:m0 |
def register(lifter, arch_name): | if issubclass(lifter, Lifter):<EOL><INDENT>l.debug("<STR_LIT>", lifter.__name__, arch_name)<EOL>lifters[arch_name].append(lifter)<EOL><DEDENT>if issubclass(lifter, Postprocessor):<EOL><INDENT>l.debug("<STR_LIT>", lifter.__name__, arch_name)<EOL>postprocessors[arch_name].append(lifter)<EOL><DEDENT> | Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor` | f14948:m1 |
def match_instruction(self, data, bitstrm): | if '<STR_LIT:c>' not in data or data['<STR_LIT:c>'] == '<STR_LIT>':<EOL><INDENT>raise ParseError("<STR_LIT>")<EOL><DEDENT> | ARM Instructions are pretty dense, so let's do what we can to weed them out | f14949:c0:m0 |
def postprocess(self): | pass<EOL> | Modify the irsb
All of the postprocessors will be used in the order that they are registered | f14952:c0:m1 |
def replace_expression(self, expression, replacement): | for k in self.__slots__:<EOL><INDENT>v = getattr(self, k)<EOL>if v is expression:<EOL><INDENT>setattr(self, k, replacement)<EOL><DEDENT>elif isinstance(v, IRExpr):<EOL><INDENT>v.replace_expression(expression, replacement)<EOL><DEDENT>elif type(v) is tuple:<EOL><INDENT>_lst = [ ]<EOL>replaced = False<EOL>for expr_ in v:<EOL><INDENT>if expr_ is expression:<EOL><INDENT>_lst.append(replacement)<EOL>replaced = True<EOL><DEDENT>else:<EOL><INDENT>_lst.append(expr_)<EOL><DEDENT><DEDENT>if replaced:<EOL><INDENT>setattr(self, k, tuple(_lst))<EOL><DEDENT><DEDENT><DEDENT> | Replace child expressions in-place.
:param IRExpr expression: The expression to look for.
:param IRExpr replacement: The expression to replace with.
:return: None | f14954:c0:m5 |
def get_type_size(ty): | m = type_str_re.match(ty)<EOL>if m is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % ty)<EOL><DEDENT>return int(m.group('<STR_LIT:size>'))<EOL> | Returns the size, in BITS, of a VEX type specifier
e.g., Ity_I16 -> 16
:param ty:
:return: | f14955:m4 |
def get_type_spec_size(ty): | m = type_tag_str_re.match(ty)<EOL>if m is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % ty)<EOL><DEDENT>return int(m.group('<STR_LIT:size>'))<EOL> | Get the width of a "type specifier"
like I16U
or F16
or just 16
(Yes, this really just takes the int out. If we must special-case, do it here.
:param tyspec:
:return: | f14955:m5 |
def __init__(self, data, mem_addr, arch, max_inst=None, max_bytes=None,<EOL>bytes_offset=<NUM_LIT:0>, traceflags=<NUM_LIT:0>, opt_level=<NUM_LIT:1>, num_inst=None, num_bytes=None, strict_block_end=False,<EOL>skip_stmts=False, collect_data_refs=False): | if max_inst is None: max_inst = num_inst<EOL>if max_bytes is None: max_bytes = num_bytes<EOL>VEXObject.__init__(self)<EOL>self.addr = mem_addr<EOL>self.arch = arch<EOL>self.statements = []<EOL>self.next = None<EOL>self._tyenv = None<EOL>self.jumpkind = None<EOL>self._direct_next = None<EOL>self._size = None<EOL>self._instructions = None<EOL>self._exit_statements = None<EOL>self.default_exit_target = None<EOL>self.data_refs = ()<EOL>self._instruction_addresses = ()<EOL>if data is not None:<EOL><INDENT>irsb = lift(data, mem_addr, arch,<EOL>max_bytes=max_bytes,<EOL>max_inst=max_inst,<EOL>bytes_offset=bytes_offset,<EOL>opt_level=opt_level,<EOL>traceflags=traceflags,<EOL>strict_block_end=strict_block_end,<EOL>skip_stmts=skip_stmts,<EOL>collect_data_refs=collect_data_refs,<EOL>)<EOL>self._from_py(irsb)<EOL><DEDENT> | :param data: The bytes to lift. Can be either a string of bytes or a cffi buffer object.
You may also pass None to initialize an empty IRSB.
:type data: str or bytes or cffi.FFI.CData or None
:param int mem_addr: The address to lift the data at.
:param arch: The architecture to lift the data as.
:type arch: :class:`archinfo.Arch`
:param max_inst: The maximum number of instructions to lift. (See note below)
:param max_bytes: The maximum number of bytes to use.
:param num_inst: Replaces max_inst if max_inst is None. If set to None as well, no instruction limit is used.
:param num_bytes: Replaces max_bytes if max_bytes is None. If set to None as well, no byte limit is used.
:param bytes_offset: The offset into `data` to start lifting at. Note that for ARM THUMB mode, both
`mem_addr` and `bytes_offset` must be odd (typically `bytes_offset` is set to 1).
:param traceflags: The libVEX traceflags, controlling VEX debug prints.
:param opt_level: The level of optimization to apply to the IR, -1 through 2. -1 is the strictest
unoptimized level, 0 is unoptimized but will perform some lookahead/lookbehind
optimizations, 1 performs constant propogation, and 2 performs loop unrolling,
which honestly doesn't make much sense in the context of pyvex. The default is 1.
:param strict_block_end: Should the LibVEX arm-thumb split block at some instructions, for example CB{N}Z.
.. note:: Explicitly specifying the number of instructions to lift (`max_inst`) may not always work
exactly as expected. For example, on MIPS, it is meaningless to lift a branch or jump
instruction without its delay slot. VEX attempts to Do The Right Thing by possibly decoding
fewer instructions than requested. Specifically, this means that lifting a branch or jump
on MIPS as a single instruction (`max_inst=1`) will result in an empty IRSB, and subsequent
attempts to run this block will raise `SimIRSBError('Empty IRSB passed to SimIRSB.')`.
.. note:: If no instruction and byte limit is used, pyvex will continue lifting the block until the block
ends properly or until it runs out of data to lift. | f14958:c0:m0 |
def extend(self, extendwith): | if self.stmts_used == <NUM_LIT:0>:<EOL><INDENT>self._from_py(extendwith)<EOL>return<EOL><DEDENT>conversion_dict = { }<EOL>invalid_vals = (<NUM_LIT>, -<NUM_LIT:1>)<EOL>new_size = self.size + extendwith.size<EOL>new_instructions = self.instructions + extendwith.instructions<EOL>new_direct_next = extendwith.direct_next<EOL>def convert_tmp(tmp):<EOL><INDENT>"""<STR_LIT>"""<EOL>if tmp not in conversion_dict:<EOL><INDENT>tmp_type = extendwith.tyenv.lookup(tmp)<EOL>conversion_dict[tmp] = self.tyenv.add(tmp_type)<EOL><DEDENT>return conversion_dict[tmp]<EOL><DEDENT>def convert_expr(expr_):<EOL><INDENT>"""<STR_LIT>"""<EOL>if type(expr_) is RdTmp:<EOL><INDENT>return RdTmp.get_instance(convert_tmp(expr_.tmp))<EOL><DEDENT>return expr_<EOL><DEDENT>for stmt_ in extendwith.statements:<EOL><INDENT>stmttype = type(stmt_)<EOL>if stmttype is WrTmp:<EOL><INDENT>stmt_.tmp = convert_tmp(stmt_.tmp)<EOL><DEDENT>elif stmttype is LoadG:<EOL><INDENT>stmt_.dst = convert_tmp(stmt_.dst)<EOL><DEDENT>elif stmttype is LLSC:<EOL><INDENT>stmt_.result = convert_tmp(stmt_.result)<EOL><DEDENT>elif stmttype is Dirty:<EOL><INDENT>if stmt_.tmp not in invalid_vals:<EOL><INDENT>stmt_.tmp = convert_tmp(stmt_.tmp)<EOL><DEDENT>for e in stmt_.args:<EOL><INDENT>convert_expr(e)<EOL><DEDENT><DEDENT>elif stmttype is CAS:<EOL><INDENT>if stmt_.oldLo not in invalid_vals: stmt_.oldLo = convert_tmp(stmt_.oldLo)<EOL>if stmt_.oldHi not in invalid_vals: stmt_.oldHi = convert_tmp(stmt_.oldHi)<EOL><DEDENT>to_replace = { }<EOL>for expr_ in stmt_.expressions:<EOL><INDENT>replacement = convert_expr(expr_)<EOL>if replacement is not expr_:<EOL><INDENT>to_replace[expr_] = replacement<EOL><DEDENT><DEDENT>for expr_, replacement in to_replace.items():<EOL><INDENT>stmt_.replace_expression(expr_, replacement)<EOL><DEDENT>self.statements.append(stmt_)<EOL><DEDENT>extendwith.next = convert_expr(extendwith.next)<EOL>self.next = extendwith.next<EOL>self.jumpkind = extendwith.jumpkind<EOL>self._size = new_size<EOL>self._instructions = new_instructions<EOL>self._direct_next = new_direct_next<EOL> | Appends an irsb to the current irsb. The irsb that is appended is invalidated. The appended irsb's jumpkind and
default exit are used.
:param extendwith: The IRSB to append to this IRSB
:vartype extendwith: :class:`IRSB` | f14958:c0:m7 |
def pp(self): | print(self._pp_str())<EOL> | Pretty-print the IRSB to stdout. | f14958:c0:m9 |
@property<EOL><INDENT>def expressions(self):<DEDENT> | for s in self.statements:<EOL><INDENT>for expr_ in s.expressions:<EOL><INDENT>yield expr_<EOL><DEDENT><DEDENT>yield self.next<EOL> | Return an iterator of all expressions contained in the IRSB. | f14958:c0:m18 |
@property<EOL><INDENT>def instructions(self):<DEDENT> | if self._instructions is None:<EOL><INDENT>if self.statements is None:<EOL><INDENT>self._instructions = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])<EOL><DEDENT><DEDENT>return self._instructions<EOL> | The number of instructions in this block | f14958:c0:m19 |
@property<EOL><INDENT>def instruction_addresses(self):<DEDENT> | if self._instruction_addresses is None:<EOL><INDENT>if self.statements is None:<EOL><INDENT>self._instruction_addresses = [ ]<EOL><DEDENT>else:<EOL><INDENT>self._instruction_addresses = [ (s.addr + s.delta) for s in self.statements if type(s) is stmt.IMark ]<EOL><DEDENT><DEDENT>return self._instruction_addresses<EOL> | Addresses of instructions in this block. | f14958:c0:m20 |
@property<EOL><INDENT>def size(self):<DEDENT> | if self._size is None:<EOL><INDENT>self._size = sum(s.len for s in self.statements if type(s) is stmt.IMark)<EOL><DEDENT>return self._size<EOL> | The size of this block, in bytes | f14958:c0:m21 |
@property<EOL><INDENT>def operations(self):<DEDENT> | ops = []<EOL>for e in self.expressions:<EOL><INDENT>if hasattr(e, '<STR_LIT>'):<EOL><INDENT>ops.append(e.op)<EOL><DEDENT><DEDENT>return ops<EOL> | A list of all operations done by the IRSB, as libVEX enum names | f14958:c0:m22 |
@property<EOL><INDENT>def all_constants(self):<DEDENT> | return sum((e.constants for e in self.expressions), [])<EOL> | Returns all constants in the block (including incrementing of the program counter) as :class:`pyvex.const.IRConst`. | f14958:c0:m23 |
@property<EOL><INDENT>def constants(self):<DEDENT> | return sum(<EOL>(s.constants for s in self.statements if not (type(s) is stmt.Put and s.offset == self.offsIP)), [])<EOL> | The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`. | f14958:c0:m24 |
@property<EOL><INDENT>def constant_jump_targets(self):<DEDENT> | exits = set()<EOL>if self.exit_statements:<EOL><INDENT>for _, _, stmt_ in self.exit_statements:<EOL><INDENT>exits.add(stmt_.dst.value)<EOL><DEDENT><DEDENT>default_target = self.default_exit_target<EOL>if default_target is not None:<EOL><INDENT>exits.add(default_target)<EOL><DEDENT>return exits<EOL> | A set of the static jump targets of the basic block. | f14958:c0:m25 |
@property<EOL><INDENT>def constant_jump_targets_and_jumpkinds(self):<DEDENT> | exits = dict()<EOL>if self.exit_statements:<EOL><INDENT>for _, _, stmt_ in self.exit_statements:<EOL><INDENT>exits[stmt_.dst.value] = stmt_.jumpkind<EOL><DEDENT><DEDENT>default_target = self.default_exit_target<EOL>if default_target is not None:<EOL><INDENT>exits[default_target] = self.jumpkind<EOL><DEDENT>return exits<EOL> | A dict of the static jump targets of the basic block to their jumpkind. | f14958:c0:m26 |
def _pp_str(self): | sa = []<EOL>sa.append("<STR_LIT>")<EOL>if self.statements is not None:<EOL><INDENT>sa.append("<STR_LIT>" % self.tyenv)<EOL><DEDENT>sa.append("<STR_LIT>")<EOL>if self.statements is not None:<EOL><INDENT>for i, s in enumerate(self.statements):<EOL><INDENT>if isinstance(s, stmt.Put):<EOL><INDENT>stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offset, s.data.result_size(self.tyenv) // <NUM_LIT:8>))<EOL><DEDENT>elif isinstance(s, stmt.WrTmp) and isinstance(s.data, expr.Get):<EOL><INDENT>stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.data.offset, s.data.result_size(self.tyenv) // <NUM_LIT:8>))<EOL><DEDENT>elif isinstance(s, stmt.Exit):<EOL><INDENT>stmt_str = s.__str__(reg_name=self.arch.translate_register_name(s.offsIP, self.arch.bits // <NUM_LIT:8>))<EOL><DEDENT>else:<EOL><INDENT>stmt_str = s.__str__()<EOL><DEDENT>sa.append("<STR_LIT>" % (i, stmt_str))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>sa.append("<STR_LIT>")<EOL><DEDENT>sa.append(<EOL>"<STR_LIT>" % (self.arch.translate_register_name(self.offsIP), self.next, self.jumpkind))<EOL>sa.append("<STR_LIT:}>")<EOL>return '<STR_LIT:\n>'.join(sa)<EOL> | Return the pretty-printed IRSB.
:rtype: str | f14958:c0:m27 |
def _is_defaultexit_direct_jump(self): | if not (self.jumpkind == '<STR_LIT>' or self.jumpkind == '<STR_LIT>' or self.jumpkind == '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>target = self.default_exit_target<EOL>return target is not None<EOL> | Checks if the default of this IRSB a direct jump or not. | f14958:c0:m28 |
def lookup(self, tmp): | if tmp < <NUM_LIT:0> or tmp > self.types_used:<EOL><INDENT>l.debug("<STR_LIT>", tmp)<EOL>raise IndexError(tmp)<EOL><DEDENT>return self.types[tmp]<EOL> | Return the type of temporary variable `tmp` as an enum string | f14958:c1:m2 |
def add(self, ty): | self.types.append(ty)<EOL>return self.types_used - <NUM_LIT:1><EOL> | Add a new tmp of type `ty` to the environment. Returns the number of the new tmp. | f14958:c1:m4 |
def _elapsed_time(begin_time, end_time): | bt = _str2datetime(begin_time)<EOL>et = _str2datetime(end_time)<EOL>return float((et - bt).seconds)<EOL> | Assuming format YYYY-MM-DD hh:mm:ss
Returns the elapsed time in seconds | f14964:m1 |
def get_password(config): | password = config.get_option('<STR_LIT>')<EOL>if password == '<STR_LIT>':<EOL><INDENT>user = config.get_option('<STR_LIT>')<EOL>url = config.get_option('<STR_LIT>')<EOL>url_obj = urllib.parse.urlparse(url)<EOL>server = url_obj.hostname<EOL>protocol = url_obj.scheme<EOL>if HAS_GNOME_KEYRING_SUPPORT:<EOL><INDENT>password = get_password_from_gnome_keyring(user, server, protocol)<EOL><DEDENT>else:<EOL><INDENT>prompt = '<STR_LIT>' % (get_app(), user,<EOL>server)<EOL>password = getpass.getpass(prompt)<EOL><DEDENT><DEDENT>return password<EOL> | Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user | f14966:m1 |
def get_fact_by_id(self, fact_id): | columns = '<STR_LIT>'<EOL>query = "<STR_LIT>"<EOL>result = self._query(query % (columns, fact_id))<EOL>if result:<EOL><INDENT>return result[<NUM_LIT:0>] <EOL><DEDENT>else:<EOL><INDENT>raise NoHamsterData('<STR_LIT>', fact_id)<EOL><DEDENT> | Obtains fact data by it's id.
As the fact is unique, it returns a tuple like:
(activity_id, start_time, end_time, description).
If there is no fact with id == fact_id, a NoHamsterData
exception will be raise | f14968:c1:m2 |
def get_activity_by_id(self, activity_id): | columns = '<STR_LIT>'<EOL>query = "<STR_LIT>"<EOL>result = self._query(query % (columns, activity_id))<EOL>if result:<EOL><INDENT>return result[<NUM_LIT:0>] <EOL><DEDENT>else:<EOL><INDENT>raise NoHamsterData('<STR_LIT>', activity_id)<EOL><DEDENT> | Obtains activity data by it's id.
As the activity is unique, it returns a tuple like:
(name, category_id). If there is no activity with
id == activity_id, a NoHamsterData exception will be raise | f14968:c1:m3 |
def get_tags_by_fact_id(self, fact_id): | if not fact_id in self.all_facts_id:<EOL><INDENT>raise NoHamsterData('<STR_LIT>', fact_id)<EOL><DEDENT>query = "<STR_LIT>"<EOL>return [self.tags[row[<NUM_LIT:0>]] for row in self._query(query % fact_id)]<EOL> | Obtains the tags associated by a fact_id.
This function returns a list of the tags name associated
to a fact, such as ['foo', 'bar', 'eggs'].
If the fact has no tags, it will return a empty list.
If there are no fact with id == fact_id, a NoHamsterData
exception will be raise | f14968:c1:m4 |
def get_all_tasks(conf): | db = HamsterDB(conf)<EOL>fact_list = db.all_facts_id<EOL>security_days = int(conf.get_option('<STR_LIT>'))<EOL>today = datetime.today()<EOL>tasks = {}<EOL>for fact_id in fact_list:<EOL><INDENT>ht = HamsterTask(fact_id, conf, db)<EOL>if ht.end_time:<EOL><INDENT>end_time = ht.get_object_dates()[<NUM_LIT:1>]<EOL>if today - timedelta(security_days) <= end_time:<EOL><INDENT>rt = ht.get_remote_task()<EOL>tasks[rt.task_id] = rt<EOL><DEDENT><DEDENT><DEDENT>db.close_connection()<EOL>print('<STR_LIT>' % len(tasks))<EOL>return tasks<EOL> | Returns a list with every task registred on Hamster. | f14970:m0 |
def copy_fields(src, to): | args = tuple(getattr(src, field.attname) for field in src._meta.fields)<EOL>return to(*args)<EOL> | Returns a new instance of `to_cls` with fields data fetched from `src`.
Useful for getting a model proxy instance from concrete model instance or
the other way around. Note that we use *arg calling to get a faster model
initialization. | f14986:m0 |
def __missing__(self, model_key): | owner = self.apps.get_model(*model_key)<EOL>if not issubclass(owner, self.model):<EOL><INDENT>raise KeyError<EOL><DEDENT>accessors = {owner: EMPTY_ACCESSOR}<EOL>with self.lock:<EOL><INDENT>for model in self.apps.get_models():<EOL><INDENT>opts = model._meta<EOL>if opts.proxy and issubclass(model, owner) and (owner._meta.proxy or opts.concrete_model is owner):<EOL><INDENT>accessors[model] = SubclassAccessor((), model, '<STR_LIT>')<EOL><DEDENT>elif opts.parents.get(owner):<EOL><INDENT>part = opts.model_name<EOL>for child, (parts, proxy, _lookup) in self[self.get_model_key(opts)].items():<EOL><INDENT>accessors[child] = SubclassAccessor((part,) + parts, proxy, LOOKUP_SEP.join((part,) + parts))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return accessors<EOL> | Generate the accessors for this model by recursively generating its
children accessors and prefixing them. | f14987:c1:m5 |
def current_request(): | return getattr(_thread_locals, REQUEST_LOCAL_KEY, None)<EOL> | Return current request for this thread.
:return: current request for this thread. | f14989:m0 |
def set_request(request): | setattr(_thread_locals, REQUEST_LOCAL_KEY, request)<EOL> | Set request for current thread.
:param request: current request. | f14989:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.