INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Caution: returns 0 when path not found
async def query_pathing( self, start: Union[Unit, Point2, Point3], end: Union[Point2, Point3] ) -> Optional[Union[int, float]]: """ Caution: returns 0 when path not found """ assert isinstance(start, (Point2, Unit)) assert isinstance(end, Point2) if isinstance(start, Point2):...
Usage: await self.query_pathings([[unit1, target2], [unit2, target2]]) -> returns [distance1, distance2] Caution: returns 0 when path not found Might merge this function with the function above
async def query_pathings(self, zipped_list: List[List[Union[Unit, Point2, Point3]]]) -> List[Union[float, int]]: """ Usage: await self.query_pathings([[unit1, target2], [unit2, target2]]) -> returns [distance1, distance2] Caution: returns 0 when path not found Might merge this function w...
Query abilities of multiple units
async def query_available_abilities( self, units: Union[List[Unit], "Units"], ignore_resource_requirements: bool = False ) -> List[List[AbilityId]]: """ Query abilities of multiple units """ if not isinstance(units, list): """ Deprecated, accepting a single unit may be removed in...
Writes a message to the chat
async def chat_send(self, message: str, team_only: bool): """ Writes a message to the chat """ ch = ChatChannel.Team if team_only else ChatChannel.Broadcast await self._execute( action=sc_pb.RequestAction( actions=[sc_pb.Action(action_chat=sc_pb.ActionChat(channel=ch....
Usage example (will spawn 1 marine in the center of the map for player ID 1): await self._client.debug_create_unit([[UnitTypeId.MARINE, 1, self._game_info.map_center, 1]])
async def debug_create_unit(self, unit_spawn_commands: List[List[Union[UnitTypeId, int, Point2, Point3]]]): """ Usage example (will spawn 1 marine in the center of the map for player ID 1): await self._client.debug_create_unit([[UnitTypeId.MARINE, 1, self._game_info.map_center, 1]]) """ assert i...
Moves camera to the target position
async def move_camera(self, position: Union[Unit, Point2, Point3]): """ Moves camera to the target position """ assert isinstance(position, (Unit, Point2, Point3)) if isinstance(position, Unit): position = position.position await self._execute( action=sc_pb.Reques...
Deprecated, may be removed soon
async def debug_text(self, texts: Union[str, list], positions: Union[list, set], color=(0, 255, 0), size_px=16): """ Deprecated, may be removed soon """ if isinstance(positions, (set, list)): if not positions: return if isinstance(texts, str): tex...
Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'.
def debug_text_simple(self, text: str): """ Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. """ self._debug_texts.append(self.to_debug_message(text))
Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'.
def debug_text_screen(self, text: str, pos: Union[Point2, Point3, tuple, list], color=None, size: int = 8): """ Draws a text on the screen with coordinates 0 <= x, y <= 1. Don't forget to add 'await self._client.send_debug'. """ assert len(pos) >= 2 assert 0 <= pos[0] <= 1 assert 0 <= po...
Draws a text at Point3 position. Don't forget to add 'await self._client.send_debug'. To grab a unit's 3d position, use unit.position3d Usually the Z value of a Point3 is between 8 and 14 (except for flying units)
def debug_text_world(self, text: str, pos: Union[Unit, Point2, Point3], color=None, size: int = 8): """ Draws a text at Point3 position. Don't forget to add 'await self._client.send_debug'. To grab a unit's 3d position, use unit.position3d Usually the Z value of a Point3 is between 8 and 14 (exc...
Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'.
def debug_line_out(self, p0: Union[Unit, Point2, Point3], p1: Union[Unit, Point2, Point3], color=None): """ Draws a line from p0 to p1. Don't forget to add 'await self._client.send_debug'. """ self._debug_lines.append( debug_pb.DebugLine( line=debug_pb.Line(p0=self.to_debug_p...
Draws a box with p_min and p_max as corners. Don't forget to add 'await self._client.send_debug'.
def debug_box_out(self, p_min: Union[Unit, Point2, Point3], p_max: Union[Unit, Point2, Point3], color=None): """ Draws a box with p_min and p_max as corners. Don't forget to add 'await self._client.send_debug'. """ self._debug_boxes.append( debug_pb.DebugBox( min=self.to_debu...
Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'.
def debug_sphere_out(self, p: Union[Unit, Point2, Point3], r: Union[int, float], color=None): """ Draws a sphere at point p with radius r. Don't forget to add 'await self._client.send_debug'. """ self._debug_spheres.append( debug_pb.DebugSphere(p=self.to_debug_point(p), r=r, color=self.to_de...
Sends the debug draw execution. Put this after your debug creation functions.
async def send_debug(self): """ Sends the debug draw execution. Put this after your debug creation functions. """ await self._execute( debug=sc_pb.RequestDebug( debug=[ debug_pb.DebugCommand( draw=debug_pb.DebugDraw( ...
Helper function for color conversion
def to_debug_color(self, color): """ Helper function for color conversion """ if color is None: return debug_pb.Color(r=255, g=255, b=255) else: r = getattr(color, "r", getattr(color, "x", 255)) g = getattr(color, "g", getattr(color, "y", 255)) b =...
Helper function for point conversion
def to_debug_point(self, point: Union[Unit, Point2, Point3]) -> common_pb.Point: """ Helper function for point conversion """ if isinstance(point, Unit): point = point.position3d return common_pb.Point(x=point.x, y=point.y, z=getattr(point, "z", 0))
Helper function to create debug texts
def to_debug_message( self, text: str, color=None, pos: Optional[Union[Point2, Point3]] = None, size: int = 8 ) -> debug_pb.DebugText: """ Helper function to create debug texts """ color = self.to_debug_color(color) pt3d = self.to_debug_point(pos) if isinstance(pos, Point3) else None...
Same as the function above, but should be 3-4 times faster because of the dropped asserts and conversions and because it doesnt use a loop (itertools or zip).
def distance_to_point2(self, p2: "Point2") -> Union[int, float]: """ Same as the function above, but should be 3-4 times faster because of the dropped asserts and conversions and because it doesnt use a loop (itertools or zip). """ return ((self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2) ** 0.5
Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process.
def _distance_squared(self, p2: "Point2") -> Union[int, float]: """ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """ return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2
This returns the target points sorted as list. You should not pass a set or dict since those are not sortable. If you want to sort your units towards a point, use 'units.sorted_by_distance_to(point)' instead.
def sort_by_distance(self, ps: Union["Units", List["Point2"]]) -> List["Point2"]: """ This returns the target points sorted as list. You should not pass a set or dict since those are not sortable. If you want to sort your units towards a point, use 'units.sorted_by_distance_to(point)' instead. """ ...
This function assumes the 2d distance is meant
def closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union["Unit", "Point2"]: """ This function assumes the 2d distance is meant """ assert ps if len(ps) == 1: return ps[0] closest_distance_squared = math.inf for p2 in ps: p2pos = p2 ...
This function assumes the 2d distance is meant
def distance_to_closest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: """ This function assumes the 2d distance is meant """ assert ps closest_distance_squared = math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2.pos...
This function assumes the 2d distance is meant
def furthest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union["Unit", "Pointlike"]: """ This function assumes the 2d distance is meant """ assert ps if len(ps) == 1: return ps[0] furthest_distance_squared = -math.inf for p2 in ps: p2pos = ...
This function assumes the 2d distance is meant
def distance_to_furthest(self, ps: Union["Units", List["Point2"], Set["Point2"]]) -> Union[int, float]: """ This function assumes the 2d distance is meant """ assert ps furthest_distance_squared = -math.inf for p2 in ps: if not isinstance(p2, Point2): p2 = p2....
Squared distance to a point.
def distance2_to(self, other: "Point2"): """Squared distance to a point.""" assert isinstance(other, Point2) return (self[0] - other[0]) ** 2 + (self[1] - other[1]) ** 2
self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding
def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]: """ self is point1, p is point2, r is the radius for circles originating in both points Used in ramp finding """ assert self != p distanceBetweenPoints = self.distance_to(p) assert r > distanceBetw...
Converts a vector to a direction that can face vertically, horizontally or diagonal or be zero, e.g. (0, 0), (1, -1), (1, 0)
def direction_vector(self, other: "Point2") -> "Point2": """ Converts a vector to a direction that can face vertically, horizontally or diagonal or be zero, e.g. (0, 0), (1, -1), (1, 0) """ return self.__class__((_sign(other.x - self.x), _sign(other.y - self.y)))
Returns the central point for points in list
def center(a: Union[Set["Point2"], List["Point2"]]) -> "Point2": """ Returns the central point for points in list """ s = Point2((0, 0)) for p in a: s += p return s / len(a)
Returns the upper points of a ramp.
def upper(self) -> Set[Point2]: """ Returns the upper points of a ramp. """ max_height = max([self.height_at(p) for p in self._points]) return {p for p in self._points if self.height_at(p) == max_height}
Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file.
def upper2_for_ramp_wall(self) -> Set[Point2]: """ Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file. """ if len(self.upper) > 5: # NOTE: this was way too slow on large ramps return set() # HAC...
Barracks position in the middle of the 2 depots
def barracks_in_middle(self) -> Point2: """ Barracks position in the middle of the 2 depots """ if len(self.upper2_for_ramp_wall) == 2: points = self.upper2_for_ramp_wall p1 = points.pop().offset((self.x_offset, self.y_offset)) p2 = points.pop().offset((self.x_offset,...
Finds the 2 depot positions on the outside
def corner_depots(self) -> Set[Point2]: """ Finds the 2 depot positions on the outside """ if len(self.upper2_for_ramp_wall) == 2: points = self.upper2_for_ramp_wall p1 = points.pop().offset((self.x_offset, self.y_offset)) # still an error with pixelmap? p2 = points....
Test if a barracks can fit an addon at natural ramp
def barracks_can_fit_addon(self) -> bool: """ Test if a barracks can fit an addon at natural ramp """ # https://i.imgur.com/4b2cXHZ.png if len(self.upper2_for_ramp_wall) == 2: return self.barracks_in_middle.x + 1 > max(self.corner_depots, key=lambda depot: depot.x).x raise Ex...
Corrected placement so that an addon can fit
def barracks_correct_placement(self) -> Point2: """ Corrected placement so that an addon can fit """ if len(self.upper2_for_ramp_wall) == 2: if self.barracks_can_fit_addon: return self.barracks_in_middle else: return self.barracks_in_middle.offset(...
Calculate (self.pathing_grid - self.placement_grid) (for sets) and then find ramps by comparing heights.
def _find_ramps(self) -> List[Ramp]: """Calculate (self.pathing_grid - self.placement_grid) (for sets) and then find ramps by comparing heights.""" rampDict = { Point2((x, y)): self.pathing_grid[(x, y)] == 0 and self.placement_grid[(x, y)] == 0 for x in range(self.pathing_grid.wi...
From a set/list of points, this function will try to group points together
def _find_groups( self, points: Set[Point2], minimum_points_per_group: int = 8, max_distance_between_points: int = 2 ) -> List[Set[Point2]]: """ From a set/list of points, this function will try to group points together """ """ Paint clusters of points in rectangular map using flood fill alg...
Splits words from CamelCase text.
def split_camel_case(text) -> list: """Splits words from CamelCase text.""" return list(reduce( lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]), text, [] ))
Tech-building requirement of buildings - may work for units but unreliably
def tech_requirement(self) -> Optional[UnitTypeId]: """ Tech-building requirement of buildings - may work for units but unreliably """ if self._proto.tech_requirement == 0: return None if self._proto.tech_requirement not in self._game_data.units: return None retur...
Building tech equality, e.g. OrbitalCommand is the same as CommandCenter
def tech_alias(self) -> Optional[List[UnitTypeId]]: """ Building tech equality, e.g. OrbitalCommand is the same as CommandCenter """ """ Building tech equality, e.g. Hive is the same as Lair and Hatchery """ return_list = [] for tech_alias in self._proto.tech_alias: if tech_a...
Building type equality, e.g. FlyingOrbitalCommand is the same as OrbitalCommand
def unit_alias(self) -> Optional[UnitTypeId]: """ Building type equality, e.g. FlyingOrbitalCommand is the same as OrbitalCommand """ if self._proto.unit_alias == 0: return None if self._proto.unit_alias not in self._game_data.units: return None """ For flying Orb...
This returns 25 for extractor and 200 for spawning pool instead of 75 and 250 respectively
def cost_zerg_corrected(self) -> "Cost": """ This returns 25 for extractor and 200 for spawning pool instead of 75 and 250 respectively """ if self.race == Race.Zerg and Attribute.Structure.value in self.attributes: # a = self._game_data.units(UnitTypeId.ZERGLING) # print(a) ...
This returns 150 minerals for OrbitalCommand instead of 550
def morph_cost(self) -> Optional["Cost"]: """ This returns 150 minerals for OrbitalCommand instead of 550 """ # Fix for BARRACKSREACTOR which has tech alias [REACTOR] which has (0, 0) cost if self.tech_alias is None or self.tech_alias[0] in {UnitTypeId.TECHLAB, UnitTypeId.REACTOR}: r...
This decorator caches the return value for one game loop, then clears it if it is accessed in a different game loop Only works on properties of the bot object because it requires access to self.state.game_loop
def property_cache_once_per_frame(f): """ This decorator caches the return value for one game loop, then clears it if it is accessed in a different game loop Only works on properties of the bot object because it requires access to self.state.game_loop """ f.frame = -1 f.cache = None @wraps(f) d...
Launch the analysis. this will start a total of `max_fetcher` threads.
def go(self): """ Launch the analysis. this will start a total of `max_fetcher` threads. """ myandro = self.settings["my"] def worker(idx, q): """ Worker Thread """ l.debug("Running worker-%d" % idx) while Tru...
This method is called in order to filer a specific app :param log: an object which corresponds to a unique app :param bytes fileraw: the raw file as bytes :rtype: a tuple with 2 elements, the return value (boolean) if it is necessary to continue the analysis and the file type
def filter_file(self, log, fileraw): """ This method is called in order to filer a specific app :param log: an object which corresponds to a unique app :param bytes fileraw: the raw file as bytes :rtype: a tuple with 2 elements, the return value (boolean) if it is necessary to ...
This method is called in order to create an Analysis object :param log: an object which corresponds to a unique app :param androguard.core.bytecodes.dvm.DalvikVMFormat dexobj: a :class:`DalvikVMFormat` object :rytpe: a :class:`~androguard.core.analysis.analysis.Analysis` object
def create_adex(self, log, dexobj): """ This method is called in order to create an Analysis object :param log: an object which corresponds to a unique app :param androguard.core.bytecodes.dvm.DalvikVMFormat dexobj: a :class:`DalvikVMFormat` object :rytpe: a :class:`~androguard...
Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path.
def build_path(graph, node1, node2, path=None): """ Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path. """ if path is None: path = [] ...
Merge the inner class(es) of a class: e.g class A { ... } class A$foo{ ... } class A$bar{ ... } ==> class A { class foo{...} class bar{...} ... }
def merge_inner(clsdict): """ Merge the inner class(es) of a class: e.g class A { ... } class A$foo{ ... } class A$bar{ ... } ==> class A { class foo{...} class bar{...} ... } """ samelist = False done = {} while not samelist: samelist = True classlist = list(clsdict.keys...
Retrieve the java type of a descriptor (e.g : I)
def get_type(atype, size=None): """ Retrieve the java type of a descriptor (e.g : I) """ res = TYPE_DESCRIPTOR.get(atype) if res is None: if atype[0] == 'L': if atype.startswith('Ljava/lang'): res = atype[1:-1].lstrip('java/lang/').replace('/', '.') el...
Return the parameters type of a descriptor (e.g (IC)V)
def get_params_type(descriptor): """ Return the parameters type of a descriptor (e.g (IC)V) """ params = descriptor.split(')')[0][1:].split() if params: return [param for param in params] return []
Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`. :param str cls_name: name of the class :param str meth_name: name of the method :param androguard.decompiler.dad.graph.Graph graph: :param str dir_name: output directory
def create_png(cls_name, meth_name, graph, dir_name='graphs2'): """ Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`. :param str cls_name: name of the class :param str meth_name: name of the method :param androguard.decompiler.dad.graph.Graph graph: :param str dir_name...
Open and read a file :param filename: filename to open and read :param binary: True if the file should be read as binary :return: bytes if binary is True, str otherwise
def read(filename, binary=True): """ Open and read a file :param filename: filename to open and read :param binary: True if the file should be read as binary :return: bytes if binary is True, str otherwise """ with open(filename, 'rb' if binary else 'r') as f: return f.read()
Format the Name type of a X509 Certificate in a human readable form. :param name: Name object to return the DN from :param short: Use short form (default: False) :param delimiter: Delimiter string or character between two parts (default: ', ') :type name: dict or :class:`asn1crypto.x509.Name` :typ...
def get_certificate_name_string(name, short=False, delimiter=', '): """ Format the Name type of a X509 Certificate in a human readable form. :param name: Name object to return the DN from :param short: Use short form (default: False) :param delimiter: Delimiter string or character between two parts...
Show color-picker dialog to select color. Qt will use the native dialog by default.
def onColorPicker(self): """ Show color-picker dialog to select color. Qt will use the native dialog by default. """ dlg = QtGui.QColorDialog(QtGui.QColor(self._color), None) # if self._color: # dlg.setCurrentColor(QtGui.QColor(self._color)) if dlg....
Analyze an android application and setup all stuff for a more quickly analysis! If session is None, no session is used at all. This is the default behaviour. If you like to continue your work later, it might be a good idea to use a session. A default session can be created by using :meth:`~get_d...
def AnalyzeAPK(_file, session=None, raw=False): """ Analyze an android application and setup all stuff for a more quickly analysis! If session is None, no session is used at all. This is the default behaviour. If you like to continue your work later, it might be a good idea to use a session....
Analyze an android dex file and setup all stuff for a more quickly analysis ! :param filename: the filename of the android dex file or a buffer which represents the dex file :type filename: string :param session: A session (Default None) :rtype: return a tuple of (sha256hash, :class:`DalvikVMFormat`, ...
def AnalyzeDex(filename, session=None): """ Analyze an android dex file and setup all stuff for a more quickly analysis ! :param filename: the filename of the android dex file or a buffer which represents the dex file :type filename: string :param session: A session (Default None) :rtype: retu...
Run the decompiler on a specific analysis :param d: the DalvikVMFormat object :type d: :class:`DalvikVMFormat` object :param dx: the analysis of the format :type dx: :class:`VMAnalysis` object :param decompiler: the type of decompiler to use ("dad", "dex2jad", "ded") :type decompiler: string
def RunDecompiler(d, dx, decompiler_name): """ Run the decompiler on a specific analysis :param d: the DalvikVMFormat object :type d: :class:`DalvikVMFormat` object :param dx: the analysis of the format :type dx: :class:`VMAnalysis` object :param decompiler: the type of decompiler to use ("...
Use jarsigner to sign an APK file. :param filename: APK file on disk to sign (path) :param keystore: path to keystore :param storepass: your keystorage passphrase
def sign_apk(filename, keystore, storepass): """ Use jarsigner to sign an APK file. :param filename: APK file on disk to sign (path) :param keystore: path to keystore :param storepass: your keystorage passphrase """ from subprocess import Popen, PIPE, STDOUT # TODO use apksigner instead...
Return a filename version, which has no characters in it which are forbidden. On Windows these are for example <, /, ?, ... The intention of this function is to allow distribution of files to different OSes. :param filename: string to clean :param unique: check if the filename is already taken and app...
def clean_file_name(filename, unique=True, replace="_", force_nt=False): """ Return a filename version, which has no characters in it which are forbidden. On Windows these are for example <, /, ?, ... The intention of this function is to allow distribution of files to different OSes. :param filena...
Load the Permissions for the given apilevel. The permissions lists are generated using this tool: https://github.com/U039b/aosp_permissions_extraction Has a fallback to select the maximum or minimal available API level. For example, if 28 is requested but only 26 is available, 26 is returned. If 5 is ...
def load_permissions(apilevel, permtype='permissions'): """ Load the Permissions for the given apilevel. The permissions lists are generated using this tool: https://github.com/U039b/aosp_permissions_extraction Has a fallback to select the maximum or minimal available API level. For example, if 28...
Load the API/Permission mapping for the requested API level. If the requetsed level was not found, None is returned. :param apilevel: integer value of the API level, i.e. 24 for Android 7.0 :return: a dictionary of {MethodSignature: [List of Permissions]}
def load_permission_mappings(apilevel): """ Load the API/Permission mapping for the requested API level. If the requetsed level was not found, None is returned. :param apilevel: integer value of the API level, i.e. 24 for Android 7.0 :return: a dictionary of {MethodSignature: [List of Permissions]}...
Split IfNodes in two nodes, the first node is the header node, the second one is only composed of the jump condition.
def split_if_nodes(graph): """ Split IfNodes in two nodes, the first node is the header node, the second one is only composed of the jump condition. """ node_map = {n: n for n in graph} to_update = set() for node in graph.nodes[:]: if node.type.is_cond: if len(node.get_in...
Simplify the CFG by merging/deleting statement nodes when possible: If statement B follows statement A and if B has no other predecessor besides A, then we can merge A and B into a new statement node. We also remove nodes which do nothing except redirecting the control flow (nodes which only contains a ...
def simplify(graph): """ Simplify the CFG by merging/deleting statement nodes when possible: If statement B follows statement A and if B has no other predecessor besides A, then we can merge A and B into a new statement node. We also remove nodes which do nothing except redirecting the control f...
Dominator algorithm from Lengauer-Tarjan
def dom_lt(graph): """Dominator algorithm from Lengauer-Tarjan""" def _dfs(v, n): semi[v] = n = n + 1 vertex[n] = label[v] = v ancestor[v] = 0 for w in graph.all_sucs(v): if not semi[w]: parent[w] = v n = _dfs(w, n) pred[w]...
Breadth first search Yields all nodes found from the starting point :param start: start node
def bfs(start): """ Breadth first search Yields all nodes found from the starting point :param start: start node """ to_visit = [start] visited = {start} while to_visit: node = to_visit.pop(0) yield node if node.exception_analysis: for _, _, exceptio...
Constructs a CFG :param androguard.core.analysis.analysis.DVMBasicBlock start_block: The startpoint :param vmap: variable mapping :param exceptions: list of androguard.core.analysis.analysis.ExceptionAnalysis :rtype: Graph
def construct(start_block, vmap, exceptions): """ Constructs a CFG :param androguard.core.analysis.analysis.DVMBasicBlock start_block: The startpoint :param vmap: variable mapping :param exceptions: list of androguard.core.analysis.analysis.ExceptionAnalysis :rtype: Graph """ bfs_block...
Remove the node from the graph, removes also all connections. :param androguard.decompiler.dad.node.Node node: the node to remove
def remove_node(self, node): """ Remove the node from the graph, removes also all connections. :param androguard.decompiler.dad.node.Node node: the node to remove """ preds = self.reverse_edges.get(node, []) for pred in preds: self.edges[pred].remove(node) ...
Number the nodes in reverse post order. An RPO traversal visit as many predecessors of a node as possible before visiting the node itself.
def compute_rpo(self): """ Number the nodes in reverse post order. An RPO traversal visit as many predecessors of a node as possible before visiting the node itself. """ nb = len(self.nodes) + 1 for node in self.post_order(): node.num = nb - node.po ...
Yields the :class`~androguard.decompiler.dad.node.Node`s of the graph in post-order i.e we visit all the children of a node before visiting the node itself.
def post_order(self): """ Yields the :class`~androguard.decompiler.dad.node.Node`s of the graph in post-order i.e we visit all the children of a node before visiting the node itself. """ def _visit(n, cnt): visited.add(n) for suc in self.all_sucs(n): ...
Writes the current graph as a PNG file :param str name: filename (without .png) :param str dname: directory of the output png :param draw_branches: :return:
def draw(self, name, dname, draw_branches=True): """ Writes the current graph as a PNG file :param str name: filename (without .png) :param str dname: directory of the output png :param draw_branches: :return: """ from pydot import Dot, Edge impor...
Parse the AndroidManifest.xml. Parsing is either direct or from a given APK and prints in XML format or saves to file. This tool can also be used to process any AXML encoded file, for example from the layout directory. Example: \b $ androguard axml AndroidManifest.xml
def axml(input_, output, file_, resource): """ Parse the AndroidManifest.xml. Parsing is either direct or from a given APK and prints in XML format or saves to file. This tool can also be used to process any AXML encoded file, for example from the layout directory. Example: \b ...
Decode resources.arsc either directly from a given file or from an APK. Example: \b $ androguard arsc app.apk
def arsc(input_, file_, output, package, locale, type_, id_, list_packages, list_locales, list_types): """ Decode resources.arsc either directly from a given file or from an APK. Example: \b $ androguard arsc app....
Create a call graph and export it into a graph format. classnames are found in the type "Lfoo/bar/bla;". Example: \b $ androguard cg APK
def cg(output, show, verbose, classname, methodname, descriptor, accessflag, no_isolated, apk): """ Create a call graph and export it into a graph format. classnames are found in the type "Lfoo/bar/bla;". Example: \b $ androguard cg ...
Decompile an APK and create Control Flow Graphs. Example: \b $ androguard resources.arsc
def decompile(input_, file_, output, format_, jar, limit, decompiler): """ Decompile an APK and create Control Flow Graphs. Example: \b $ androguard resources.arsc """ from androguard import session if file_ and input_: print("Can not give --input and positional argument! "...
Return the fingerprint(s) of all certificates inside an APK.
def sign(hash_, print_all_hashes, show, apk): """Return the fingerprint(s) of all certificates inside an APK.""" androsign_main(apk, hash_, print_all_hashes, show)
Return the packageName/versionCode/versionName per APK as JSON.
def apkid(apks): """Return the packageName/versionCode/versionName per APK as JSON.""" import json import logging logging.getLogger("androguard.axml").setLevel(logging.ERROR) results = dict() for apk in apks: results[apk] = androguard.core.bytecodes.apk.get_apkid(apk) print(json.dump...
Load a module by name and search path Returns None if Module could not be loaded.
def load_module(module_name, file_path): """ Load a module by name and search path Returns None if Module could not be loaded. """ if sys.version_info >= (3,5,): import importlib.util spec = importlib.util.spec_from_file_location(module_name, file_path) if not spec: ...
Helper function called by any window to display a message in status bar.
def showStatus(self, msg): """Helper function called by any window to display a message in status bar. """ log.debug(msg) self.statusBar().showMessage(msg)
User clicked Save menu. Display a Dialog to ask whwre to save.
def saveFile(self): """User clicked Save menu. Display a Dialog to ask whwre to save.""" filepath, _ = QtWidgets.QFileDialog.getSaveFileName( self, "Save File", '', "Androguard Session (*.ag)") if filepath: # Ensure .ag as file ending if not filepath.endswith...
Save androguard session.
def saveSession(self, filepath): """Save androguard session.""" try: session_module.Save(self.session, filepath) except RuntimeError as e: log.exception(e) os.remove(filepath) log.warning("Session not saved")
Setup empty Tree at startup.
def setupEmptyTree(self): """Setup empty Tree at startup. """ if hasattr(self, "tree"): del self.tree self.tree = QtWidgets.QTreeWidget(self) self.tree.header().close()
Setup empty Dock at startup.
def setupDock(self): """Setup empty Dock at startup. """ self.dock = QtWidgets.QDockWidget("Classes", self) self.dock.setWidget(self.tree) self.dock.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)
Setup empty window supporting tabs at startup.
def setupCentral(self): """Setup empty window supporting tabs at startup. """ self.central = TabsWindow(self.bin_windows, self) self.setCentralWidget(self.central)
Main function to open a decompile source window It checks if it already opened and open that tab, otherwise, initialize a new window.
def openSourceWindow(self, current_class, method=None): """Main function to open a decompile source window It checks if it already opened and open that tab, otherwise, initialize a new window. """ log.debug("openSourceWindow for %s" % current_class) sourcewin = sel...
Convert a object or primitive name into androguard syntax For example: byte --> B foo.bar.bla --> Lfoo/bar/bla; [int --> [I There is also a special case, where some arrays are specified differently: B[] --> [B foo.bar.bla[] --> [Lfoo/bar/bla; :param n: :return:
def name_to_androguard(n): """ Convert a object or primitive name into androguard syntax For example: byte --> B foo.bar.bla --> Lfoo/bar/bla; [int --> [I There is also a special case, where some arrays are specified differently: B[] --> [B foo.bar.bla[] --> [Lf...
Converts a line of axplorer format into androguard method signature + permission :param s: :return:
def convert_name(s): """ Converts a line of axplorer format into androguard method signature + permission :param s: :return: """ m = re.compile(r"^(.*)\.(.*)\((.*)\)(.*) :: (.*)$") res = m.search(s) if res: clname, methodname, all_args, ret, perm = res.groups() args = "...
Generate the permission mappings from a axplorer root dir into a given folder. For each API Level, separate json file will be created. :param axplorerdir: path to the axplorer dir :param outfolder: path to the folder where the resulting json files are put
def generate_mappings(axplorerdir="libraries/axplorer", outfolder="androguard/core/api_specific_resources"): """ Generate the permission mappings from a axplorer root dir into a given folder. For each API Level, separate json file will be created. :param axplorerdir: path to the axplorer dir :param...
Return the :class:`DvClass` with the given name The name is partially matched against the known class names and the first result is returned. For example, the input `foobar` will match on Lfoobar/bla/foo; :param str class_name: :return: the class matching on the name :rtype: Dv...
def get_class(self, class_name): """ Return the :class:`DvClass` with the given name The name is partially matched against the known class names and the first result is returned. For example, the input `foobar` will match on Lfoobar/bla/foo; :param str class_name: :retu...
Process all classes inside the machine. This calls :meth:`~androgaurd.decompiler.dad.decompile.DvClass.process` on each :class:`DvClass`.
def process(self): """ Process all classes inside the machine. This calls :meth:`~androgaurd.decompiler.dad.decompile.DvClass.process` on each :class:`DvClass`. """ for name, klass in self.classes.items(): logger.debug('Processing class: %s', name) if isi...
Run :meth:`process` and :meth:`show_source` after each other.
def process_and_show(self): """ Run :meth:`process` and :meth:`show_source` after each other. """ for name, klass in sorted(self.classes.items()): logger.debug('Processing class: %s', name) if not isinstance(klass, DvClass): klass = DvClass(klass, ...
Disable colors from the output (color = normal)
def disable_colors(): """ Disable colors from the output (color = normal)""" for i in CONF["COLORS"]: if isinstance(CONF["COLORS"][i], dict): for j in CONF["COLORS"][i]: CONF["COLORS"][i][j] = Color.normal else: CONF["COLORS"][i] = Color.normal
Processes each class with AST enabled and returns a dictionary with all single ASTs Classnames as keys. :return: an dictionary for all classes :rtype: dict
def get_ast(self): """ Processes each class with AST enabled and returns a dictionary with all single ASTs Classnames as keys. :return: an dictionary for all classes :rtype: dict """ ret = dict() for name, cls in sorted(self.classes.items()): ...
Remove colors from the output (no escape sequences)
def remove_colors(): """ Remove colors from the output (no escape sequences)""" for i in CONF["COLORS"]: if isinstance(CONF["COLORS"][i], dict): for j in CONF["COLORS"][i]: CONF["COLORS"][i][j] = "" else: CONF["COLORS"][i] = ""
Returns a string that describes the type of file, for common Android specific formats
def is_android_raw(raw): """ Returns a string that describes the type of file, for common Android specific formats """ val = None # We do not check for META-INF/MANIFEST.MF, # as you also want to analyze unsigned APKs... # AndroidManifest.xml should be in every APK. # classes.dex an...
enable log messages on stdout We will catch all messages here! From all loggers...
def show_logging(level=logging.INFO): """ enable log messages on stdout We will catch all messages here! From all loggers... """ logger = logging.getLogger() h = logging.StreamHandler(stream=sys.stderr) h.setFormatter(logging.Formatter(fmt="[%(levelname)-8s] %(name)s: %(message)s")) l...
Recursivly delete a directory :param directory: directory to remove
def rrmdir(directory): """ Recursivly delete a directory :param directory: directory to remove """ for root, dirs, files in os.walk(directory, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root,...
turn something like "#000000" into 0,0,0 or "#FFFFFF into "255,255,255"
def make_color_tuple(color): """ turn something like "#000000" into 0,0,0 or "#FFFFFF into "255,255,255" """ R = color[1:3] G = color[3:5] B = color[5:7] R = int(R, 16) G = int(G, 16) B = int(B, 16) return R, G, B
wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such)
def color_range(startcolor, goalcolor, steps): """ wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such) """ start_tuple = make_color_tuple(startcolor) goal_tuple = make_color_tuple(goalcolor) return interpolate_tuple(start_tuple, goal_tuple, steps)
Load the module from the JSON files and return a dict, which might be empty if the resource could not be loaded. If no api version is given, the default one from the CONF dict is used. :param resource_name: Name of the resource to load :param api: API version :return: dict
def load_api_specific_resource_module(resource_name, api=None): """ Load the module from the JSON files and return a dict, which might be empty if the resource could not be loaded. If no api version is given, the default one from the CONF dict is used. :param resource_name: Name of the resource to...
qp.drawLine(self.fontWidth*(len(pos) + 1) + 15, 0, self.fontWidth*(len(pos) + 1) + 15, 50) qp.drawLine(self.fontWidth*(len(pos + sd) + 1) + 3*15, 0, self.fontWidth*(len(pos + sd) + 1) + 3*15, 50) qp.drawLine(self.fontWidth*(len(pos + sd + sq) + 1) + 5*15, 0, self.fontWidth*(len(pos + sd + sq) + 1) + 5*1...
def draw(self): qp = QtGui.QPainter() qp.begin(self.qpix) qp.fillRect(0, 0, self.width, self.height, self.backgroundBrush) qp.setPen(self.textPen) qp.setFont(self.font) cemu = ConsoleEmulator(qp, self.height // self.fontHeight, self.width // self.fontWidth) dwo...