code
stringlengths
1
1.72M
language
stringclasses
1 value
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' from message import Message class State(object): ''' Classe que mantém o estado entre a máquina em questão e uma outra. Nesse sentido, o State mantém o estado de uma comunicação cliente-servidor. Sendo assim, é necessário guardar o id do cliente o qual está ocorrendo a comunicação e o último número de sequência recebido (last_sequence). ''' def __init__(self): ''' Constructor ''' self.message = Message(None,None,-1,-1,None) self.data = None def __str__(self): return str(self.message) + ' ' + str(self.data) def isEmpty(self): return self.message.isEmpty() and (self.data == 'None')
Python
# -*- coding: utf-8 -*- ''' Created on 12/07/2010 @author: Douglas ''' from messenger import Messenger import coordinator import sys from consts import Consts from state import State from message import Message class Servidor(object): ''' classdocs ''' def __init__(self, isPassive): self.isPassive = isPassive def start(self): ''' Inicialização de TF: ''' coord = coordinator.Coordinator() coord.id = 'Server' messenger = Messenger() coordinator.init_FenixSD(messenger, coord) if not self.isPassive: coord.setActive() else: coord.setPassive() clientList = {} while(True): print 'Esperando requisições...' message = messenger.receive() #print 'Servidor: recebi: ' + str(message) data, client = message.data, message.sender clientList = coord.stateListToClientList() #print 'Servidor: retornou o clientList: ' + str(clientList) if not (client in clientList): #print 'Servidor: novo cliente' clientList[client] = 0 #cria o cliente print 'Processando requisição do cliente '+ str(client) clientList[client] += int(data) state = State() state.message = message state.data = clientList[client] #print 'Servidor: state: ' + str(state) coord.refreshState(state) print 'Salvando estado do cliente: ' + str(state.message.sender) + ' acumulador = ' + str(state.data) coord.sendState(message) print 'Enviando resposta para ' + str(client) messenger.send(client, str(clientList[client])) if __name__ == '__main__': if len(sys.argv) < 2: print 'Parâmetros: a/p - ativo/passivo' else: servidor = Servidor(sys.argv[1] == 'p') servidor.start()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' from message import Message from messenger import Messenger from consts import Consts from threading import Timer from state import State def init_FenixSD(messenger,coordinator): ''' Função para fazer as classes se conhecerem ''' messenger.coordinator = coordinator coordinator.messenger = messenger class Coordinator(object): ''' Classe estática (não em constructor). ''' PASSIVE = 0 ACTIVE = 1 stateList = [] _mode = PASSIVE #indefinido inicialmentes id = None #id da máquina active_timer = None passive_timer = None def setActive(self): self._mode = self.ACTIVE if self.id == Consts.SERVER_NAME: self.setActiveTimer() def setActiveTimer(self): if self.active_timer != None: self.active_timer.cancel() del self.active_timer self.active_timer = Timer(Consts.TIMEOUT_ACTIVE,self.heartbeat) self.active_timer.start() def setPassiveTimer(self): if self.passive_timer != None: self.passive_timer.cancel() del self.passive_timer self.passive_timer = Timer(Consts.TIMEOUT_PASSIVE,self.assumeControl) self.passive_timer.start() def setPassive(self): self._mode = self.PASSIVE self.setPassiveTimer() def assumeControl(self): print '|--------------------------|' print '| Assumindo o controle! |' print '|--------------------------|' self.passive_timer.cancel() self.setActive() def heartbeat(self): #print 'Enviando heartbeat' state = State() self.messenger.send(self.id, str(state),Message.STATE_MESSAGE) self.setActiveTimer() def refreshState(self, state): """ Salva o estado na lista de states """ if not state.isEmpty(): stateListAux = [] for s in self.stateList: if s != None: if s.message.sender != state.message.sender: stateListAux.append(s) #if len(stateListAux) == len(self.stateList): #print 'Estado de Cliente novo detectado' stateListAux.append(state) self.stateList = stateListAux #print 'State inserido na lista' #else: #print 'Mensagem era um heartbeat' #zerar o timer do passivo, aqui def sendState(self, message): """ Como vamos salvar o estado, logo em seguida, resetamos o timer para evitar o envio de um State nulo. """ if self.id == Consts.SERVER_NAME and self._mode == self.ACTIVE: self.setActiveTimer() """ Para salvar o estado, temos que procurar o id do cliente correspondente. """ state = None for s in self.stateList: if s != None: if s.message.sender == message.sender: state = s break if state != None: """ Devemos enviar o estado mais atual do cliente agora, antes de processar. """ #print ' LISTA DE ESTADOS' #for stt in self.stateList: #print ' ' + str(stt) #print 'Enviando State do sendState: ' + str(state) self.messenger.send(self.id, str(state),Message.STATE_MESSAGE) #self.messenger.receiveAck() def stateListToClientList(self): clientList = {} for state in self.stateList: clientList[state.message.sender] = int(state.data) #print clientList return clientList def processMessage(self, message): if message.receiver != self.id: #print 'Msg não era para mim!' return self.messenger.receive() if message.msg_type == Message.STATE_MESSAGE: """ A maquina passiva recebe um estado. """ #print 'Processando uma mensagem STATE' if self._mode == self.ACTIVE: #print 'Ignorando STATE enviado' return self.messenger.receive() #print 'Recebido msg: ' + str(message) #if message.data == 'None' or int(message.data) == 0: # As vezes retorna o heartbeat como 0 ou como None # print 'Recebido heartbeat' #else: state = self.messenger.stringToState(message.data) print 'Salvando estado do cliente: ' + str(state.message.sender) + ' acumulador = ' + str(state.data) #print 'state convertido:' + str(state) self.refreshState(state) #Reinicia o contador para assumir o controle: self.setPassiveTimer() #print ' LISTA DE ESTADOS' #for stt in self.stateList: #print ' ' + str(stt) """ Envia msg de ACK """ #print 'Enviando ACK para a máquina ativa' self.messenger.send(self.id, str(None),Message.ACK_MESSAGE) return self.messenger.receive() #volta a escutar elif message.msg_type == Message.NORMAL_MESSAGE: """ A máquina ativa ou passiva receberam uma mensagem """ #print 'Processando mensagem NORMAL' if self._mode == self.PASSIVE: #A máquina passiva recebe mensagens, mas as ignora. #print 'Ignorando mensagem' return self.messenger.receive() #volta a escutar #Descobrir se o número de seq já existe for stt in self.stateList: if message.sender == stt.message.sender: if message.sequence <= stt.message.sequence: self.messenger.send(message.sender, str(message),Message.NORMAL_MESSAGE) print 'Duplicata' return self.messenger.receive() #volta a escutar elif message.msg_type == Message.ACK_MESSAGE: #print 'Processando uma mensagem ACK' if self._mode == self.ACTIVE: #print 'Recebi ACK da passiva' pass else: #zerar contador do reenvio do principal #print 'Ignorando ACK enviado' pass return self.messenger.receive() #volta a escutar else: raise Exception("Tipo de mensagem desconhecido: " + message.msg_type) return message
Python
''' Created on 13/07/2010 @author: Rondon ''' import unittest from messenger import Messenger from message import Message class Test(unittest.TestCase): def testMessenger(self): msg = Message(None,None,None,None,None) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testMessenger'] unittest.main()
Python
# -*- coding: utf-8 -*- ''' Created on Jul 12, 2010 @author: Giulio ''' from messenger import Messenger from consts import Consts import coordinator import sys import random import time from message import Message from state import State class Cliente(object): ''' classdocs ''' def __init__(self, isPassive): self.isPassive = isPassive self.serverID = 'Server' self.id = '' def start(self): ''' Inicialização de TF: ''' print 'Cliente: Inicializando...' #coord = coordinator.Coordinator(Consts.CORDINATOR_TYPE[0]) coord = coordinator.Coordinator() coord.id = self.id messenger = Messenger() coordinator.init_FenixSD(messenger, coord) if not self.isPassive: coord.setActive() else: coord.setPassive() while(True): sys.stdin.readline() print 'Cliente: enviando requisição' message = str(5) """ state = State() state.message = Message(sender=self.id, \ receiver=self.serverID, \ sequence=seq, \ msg_type=message.REQUEST, \ data=message) state.data = message coord.refreshState(state) """ messenger.prepare() messenger.send(self.serverID, message) print 'Cliente: esperando resposta...' message = messenger.receive(True) resp, id = message.data, message.sender print 'Cliente: resposta = ' + str(resp) + ' ' + str(id) #time.sleep(int(random.random() * 5 + 1)) #espera de 1 a 5 segundos #time.sleep(int(random.random() + 1)) #espera de 1 a 5 segundos if __name__ == '__main__': if len(sys.argv) < 3: print 'Parâmetro 1: a/p - ativo/passivo' print 'Parâmetro 2: nome do cliente' else: cliente = Cliente(sys.argv[1] == 'p') cliente.id = sys.argv[2] cliente.start()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' class Message(object): ''' classdocs ''' #Tipos de mensagem NORMAL_MESSAGE = 0 #a mensagem deve ser repassada para a aplicação STATE_MESSAGE = 1 #a mensagem carrega um State em data ACK_MESSAGE = 2 #mensagem de confirmação de recebimento de um State vindo do servidor Principal para o Secundário def __init__(self, sender, receiver, sequence, msg_type, data): ''' Constructor ''' self.sender = sender self.receiver = receiver self.sequence = sequence self.msg_type = msg_type self.data = data def __str__(self): return str(self.msg_type) + ' ' + str(self.sender) + ' ' + str(self.receiver) + ' ' + str(self.sequence) + ' ' + str(self.data) def isEmpty(self): return (self.sender == 'None') and (self.receiver == 'None') and (self.sequence < 0) \ and (self.msg_type < 0) and (self.data == 'None')
Python
''' Created on Jul 12, 2010 @author: Giulio ''' class Consts(object): GROUPS = {'Rodrigo':'226.0.0.1','Vinicius':'226.0.0.2','Giulio':'226.0.0.3','Douglas':'226.0.0.4',\ 'Matheus':'226.0.0.5','Carlos':'226.0.0.6','Server':'225.0.0.1'} TIMEOUT_ACTIVE = 15 TIMEOUT_PASSIVE = 25 SERVER_NAME = 'Server'
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' class Controller(object): ''' classdocs ''' def __init__(self): ''' Constructor '''
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' import sys, socket, struct from message import Message from state import State import exceptions from consts import Consts from threading import Timer from threading import Lock class Messenger(object): ''' Classe estática É a entidade que faz interface com o programador da aplicação. Ele envia as mensagens com o send e receive, e por baixo dos panos, o Messenger conversa com o Coordinator para saber o que fazer. Quando o programa da aplicação envia uma mensagem (que é uma String) através do send, o Messenger precisa adicionar o header de tolerância a falhas na mensagem, criando um objeto do tipo Message. Isso é feito através do método _insertHeader. A operação inversa (transformar um Message em String) é feita pelo _removeHeader. Além disso, para preencher essas informações, o Messenger precisa se comunicar com o Coordinator para poder obter a última sequencia recebida de um cliente. ''' port = 1905 timeout = 5 #timeout em segundos next_sequence = 0 resendList = [] #lista de mensagens a serem reenviadas send_mutex = Lock() resendList_mutex = Lock() def __init__(self, coordinator): """ Inicia o socket para recebimento. Caso o socket não seja iniciado apenas uma vez, não haverá fila no sistema de comunicação """ self.coordinator = coordinator self.fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind udp port self.fd.bind(('', self.port)) multicast = Consts.GROUPS[self.coordinator.id] if multicast == None: raise Exception('ID da maquina nao pertence a nenhum grupo multicast: ' + str(self.coordinator.id)) mreq = struct.pack('4sl', socket.inet_aton(multicast), socket.INADDR_ANY) self.fd.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) def stringToMessage(self, string): """ Campos da mensagem: Type Sender Receiver Sequence Data """ fields = string.split() return Message(sender=fields[1], \ receiver=fields[2], \ sequence=int(fields[3]), \ msg_type=int(fields[0]), \ data=fields[4]) def messageToString(self, message): return str(message) def getNextSeq(self, id): for state in self.coordinator.stateList: if state.message.sender == id: return state.message.sequence + 1 return 0 def stringToState(self, string): """ Campos do state: Message Data """ if string == "None": return None fields = string.split() state = State() state.message = self.stringToMessage(fields[0]) state.data = fields[1] return State def resend(self, msg): print 'Reenviando mensagem' multicast = Consts.GROUPS[msg.receiver] if multicast == None: raise Exception('Destino desconhecido: ' + str(msg.receiver)) self.send_mutex.acquire() fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(str(msg), (multicast, self.port)) fd.close() self.send_mutex.release() def send(self, destination, message, type=Message.NORMAL_MESSAGE): if destination != None and message != None: msg = Message(sender=self.coordinator.id, \ receiver=destination,\ sequence=self.next_sequence, \ msg_type=type, \ data=message) if type == Message.NORMAL_MESSAGE: #o reenvio eh somente para msgs normais self.resendList_mutex.acquire() self.resendList.append(msg) self.resendList_mutex.release() multicast = Consts.GROUPS[destination] if multicast == None: raise Exception('Destino desconhecido: ' + str(destination)) self.send_mutex.acquire() fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) fd.sendto(str(msg), (multicast, self.port)) fd.close() self.send_mutex.release() else: raise Exception('destino ou mensagem são nulos') def receive(self, useTimeout=False): ''' Retorna (mensagem, origem) quando a mensagem chega dentro do timeout E retornar um erro quando o timeout chega ao fim ''' if useTimeout: self.fd.settimeout(self.timeout) else: self.fd.settimeout(None) try: data, addr = self.fd.recvfrom(1024) except Exception as inst: if useTimeout: #timeout implica reenvio self.resendList_mutex.acquire() msg = self.resendList[0] #pega o primeiro da "fila" self.resendList_mutex.release() self.resend(msg) #parar depois de N tentativas (falta implementar) return self.receive(useTimeout) else: #saiu uma excessão e não estavamos no modo timeout raise inst #sobe a excessão if useTimeout: #timeout implica reenvio self.resendList_mutex.acquire() self.resendList.pop() #recebeu com sucesso, remove da lista self.resendList_mutex.release() msg_rec = self.stringToMessage(data) #return msg_rec.data, msg_rec.sender return self.coordinator.processMessage(msg_rec) def prepare(self): self.next_sequence += 1 print 'NextSequence = ' + str(self.next_sequence) def __del__(self): self.fd.close()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' class State(object): ''' Classe que mantém o estado entre a máquina em questão e uma outra. Nesse sentido, o State mantém o estado de uma comunicação cliente-servidor. Sendo assim, é necessário guardar o id do cliente o qual está ocorrendo a comunicação e o último número de sequência recebido (last_sequence). ''' def __init__(self): ''' Constructor ''' self.message = None self.data = None def __str__(self): return str(self.message) + ' ' + str(self.data)
Python
# -*- coding: utf-8 -*- ''' Created on 12/07/2010 @author: Douglas ''' from messenger import Messenger import coordinator import sys from consts import Consts from state import State from message import Message class Servidor(object): ''' classdocs ''' def __init__(self, isPassive): self.isPassive = isPassive def start(self): ''' Inicialização de TF: ''' coord = coordinator.Coordinator() coord.id = 'Server' messenger = Messenger(coord) coordinator.init_FenixSD(messenger, coord) if not self.isPassive: coord.setActive() else: coord.setPassive() clientList = {} while(True): print 'Servidor: esperando requisições...' message = messenger.receive() data, client = message.data, message.sender if not (client in clientList): print 'Servidor: novo cliente' clientList[client] = 0 #cria o cliente print 'Servidor: processando requisição' clientList[client] += int(data) print 'Servidor: enviando resposta para ' + str(client) state = State() state.message = message state.data = clientList[client] print 'Servidor: salvando estado: ' + str(state) coord.refreshState(state) messenger.send(client, str(clientList[client])) if __name__ == '__main__': if len(sys.argv) < 2: print 'Parâmetros: a/p - ativo/passivo' else: servidor = Servidor(sys.argv[1] == 'p') servidor.start()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' from message import Message from messenger import Messenger from consts import Consts from threading import Timer def init_FenixSD(messenger,coordinator): ''' Função para fazer as classes se conhecerem ''' messenger.coordinator = coordinator coordinator.messenger = messenger class Coordinator(object): ''' Classe estática (não em constructor). ''' PASSIVE = 0 ACTIVE = 1 stateList = [] _mode = PASSIVE #indefinido inicialmentes id = None #id da máquina active_timer = None passive_timer = None def setActive(self): self._mode = self.ACTIVE self.setActiveTimer() def setActiveTimer(self): if self.active_timer != None: self.active_timer.cancel() self.active_timer = Timer(Consts.TIMEOUT_ACTIVE,self.heartbeat) self.active_timer.start() def setPassiveTimer(self): if self.passive_timer != None: self.passive_timer.cancel() self.passive_timer = Timer(Consts.TIMEOUT_PASSIVE,self.assumeControl) self.passive_timer.start() def setPassive(self): self._mode = self.PASSIVE self.setPassiveTimer() def assumeControl(self): print 'Assumindo o controle!' self.passive_timer.cancel() #self.setActive() def heartbeat(self): print 'Enviando heartbeat' self.messenger.send(self.id, str(None),Message.STATE_MESSAGE) self.setActiveTimer() def refreshState(self, state): "Salva o estado na lista de states" if state != None: stateListAux = [] for s in self.stateList: if s != None: if s.message.sender != state.message.sender: stateListAux.append(s) if len(stateListAux) == len(self.stateList): print 'Estado de Cliente novo detectado' stateListAux.append(state) self.stateList = stateListAux else: print 'Mensagem era um heartbeat' #zerar o timer do passivo, aqui def processMessage(self, message): if message.msg_type == Message.STATE_MESSAGE: """ A maquina passiva recebe um estado. Não interessa a máquina ativa receber um estado. """ print 'Processando uma mensagem STATE' if self._mode == self.ACTIVE: print 'Ignorando salvamento de estado' return self.messenger.receive() print 'Recebido msg: ' + str(message) state = self.messenger.stringToState(message.data) self.refreshState(state) #Reinicia o contador para assumir o controle: self.setPassiveTimer() """ Envia msg de ACK """ print 'Enviando ACK para a máquina ativa' self.messenger.send(self.id, str(None),Message.ACK_MESSAGE) return self.messenger.receive() #volta a escutar elif message.msg_type == Message.NORMAL_MESSAGE: """ A máquina ativa ou passiva receberam uma mensagem """ print 'Processando mensagem NORMAL' if self._mode == self.PASSIVE: #A máquina passiva recebe mensagens, mas as ignora. print 'Ignorando mensagem' return self.messenger.receive() #volta a escutar """ Como vamos salvar o estado, logo em seguida, resetamos o timer para evitar o envio de um State nulo. """ self.setActiveTimer() """ Para salvar o estado, temos que procurar o id do cliente correspondente. """ state = None for s in self.stateList: if s != None: if s.message.sender == message.sender: state = s break if state != None: """ Devemos enviar o estado mais atual do cliente agora, antes de processar. """ print 'Enviando State: ' + str(state) import sys sys.stdin.readline() self.messenger.send(self.id, str(state),type=Message.STATE_MESSAGE) #esperar o ACK aqui? elif message.msg_type == Message.ACK_MESSAGE: print 'Processando uma mensagem ACK' if self._mode == self.ACTIVE: print 'Ignorando ACK enviado' else: #zerar contador do reenvio do principal pass return self.messenger.receive() #volta a escutar else: raise Exception("Tipo de mensagem desconhecido: " + message.msg_type) return message
Python
''' Created on 13/07/2010 @author: Rondon ''' import unittest from messenger import Messenger from message import Message class Test(unittest.TestCase): def testMessenger(self): msg = Message(None,None,None,None,None) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testMessenger'] unittest.main()
Python
# -*- coding: utf-8 -*- ''' Created on Jul 12, 2010 @author: Giulio ''' from messenger import Messenger from consts import Consts import coordinator import sys import random import time from message import Message from state import State class Cliente(object): ''' classdocs ''' def __init__(self, isPassive): self.isPassive = isPassive self.serverID = 'Server' self.id = '' def start(self): ''' Inicialização de TF: ''' print 'Cliente: Inicializando...' #coord = coordinator.Coordinator(Consts.CORDINATOR_TYPE[0]) coord = coordinator.Coordinator() coord.id = self.id messenger = Messenger(coord) coordinator.init_FenixSD(messenger, coord) if not self.isPassive: coord.setActive() else: coord.setPassive() while(True): sys.stdin.readline() print 'Cliente: enviando requisição' message = str(5) """ state = State() state.message = Message(sender=self.id, \ receiver=self.serverID, \ sequence=seq, \ msg_type=message.REQUEST, \ data=message) state.data = message coord.refreshState(state) """ messenger.prepare() messenger.send(self.serverID, message) print 'Cliente: esperando resposta...' message = messenger.receive(True) resp, id = message.data, message.sender print 'Cliente: resposta = ' + str(resp) + ' ' + str(id) #time.sleep(int(random.random() * 5 + 1)) #espera de 1 a 5 segundos #time.sleep(int(random.random() + 1)) #espera de 1 a 5 segundos if __name__ == '__main__': if len(sys.argv) < 3: print 'Parâmetro 1: a/p - ativo/passivo' print 'Parâmetro 2: nome do cliente' else: cliente = Cliente(sys.argv[1] == 'p') cliente.id = sys.argv[2] cliente.start()
Python
# -*- coding: utf-8 -*- ''' Created on 11/07/2010 @author: Rondon ''' class Message(object): ''' classdocs ''' #Tipos de mensagem NORMAL_MESSAGE = 0 #a mensagem deve ser repassada para a aplicação STATE_MESSAGE = 1 #a mensagem carrega um State em data ACK_MESSAGE = 2 #mensagem de confirmação de recebimento de um State vindo do servidor Principal para o Secundário def __init__(self, sender, receiver, sequence, msg_type, data): ''' Constructor ''' self.sender = sender self.receiver = receiver self.sequence = sequence self.msg_type = msg_type self.data = data def __str__(self): return str(self.msg_type) + ' ' + str(self.sender) + ' ' + str(self.receiver) + ' ' + str(self.sequence) + ' ' + str(self.data)
Python
''' Created on Jul 12, 2010 @author: Giulio ''' class Consts(object): GROUPS = {'Rodrigo':'226.0.0.1','Vinicius':'226.0.0.2','Giulio':'226.0.0.3','Douglas':'226.0.0.4',\ 'Matheus':'226.0.0.5','Carlos':'226.0.0.6','Server':'225.0.0.1'} TIMEOUT_ACTIVE = 5 TIMEOUT_PASSIVE = 15
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.6 # """Simple Python command-line client to Speedometer.""" __author__ = 'royman@google.com (Roy McElmurry)' import datetime import json import logging import optparse import random import sys import appengine_client parser = optparse.OptionParser() parser.add_option('--speedometer_server', default='http://speedometer.googleplex.com', help='Speedometer server') parser.add_option('--use_local_dev_server', action='store_true', default=False, help='Connect to a local development server') parser.add_option('--username', default=None, help='Username to login with') parser.add_option('--password', default=None, help='Application-specific password') parser.add_option('--list_devices', action='store_true', default=False, help='List accessible devices') parser.add_option('--fake_checkin', action='store_true', default=False, help='Perform a fake device checkin') parser.add_option('--fake_post_measurements', action='store_true', default=False, help='Perform fake measurement posts') options, unused_leftover_args = parser.parse_args(args=sys.argv) def TimeToMicrosecondsSinceEpoch(dt): """Convert a datetime object to microseconds since the epoch UTC. Args: dt: A datetime.datetime object. Returns: A long in microseconds since the epoch UTC. """ epoch = datetime.datetime(1970, 1, 1) diff = dt - epoch microsec_since_epoch = int(((diff.days * 86400) + (diff.seconds)) * 1000000) microsec_since_epoch += diff.microseconds return microsec_since_epoch class SpeedometerClient(object): """Encapsulates an rpc agent with common tasks.""" def __init__ (self, speedometer_server=None, use_local_dev_server=None, auth_function=None): if speedometer_server is None: speedometer_server = options.speedometer_server if use_local_dev_server is None: use_local_dev_server = options.use_local_dev_server if use_local_dev_server: rpc_agent = appengine_client.DevAppServerHttpRpcServer(speedometer_server) else: if auth_function is None: auth_function = lambda: (options.username, options.password) rpc_agent = appengine_client.HttpRpcServer( speedometer_server, auth_function=auth_function) self.rpc_agent = rpc_agent def GetDevices(self): """Returns a list of available devices.""" devices_json = self.rpc_agent.Send('/devices') devices = json.loads(devices_json) logging.info('Found %d devices', len(devices)) return devices def _FakeDeviceProperties(self): """Return a dict containing a fake device_properties record.""" retval = { 'app_version': '0.1', 'ip_address': '127.42.38.1', 'os_version': '1.0', 'carrier': 'Fake carrier', 'network_type': 'Fake network', 'location': { 'latitude': 47.6508, 'longitude': -122.3515 }, 'location_type': 'Fake location type', 'battery_level': random.randint(1, 100), 'is_battery_charging': False, 'cell_info': 'LAC1,CID1,RSSI1;LAC2,CID2,RSSI2', 'rssi': random.randint(1, 100), } return retval def FakeDeviceCheckin(self, device_id): """Perform a fake checkin to the server.""" payload_json = json.dumps({ 'status': 'READY', 'id': device_id, 'manufacturer': 'Fake manufacturer', 'model': 'Fake model', 'os': 'Fake OS', 'properties': self._FakeDeviceProperties(), }) response_json = self.rpc_agent.Send('/checkin', payload=payload_json) return json.loads(response_json) def FakePostMeasurement(self, device_id, measurement_type='ping', task_parameters=None, task_values=None, timestamp=None): """Submit a fake measurement result to the server.""" timestamp = timestamp or datetime.datetime.utcnow() tsusec = TimeToMicrosecondsSinceEpoch(timestamp) payload_json = json.dumps([{ 'device_id': device_id, 'timestamp': tsusec, 'properties': self._FakeDeviceProperties(), 'type': measurement_type, 'success': True, 'parameters': task_parameters or {}, 'values': task_values or {}}]) response_json = self.rpc_agent.Send('/postmeasurement', payload=payload_json) return json.loads(response_json) def main(): client = SpeedometerClient() if options.list_devices: devices = client.GetDevices() for device in devices: print ('%(id)s,%(status)s,%(pending_count)d,%(manufacturer)s,' '%(model)s,%(os)s,%(os_version)s') % device elif options.fake_checkin: print client.FakeDeviceCheckin('fakedevice1') elif options.fake_post_measurements: # Generate a bunch of fake measurements timestamp = datetime.datetime.utcnow() timestamp -= datetime.timedelta(days=1) for x in range(10): device_id = 'fakedevice_%d' % x print client.FakeDeviceCheckin(device_id) for unused_y in range(25): timestamp += datetime.timedelta(minutes=1) params = {'target': 'www.faketarget.com'} vals = {'target_ip': '1.2.3.4', 'ping_method': 'ping_cmd', 'mean_rtt_ms': str(random.randint(25, 75)), 'min_rtt_ms': str(random.randint(1, 25)), 'max_rtt_ms': str(random.randint(75, 100)), 'stddev_rtt_ms': str(random.randint(1, 10)), 'packet_loss': '0.25'} client.FakePostMeasurement(device_id, measurement_type='ping', task_parameters=params, task_values=vals, timestamp=timestamp) else: print 'No command option specified.' sys.exit(1) if __name__ == '__main__': main()
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Python routines for authenticating against AppEngine. This code is modified from the Rietveld upload.py code found here: http://codereview.appspot.com/static/upload.py """ __author__ = ['mdw@google.com (Matt Welsh)', 'royman@google.com (Roy McElmurry)'] import cookielib import logging import socket import sys import urllib import urllib2 import urlparse AUTH_ACCOUNT_TYPE = 'GOOGLE' class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args['Error'] self.info = args.get('Info', None) class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, account_type=AUTH_ACCOUNT_TYPE): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. account_type: Account type used for authentication. Defaults to AUTH_ACCOUNT_TYPE. """ self.host = host if (not self.host.startswith('http://') and not self.host.startswith('https://')): self.host = 'http://' + self.host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.account_type = account_type self.opener = self._GetOpener() if self.host_override: logging.info('Server: %s; Host: %s', self.host, self.host_override) else: logging.info('Server: %s', self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug('Creating request for: "%s" with payload:\n%s', url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header('Host', self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = self.account_type if self.host.endswith('.google.com'): # Needed for use inside Google. account_type = 'HOSTED' req = self._CreateRequest( url='https://www.google.com/accounts/ClientLogin', data=urllib.urlencode({ 'Email': email, 'Passwd': password, 'service': 'ah', 'source': 'appengine-client', 'accountType': account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split('=') for x in response_body.split('\n') if x) return response_dict['Auth'] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split('=', 1) for x in body.split('\n') if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = 'http://localhost/' args = {'continue': continue_location, 'auth': auth_token} req = self._CreateRequest('%s/_ah/login?%s' % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()['location'] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: print >>sys.stderr, '' if e.reason == 'BadAuthentication': if e.info == 'InvalidSecondFactor': print >>sys.stderr, ( 'Use an application-specific password instead ' 'of your regular account password.\n' 'See http://www.google.com/' 'support/accounts/bin/answer.py?answer=185833') else: print >>sys.stderr, 'Invalid username or password.' elif e.reason == 'CaptchaRequired': print >>sys.stderr, ( 'Please go to\n' 'https://www.google.com/accounts/DisplayUnlockCaptcha\n' 'and verify you are a human. Then try again.\n' 'If you are using a Google Apps account the URL is:\n' 'https://www.google.com/a/yourdomain.com/UnlockCaptcha') elif e.reason == 'NotVerified': print >>sys.stderr, 'Account not verified.' elif e.reason == 'TermsNotAgreed': print >>sys.stderr, 'User has not agreed to TOS.' elif e.reason == 'AccountDeleted': print >>sys.stderr, 'The user account has been deleted.' elif e.reason == 'AccountDisabled': print >>sys.stderr, 'The user account has been disabled.' break elif e.reason == 'ServiceDisabled': print >>sys.stderr, ('The user\'s access to the service has been ' 'disabled.') elif e.reason == 'ServiceUnavailable': print >>sys.stderr, 'The service is not available; try again later.' else: # Unknown error. raise print >>sys.stderr, '' continue self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type='application/octet-stream', timeout=None, extra_headers=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) extra_headers: Dict containing additional HTTP headers that should be included in the request (string header names mapped to their values), or None to not include any additional headers. kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO(mdw): Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = '%s%s' % (self.host, request_path) if args: url += '?' + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header('Content-Type', content_type) if extra_headers: for header, value in extra_headers.items(): req.add_header(header, value) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401 or e.code == 302: self._Authenticate() elif e.code == 301: # Handle permanent redirect manually. url = e.info()['location'] url_loc = urlparse.urlparse(url) self.host = '%s://%s' % (url_loc[0], url_loc[1]) else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener class DevAppServerHttpRpcServer(HttpRpcServer): """Subclass of HttpRpcServer that talks to a dev_appserver instance.""" def __init__(self, host, username='test@example.com', host_override=None, extra_headers={}, account_type=AUTH_ACCOUNT_TYPE): auth_function = lambda: (username, 'fakepassword') extra_headers = {'Cookie': 'dev_appserver_login="%s:False"' % username} super(HttpRpcServer, self).__init__(host, auth_function, host_override, extra_headers, account_type) self.authenticated = True
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Service to collect and visualize mobile network performance data.""" __author__ = 'mdw@google.com (Matt Welsh)' # pylint: disable-msg=C6205 try: # This is expected to fail on the local server. from google.appengine.dist import use_library # pylint: disable-msg=C6204 except ImportError: pass else: # We could use newer version of Django, but 1.2 is the highest version that # Appengine provides (as of May 2011). use_library('django', '1.2') #from google.appengine.ext.webapp import Request #from google.appengine.ext.webapp import RequestHandler #from google.appengine.ext.webapp import Response #from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app # pylint: disable-msg=W0611 from gspeedometer import wsgi from gspeedometer.controllers import checkin from gspeedometer.controllers import device from gspeedometer.controllers import googlemap from gspeedometer.controllers import home from gspeedometer.controllers import measurement from gspeedometer.controllers import schedule from gspeedometer.controllers import timeseries import routes m = routes.Mapper() m.connect('/', controller='home:Home', action='Dashboard') m.connect('/checkin', controller='checkin:Checkin', action='Checkin') m.connect('/device/view', controller='device:Device', action='DeviceDetail') m.connect('/device/delete', controller='device:Device', action='Delete') m.connect('/postmeasurement', controller='measurement:Measurement', action='PostMeasurement') m.connect('/measurements', controller='measurement:Measurement', action='ListMeasurements') m.connect('/measurement/view', controller='measurement:Measurement', action='MeasurementDetail') m.connect('/schedule/add', controller='schedule:Schedule', action='Add') m.connect('/schedule/delete', controller='schedule:Schedule', action='Delete') m.connect('/map', controller='googlemap:MapView', action='MapView') m.connect('/timeseries', controller='timeseries:Timeseries', action='Timeseries') m.connect('/timeseries/data', controller='timeseries:Timeseries', action='TimeseriesData') application = wsgi.WSGIApplication(m, debug=True) def real_main(): run_wsgi_app(application) def profile_main(): # This is the main function for profiling import cProfile, pstats, StringIO, logging prof = cProfile.Profile() prof = prof.runctx('real_main()', globals(), locals()) print '<pre>' stats = pstats.Stats(prof) stats.sort_stats('cumulative') stats.print_stats(80) # 80 = how many to print stats.print_callees() stats.print_callers() print '</pre>' #main = profile_main main = real_main if __name__ == '__main__': main()
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Wrapper for Google Map Javascript interface.""" __author__ = 'wenjiezeng@google.com (Wenjie Zeng)' from google.appengine.ext.webapp import template from gspeedometer import config class Icon(object): """Represent the resource needed to draw a Google Map icon.""" def __init__(self, icon_id='icon', image=config.DEFAULT_GOOGLEMAP_ICON_IMAGE, shadow='', icon_size=(15, 16), shadow_size=(18, 20), icon_anchor=(7, 16), info_window_anchor=(5, 1)): self.icon_id = icon_id # TODO(wenjiezeng): May want to check whether the resource exists. self.image = image self.shadow = shadow self.icon_size = icon_size self.shadow_size = shadow_size self.icon_anchor = icon_anchor self.info_window_anchor = info_window_anchor def __str__(self): return 'Icon <id %s, image %s, iconSize %s>' % ( self.icon_id, self.image, self.icon_size) class Map(object): """Represents the resource needed to draw a map.""" def __init__(self, map_id='map', width='500px', height='300px', center=(0, 0), zoom='2', show_navcontrols=True, show_mapcontrols=True, pointlist=None): # id of the html div component self.map_id = map_id # map div width self.width = width # map div height self.height = height # center (lat, long) of the view port self.center = center # zoom level of the map self.zoom = zoom # whether to show google map navigation controls self.show_navcontrols = show_navcontrols # whether to show toogle map type (sat/map/hybrid) controls self.show_mapcontrols = show_mapcontrols # point list self.points = pointlist or [] def AddPoint(self, point): """Add a point to the map.""" self.points.append(point) def __str__(self): return 'Map <id %s, width %s, height %s, center %s>' % ( self.map_id, self.width, self.height, str(self.center)) class GoogleMapWrapper(object): """A Python wrapper for Google Maps API.""" def __init__(self, key=None, themap=None, iconlist=None): # Set the appropriate Google Map key of yours self.key = key self.themap = themap or Map() self.icons = iconlist or [] def AddIcon(self, icon): """Add an icon as into the map resource so that points can reference it.""" self.icons.append(icon) def GetGoogleMapScript(self): """Returns complete javacript for rendering map.""" template_args = { 'googlemap_key': self.key, 'map': self.themap, 'points': self._GetPointsScript(self.themap), 'icons': self.icons, 'center_lat': self.themap.center[0], 'center_lon': self.themap.center[1] } return template.render( 'templates/googlemaphelper.html', template_args) def _GetPointsScript(self, themap): if not themap.points: return '[]' script_list = ['['] # Constructs the points for the map for point in themap.points: script_list.append("[%f, %f, '%s', %s]" % point) script_list.append(',') script_list = script_list[:-1] script_list.append('];\n') js = ''.join(script_list) js = js.replace("u'", "'") return js def __str__(self): iconlist = [] for icon in self.icons: iconlist.append(str(icon)) iconstr = ''.join(iconlist) return 'GoogleMapWrapper <key %s, icons %s>' % ( self.key, iconstr)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions with access control checks.""" __author__ = 'mdw@google.com (Matt Welsh)' from google.appengine.api import users from google.appengine.ext import db from gspeedometer import config def UserIsAdmin(): """Whether current user is an admin.""" user = users.get_current_user() if user and user.email() and user.email() in config.ADMIN_USERS: return True return False def UserIsScheduleAdmin(): """Whether current user is a schedule admin.""" user = users.get_current_user() if user and user.email() and user.email() in config.SCHEDULE_ADMIN_USERS: return True return False
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Utility functions for the Speedometer service.""" __author__ = 'mdw@google.com (Matt Welsh)' import cgi import datetime import logging import random import sys import time from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from django.utils import simplejson as json def StringToTime(thestr): """Convert an ISO8601 timestring into a datetime object.""" try: strtime, extra = thestr.split('.') except: # Must not be a '.' in the string strtime = thestr[:-1] # Get rid of 'Z' at end extra = 'Z' dt = datetime.datetime(*time.strptime(strtime, "%Y-%m-%dT%H:%M:%S")[0:6]) # Strip 'Z' off of end if (extra[-1] != 'Z'): raise ValueError, "Timestring does not end in Z" usecstr = extra[:-1] # Append extra zeros to end of usecstr if needed while (len(usecstr) < 6): usecstr = usecstr + '0' usec = int(usecstr) dt = dt.replace(microsecond=usec) return dt def TimeToString(dt): """Convert a DateTime object to an ISO8601-encoded string.""" return dt.isoformat() + 'Z' def MicrosecondsSinceEpochToTime(microsec_since_epoch): """Convert microseconds since epoch UTC to a datetime object.""" sec = int(microsec_since_epoch / 1000000) usec = int(microsec_since_epoch % 1000000) dt = datetime.datetime.utcfromtimestamp(sec) dt = dt.replace(microsecond=usec) return dt def TimeToMicrosecondsSinceEpoch(dt): """Convert a datetime object to microseconds since the epoch UTC.""" epoch = datetime.datetime(1970, 1, 1) diff = dt - epoch microsec_since_epoch = int(((diff.days * 86400) + (diff.seconds)) * 1000000) microsec_since_epoch += diff.microseconds return microsec_since_epoch _SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list) def ConvertToDict(model, include_fields=None, exclude_fields=None, timestamps_in_microseconds=False): """Convert an AppEngine Model object to a Python dict ready for json dump. For each property in the model, set a value in the returned dict with the property name as its key. """ output = {} for key, prop in model.properties().iteritems(): if include_fields is not None and key not in include_fields: continue if exclude_fields is not None and key in exclude_fields: continue value = getattr(model, key) if value is None or isinstance(value, _SIMPLE_TYPES): output[key] = value elif isinstance(value, datetime.date): if timestamps_in_microseconds: output[key] = TimeToMicrosecondsSinceEpoch(value) else: output[key] = TimeToString(value) elif isinstance(value, db.GeoPt): output[key] = {'latitude': value.lat, 'longitude': value.lon} elif isinstance(value, db.Model): output[key] = ConvertToDict(value, include_fields, exclude_fields, timestamps_in_microseconds) elif isinstance(value, users.User): output[key] = value.email() else: raise ValueError('cannot encode ' + repr(prop)) return output def ConvertToJson(model, include_fields=None, exclude_fields=None): """Convert an AppEngine Model object to a JSON-encoded string.""" return json.dumps(ConvertToDict(model, include_fields, exclude_fields)) def ConvertFromDict(model, input_dict, include_fields=None, exclude_fields=None): """Fill in Model fields with values from a dict. For each key in the dict, set the value of the corresponding field in the given Model object to that value. If the Model implements a method 'JSON_DECODE_key' for a given key 'key', this method will be invoked instead with an argument containing the value. This allows Model subclasses to override the decoding behavior on a per-key basis. """ for k, v in input_dict.items(): if include_fields is not None and k not in include_fields: continue if exclude_fields is not None and k in exclude_fields: continue if hasattr(model, 'JSON_DECODE_' + k): method = getattr(model, 'JSON_DECODE_' + k) method(v) else: setattr(model, k, v)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Definition for error classes.""" __author__ = 'qfang@google.com (Qinming Fang)' class BaseError(Exception): def __init__(self, value): Exception.__init__(self) self.value = value def __str__(self): return repr(self.value) class BadRequest(BaseError): pass class AccessDenied(BaseError): pass
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Replacement WSGIApplication that supports Routes. This code facilitates the use of Routes to invoke controllers based on URLs and is based on code from an entry in the AppEngine cookbook, http://appengine-cookbook.appspot.com/recipe/match-webapp-urls-using-routes. """ __author__ = 'qfang@google.com (Qinming Fang)' import logging import sys from google.appengine.ext.webapp import Request from google.appengine.ext.webapp import Response from gspeedometer.helpers import error _CONTROLLERS_MODULE_PREFIX = 'gspeedometer.controllers' class WSGIApplication(object): """Wraps a set of webapp RequestHandlers in a WSGI-compatible application. This is based on webapp's WSGIApplication by Google, but uses Routes library (http://routes.groovie.org/) to match URLs. """ def __init__(self, mapper, debug=False): """Initializes this application with the given URL mapping. Args: mapper: a routes.mapper.Mapper instance. debug: if true, we send Python stack traces to the browser on errors. """ self.mapper = mapper self.__debug = debug WSGIApplication.active_instance = self self.current_request_args = () def __call__(self, environ, start_response): """Called by WSGI when a request comes in.""" request = Request(environ) response = Response() WSGIApplication.active_instance = self # Match the path against registered routes. kargs = self.mapper.match(request.path) if kargs is None: raise TypeError('No routes match. Provide a fallback to avoid this.') # Extract the module and controller names from the route. try: module_name, class_name = kargs['controller'].split(':', 1) except (KeyError, ValueError): module_name = kargs['controller'] class_name = module_name del kargs['controller'] module_name = _CONTROLLERS_MODULE_PREFIX + '.' + module_name # Initialize matched controller from given module. try: __import__(module_name) module = sys.modules[module_name] controller = getattr(module, class_name)() controller.initialize(request, response) except (ImportError, AttributeError): logging.exception('Could not import controller %s:%s', module_name, class_name) raise ImportError('Controller %s from module %s could not be initialized.' % (class_name, module_name)) # Use the action set in the route, or the HTTP method. if 'action' in kargs: action = kargs['action'] del kargs['action'] else: action = environ['REQUEST_METHOD'].lower() if action not in [ 'get', 'post', 'head', 'options', 'put', 'delete', 'trace']: action = None if controller and action: try: # Execute the requested action, passing the route dictionary as # named parameters. getattr(controller, action)(**kargs) except error.AccessDenied, acl_e: logging.exception(acl_e) response.set_status(404) except Exception, e: # We want to catch any exception thrown by the controller and # pass it on to the controller's own exception handler. controller.handle_exception(e, self.__debug) response.wsgi_write(start_response) return [''] else: response.set_status(404)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Service to collect and visualize mobile network performance data.""" __author__ = 'mdw@google.com (Matt Welsh)' import datetime import urllib import urlparse from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import config from gspeedometer import model from gspeedometer.helpers import acl class Home(webapp.RequestHandler): """Controller for the home page.""" def Dashboard(self, **unused_args): """Main handler for the service dashboard.""" errormsg = None devices, cursor = self._GetDeviceList( cursor=self.request.get('device_cursor')) if cursor: parsed_url = list(urlparse.urlparse(self.request.url)) url_query_dict = {'device_cursor': cursor} parsed_url[4] = urllib.urlencode(url_query_dict) more_devices_link = urlparse.urlunparse(parsed_url) else: more_devices_link = None schedule = model.Task.all() schedule.order('-created') template_args = { 'user_schedule_admin': acl.UserIsScheduleAdmin(), 'devices': devices, 'schedule': schedule, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/'), 'more_devices_link': more_devices_link, 'error': errormsg } self.response.out.write(template.render( 'templates/home.html', template_args)) def _GetDeviceList(self, cursor=None, show_inactive=False): device_query = model.DeviceInfo.GetDeviceListWithAcl(cursor=cursor) devices = list(device_query.fetch(config.NUM_DEVICES_IN_LIST)) # Don't need cursor if we are at the end of the list if len(devices) == config.NUM_DEVICES_IN_LIST: cursor = device_query.cursor() else: cursor = None if not show_inactive: active_time = (datetime.datetime.utcnow() - datetime.timedelta(days=config.ACTIVE_DAYS)) devices = [d for d in devices if d.LastUpdateTime() >= active_time] devices.sort(key=lambda dev: dev.LastUpdateTime()) devices.reverse() return (devices, cursor)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Controller to manage manipulation of measurement schedules.""" __author__ = 'mdw@google.com (Matt Welsh)' import datetime import logging from django import forms from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import model from gspeedometer.controllers import measurement from gspeedometer.helpers import acl class AddToScheduleForm(forms.Form): """Form to add a task to the schedule.""" type = forms.ChoiceField(measurement.MEASUREMENT_TYPES) param1 = forms.CharField(required=False) param2 = forms.CharField(required=False) param3 = forms.CharField(required=False) count = forms.IntegerField(required=False, initial=-1, min_value=-1, max_value=1000) interval = forms.IntegerField(required=True, label='Interval (sec)', min_value=1, initial=600) tag = forms.CharField(required=False) filter = forms.CharField(required=False) class Schedule(webapp.RequestHandler): """Measurement request handler.""" def Add(self, **unused_args): """Add a task to the schedule.""" if not acl.UserIsScheduleAdmin(): self.error(404) return if not self.request.POST: add_to_schedule_form = AddToScheduleForm() else: add_to_schedule_form = AddToScheduleForm(self.request.POST) add_to_schedule_form.full_clean() if add_to_schedule_form.is_valid(): thetype = add_to_schedule_form.cleaned_data['type'] param1 = add_to_schedule_form.cleaned_data['param1'] param2 = add_to_schedule_form.cleaned_data['param2'] param3 = add_to_schedule_form.cleaned_data['param3'] tag = add_to_schedule_form.cleaned_data['tag'] thefilter = add_to_schedule_form.cleaned_data['filter'] count = add_to_schedule_form.cleaned_data['count'] or -1 interval = add_to_schedule_form.cleaned_data['interval'] logging.info('Got TYPE: ' + thetype) task = model.Task() task.created = datetime.datetime.utcnow() task.user = users.get_current_user() task.type = thetype if tag: task.tag = tag if thefilter: task.filter = thefilter task.count = count task.interval_sec = float(interval) # Set up correct type-specific measurement parameters if task.type == 'ping': task.mparam_target = param1 task.mparam_ping_timeout_sec = param2 task.mparam_packet_size_byte = param3 elif task.type == 'traceroute': task.mparam_target = param1 task.mparam_pings_per_hop = param2 task.mparam_max_hop_count = param3 elif task.type == 'http': task.mparam_url = param1 task.mparam_method = param2 task.mparam_headers = param3 elif task.type == 'dns_lookup': task.mparam_target = param1 task.mparam_server = param2 task.put() schedule = model.Task.all() schedule.order('-created') template_args = { 'user_schedule_admin': acl.UserIsScheduleAdmin(), 'add_form': add_to_schedule_form, 'schedule': schedule, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/schedule.html', template_args)) def Delete(self, **unused_args): """Delete a task from the schedule.""" if not acl.UserIsScheduleAdmin(): self.error(404) return errormsg = None message = None add_to_schedule_form = AddToScheduleForm() task_id = self.request.get('id') task = model.Task.get_by_id(int(task_id)) if not task: errormsg = 'Task %s does not exist' % task_id else: # TODO(mdw): Do we need to wrap the following in a transaction? # First DeviceTasks that refer to this one device_tasks = model.DeviceTask.all() device_tasks.filter('task =', task) for dt in device_tasks: dt.delete() # Now delete the task itself task.delete() message = 'Task %s deleted' % task_id schedule = model.Task.all() schedule.order('-created') template_args = { 'user_schedule_admin': acl.UserIsScheduleAdmin(), 'add_form': add_to_schedule_form, 'message': message, 'error': errormsg, 'schedule': schedule, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/schedule.html', template_args))
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Service to collect and visualize mobile network performance data.""" __author__ = 'mdw@google.com (Matt Welsh)' import logging from django.utils import simplejson as json from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import model from gspeedometer.controllers import device from gspeedometer.helpers import error from gspeedometer.helpers import util MEASUREMENT_TYPES = [('ping', 'ping'), ('dns_lookup', 'DNS lookup'), ('traceroute', 'traceroute'), ('http', 'HTTP get'), ('ndt', 'NDT measurement')] class Measurement(webapp.RequestHandler): """Measurement request handler.""" def PostMeasurement(self, **unused_args): """Handler used to post a measurement from a device.""" if self.request.method.lower() != 'post': raise error.BadRequest('Not a POST request.') try: measurement_list = json.loads(self.request.body) logging.info('PostMeasurement: Got %d measurements to write', len(measurement_list)) for measurement_dict in measurement_list: device_info = model.DeviceInfo.get_or_insert( measurement_dict['device_id']) # Write new device properties, if present if 'properties' in measurement_dict: device_properties = model.DeviceProperties(parent=device_info) device_properties.device_info = device_info properties_dict = measurement_dict['properties'] # TODO(wenjiezeng): Sanitize input that contains bad fields util.ConvertFromDict(device_properties, properties_dict) # Don't want the embedded properties in the Measurement object del measurement_dict['properties'] else: # Get most recent device properties device_properties = device.GetLatestDeviceProperties( device_info, create_new_if_none=True) device_properties.put() measurement = model.Measurement(parent=device_info) util.ConvertFromDict(measurement, measurement_dict) measurement.device_properties = device_properties measurement.put() except Exception, e: logging.exception('Got exception posting measurements') logging.info('PostMeasurement: Done processing measurements') response = {'success': True} self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(response)) def ListMeasurements(self, **unused_args): """Handles /measurements REST request.""" # This is very limited and only supports time range and limit # queries. You might want to extend this to filter by other # properties, but for the purpose of measurement archiving # this is all we need. start_time = self.request.get('start_time') end_time = self.request.get('end_time') limit = self.request.get('limit') query = model.Measurement.all() if start_time: dt = util.MicrosecondsSinceEpochToTime(int(start_time)) query.filter('timestamp >=', dt) if end_time: dt = util.MicrosecondsSinceEpochToTime(int(end_time)) query.filter('timestamp <', dt) query.order('timestamp') if limit: results = query.fetch(int(limit)) else: results = query output = [] for measurement in results: # Need to catch case where device has been deleted try: unused_device_info = measurement.device_properties.device_info except db.ReferencePropertyResolveError: logging.exception('Device deleted for measurement %s', measurement.key().id()) # Skip this measurement continue # Need to catch case where task has been deleted try: unused_task = measurement.task except db.ReferencePropertyResolveError: measurement.task = None measurement.put() mdict = util.ConvertToDict(measurement, timestamps_in_microseconds=True) # Fill in additional fields mdict['id'] = str(measurement.key().id()) mdict['parameters'] = measurement.Params() mdict['values'] = measurement.Values() if 'task' in mdict and mdict['task'] is not None: mdict['task']['id'] = str(measurement.GetTaskID()) mdict['task']['parameters'] = measurement.task.Params() output.append(mdict) self.response.out.write(json.dumps(output)) def MeasurementDetail(self, **unused_args): """Handler to display measurement detail.""" errormsg = '' measurement = None try: deviceid = self.request.get('deviceid') measid = self.request.get('measid') # Need to construct complete key from ancestor path key = db.Key.from_path('DeviceInfo', deviceid, 'Measurement', int(measid)) measurement = db.get(key) if not measurement: errormsg = 'Cannot get measurement ' + measid return finally: template_args = { 'error': errormsg, 'id': measid, 'measurement': measurement, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/measurementdetail.html', template_args))
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Service that queries user data and renders on google map.""" __author__ = 'wenjiezeng@google.com (Wenjie Zeng)' import datetime import random from django import forms from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import config from gspeedometer import model from gspeedometer.helpers import googlemaphelper # Workaround to mismatch between Google App Engine # and Django types for MultipleChoiceField inputs # See http://vanderwijk.info/2011/02/ class SelectMultiple(forms.widgets.SelectMultiple): """Fixed SelectMultiple to work with Google App Engine.""" def value_from_datadict(self, data, unused_files, name): try: return data.getall(name) except: return data.get(name, None) def DeviceChoice(dev): """Return a tuple (key, description) for the given device.""" key_name = dev.key().name() description = '%s %s %s' % ( key_name, dev.manufacturer, dev.model) return (key_name, description) class MapView(webapp.RequestHandler): """Controller for the Google map view.""" def MapView(self, **unused_args): """Main handler for the google map view.""" all_devices = model.DeviceInfo.GetDeviceListWithAcl() all_device_ids = [dev.key().name() for dev in all_devices] now = datetime.datetime.utcnow() init_end_date = datetime.date(now.year, now.month, now.day) init_end_date += datetime.timedelta(days=1) init_start_date = init_end_date - datetime.timedelta(days=7) if self.request.get('device_id'): # If map invoked with one device ID, make this one the default device_ids = [self.request.get('device_id')] # And show most recent data for this device start_date = None end_date = None else: device_ids = all_device_ids start_date = init_start_date end_date = init_end_date class FilterMeasurementForm(forms.Form): """A form to filter measurement results for a given device.""" device = forms.MultipleChoiceField( widget=SelectMultiple, choices=[DeviceChoice(dev) for dev in all_devices], required=False) start_date = forms.DateField(label='Start date (GMT)') end_date = forms.DateField(label='End date (GMT)') form_initial = {'start_date': init_start_date, 'end_date': init_end_date} if not self.request.POST: form = FilterMeasurementForm(initial=form_initial) else: form = FilterMeasurementForm(self.request.POST, initial=form_initial) form.full_clean() if form.is_valid(): device_ids = form.cleaned_data['device'] or device_ids start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] # Impose a time limit on this to avoid deadline exceeded errors timelimit = datetime.datetime.utcnow() + datetime.timedelta(seconds=10) measurements = self._GetMeasurements(device_ids, start_date, end_date, timelimit) template_args = { 'filter_form': form, 'num_measurements': len(measurements), 'map_code': self._GetJavascriptCodeForMap(measurements) } self.response.out.write(template.render( 'templates/mapview.html', template_args)) def _GetMeasurements(self, device_ids, start_date=None, end_date=None, timelimit=None): """Return a list of measurements. Args: device_ids: List of device IDs to retrieve measurements for. start_date: datetime.datetime object representing start date. end_date: datetime.datetime object representing end date. timelimit: datetime.datetime object for max time that we should keep querying for results. Returns: A list of measurement objects. """ results = [] per_device_limit = max(1, int(config.GOOGLEMAP_MARKER_LIMIT / len(device_ids))) for device_id in device_ids: if timelimit and datetime.datetime.utcnow() > timelimit: break subquery = model.Measurement.GetMeasurementListWithAcl( limit=per_device_limit, device_id=device_id, start_time=start_date, end_time=end_date) results.extend(subquery) return results def _GetJavascriptCodeForMap(self, measurements): """Constructs the javascript code to map measurement results.""" # TODO(mattp) - This whole thing should be redone as a heatmap tmap = googlemaphelper.Map() red_icon = googlemaphelper.Icon(icon_id='red_icon', image='/static/red_location_pin.png') green_icon = googlemaphelper.Icon(icon_id='green_icon', image='/static/green_location_pin.png') # Add resource into the google map my_key = config.GOOGLEMAP_KEY gmap = googlemaphelper.GoogleMapWrapper(key=my_key, themap=tmap) gmap.AddIcon(green_icon) gmap.AddIcon(red_icon) tmap.zoom = config.GOOGLE_MAP_ZOOM lat_sum = 0 lon_sum = 0 random.seed() measurement_cnt = 0 # Add points to the map for meas in measurements: prop_entity = meas.device_properties # Skip measurements without a location associated with them if not prop_entity.location or prop_entity.location_type == 'unknown': continue device_id = prop_entity.device_info.key().name() values = {} icon_to_use = red_icon # these attributes can be non-existent if the experiment fails if meas.success == True: # type strings from controller/measurement.py if meas.type == 'ping': values = {'target': meas.mparam_target, 'mean rtt': meas.mval_mean_rtt_ms, 'max rtt': meas.mval_max_rtt_ms, 'min rtt': meas.mval_min_rtt_ms, 'rtt stddev': meas.mval_stddev_rtt_ms, 'packet loss': meas.mval_packet_loss} if (float(meas.mval_mean_rtt_ms) < config.SLOW_PING_THRESHOLD_MS): icon_to_use = green_icon elif meas.type == 'http': values = {'url': meas.mparam_url, 'code': meas.mval_code, 'time (msec)': meas.mval_time_ms, 'header length (bytes)': meas.mval_headers_len, 'body length (bytes)': meas.mval_body_len} if meas.mval_code == '200': icon_to_use = green_icon elif meas.type == 'dns_lookup': values = {'target': meas.mparam_target, 'IP address': meas.mval_address, 'real hostname': meas.mval_real_hostname, 'time (msec)': meas.mval_time_ms} if float(meas.mval_time_ms) < config.SLOW_DNS_THRESHOLD_MS: icon_to_use = green_icon elif meas.type == 'traceroute': values = {'target': meas.mparam_target, '# of hops': meas.mval_num_hops} if (float(meas.mval_num_hops) < config.LONG_TRACEROUTE_HOP_COUNT_THRESHOLD): icon_to_use = green_icon htmlstr = self._GetHtmlForMeasurement(device_id, meas, values) # Use random offset to deal with overlapping points rand_lat = (random.random() - 0.5) * config.LOCATION_FUZZ_FACTOR rand_lon = (random.random() - 0.5) * config.LOCATION_FUZZ_FACTOR point = (prop_entity.location.lat + rand_lat, prop_entity.location.lon + rand_lon, htmlstr, icon_to_use.icon_id) lat_sum += prop_entity.location.lat lon_sum += prop_entity.location.lon measurement_cnt += 1 tmap.AddPoint(point) # Set the center of the viewport if measurement_cnt: center_lat = lat_sum / measurement_cnt center_lon = lon_sum / measurement_cnt tmap.center = (center_lat, center_lon) else: tmap.center = config.DEFAULT_MAP_CENTER mapcode = gmap.GetGoogleMapScript() return mapcode def _GetHtmlForMeasurement(self, device_id, meas, values): """Returns the HTML string representing a measurement result. Args: device_id: The device ID meas: The measurement object. values: The measurement values to include in the table. Returns: An HTML string. """ result = '<html><body><b>%s</b><br/>' % meas.type result += 'Device %s<br/>' % device_id result += '%s<br/>' % meas.timestamp result += """<style media="screen" type="text/css"></style>""" result += """<table style="border:1px #000000 solid;">""" for k, v in values.iteritems(): result += ( '<tr>' '<td align=\"left\" ' 'style=\"padding-right:10px;border-bottom:' '1px #000000 dotted;\">%s</td>' '<td align=\"left\" ' 'style=\"padding-right:10px;border-bottom:' '1px #000000 dotted;\">%s</td>' '</tr>' % (k, v)) result += '</table>' if not values: result += '<br/>Measurement failed.' result += '</body></html>' return result
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Timeseries plotting of measurement results.""" __author__ = 'mdw@google.com (Matt Welsh)' from django.utils import simplejson as json from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import config from gspeedometer import model from gspeedometer.helpers import util class Timeseries(webapp.RequestHandler): """Controller for the timeseries view.""" def Timeseries(self, **unused_args): """Main handler for the timeseries view.""" # This simply sets up the chart - the data is retrieved asynchronously. device_id = self.request.get('device_id') # Used to trigger permission check unused_device = model.DeviceInfo.GetDeviceWithAcl(device_id) tscolumns = [] tscolumns.append('Signal strength (%s)' % device_id) tscolumns.append('Battery level (%s)' % device_id) template_args = { 'limit': config.TIMESERIES_POINT_LIMIT, 'device_id': device_id, 'timeseries_columns': tscolumns, } self.response.out.write(template.render( 'templates/timeseriesview.html', template_args)) def TimeseriesData(self, **unused_args): """Returns data for the timeseries view in JSON format.""" device_id = self.request.get('device_id') start_time = self.request.get('start_time') end_time = self.request.get('start_time') limit = self.request.get('limit') # Used to trigger permission check unused_device = model.DeviceInfo.GetDeviceWithAcl(device_id) if start_time: start_time = util.MicrosecondsSinceEpochToTime(int(start_time)) if end_time: end_time = util.MicrosecondsSinceEpochToTime(int(end_time)) if limit: limit = int(limit) measurements = model.Measurement.GetMeasurementListWithAcl( limit=limit, device_id=device_id, start_time=start_time, end_time=end_time) tsdata = [] for meas in measurements: ms_time = util.TimeToMicrosecondsSinceEpoch(meas.timestamp) / 1000 rssi = meas.device_properties.rssi or 0 battery = meas.device_properties.battery_level or 0 val = ('new Date(%d)' % ms_time, rssi, battery) tsdata.append(val) self.response.out.write(json.dumps(tsdata))
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Controller for device management.""" __author__ = 'mdw@google.com (Matt Welsh)' import urllib import urlparse from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from gspeedometer import config from gspeedometer import model class Device(webapp.RequestHandler): """Controller to handle device management.""" def DeviceDetail(self, **unused_args): """Query for a specific device.""" errormsg = None device_id = self.request.get('device_id') device = model.DeviceInfo.GetDeviceWithAcl(device_id) try: if not device: errormsg = 'Device %s not found' % device_id template_args = { 'error': errormsg, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/devicedetail.html', template_args)) return # Get set of properties associated with this device query = device.deviceproperties_set query.order('-timestamp') properties = query.fetch(config.NUM_PROPERTIES_IN_LIST) # Get current tasks assigned to this device cur_schedule = [device_task.task for device_task in device.devicetask_set] # Get measurements cursor = self.request.get('measurement_cursor') if self.request.get('all') == '1': query = db.GqlQuery('SELECT * FROM Measurement ' 'WHERE ANCESTOR IS :1 ' 'ORDER BY timestamp DESC', device.key()) else: query = db.GqlQuery('SELECT * FROM Measurement ' 'WHERE ANCESTOR IS :1 AND success = TRUE ' 'ORDER BY timestamp DESC', device.key()) if cursor: query.with_cursor(cursor) measurements = query.fetch(config.NUM_MEASUREMENTS_IN_LIST) # If there are more measurements to show, give the user a cursor if len(measurements) == config.NUM_MEASUREMENTS_IN_LIST: cursor = query.cursor() parsed_url = list(urlparse.urlparse(self.request.url)) url_query_dict = {'device_id': device_id, 'measurement_cursor': cursor, 'all': self.request.get('all')} parsed_url[4] = urllib.urlencode(url_query_dict) more_measurements_link = urlparse.urlunparse(parsed_url) else: more_measurements_link = None template_args = { 'error': errormsg, 'device_id': device_id, 'dev': device, 'properties': properties, 'measurements': measurements, 'more_measurements_link': more_measurements_link, 'schedule': cur_schedule, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/'), } self.response.out.write(template.render( 'templates/devicedetail.html', template_args)) except: raise def Delete(self, **unused_args): """Delete a specific device.""" errormsg = None device_id = self.request.get('device_id') device = model.DeviceInfo.GetDeviceWithAcl(device_id) if not device: errormsg = 'Device %s not found' % device_id template_args = { 'error': errormsg, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/devicedelete.html', template_args)) return else: if self.request.get('confirm') == '1': # Do the deletion itself. device.delete() self.redirect('/') return else: # Not confirmed template_args = { 'device_id': device_id, 'dev': device, 'user': users.get_current_user().email(), 'logout_link': users.create_logout_url('/') } self.response.out.write(template.render( 'templates/devicedelete.html', template_args)) return def GetLatestDeviceProperties(device_info, create_new_if_none=False): """Retrieve the latest device properties corresponding to this device_info. Arguments: device_info: The DeviceInfo object on which to retrieve the properties. create_new_if_none: Whether to create a new DeviceProperties if none exists. Returns: A DeviceProperties object, or None. """ query = device_info.deviceproperties_set query.order('-timestamp') device_properties_list = query.fetch(1) if not device_properties_list: if create_new_if_none: device_properties = model.DeviceProperties(parent=device_info) device_properties.device_info = device_info return device_properties else: return None else: return device_properties_list[0]
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Service to collect and visualize mobile network performance data.""" __author__ = 'mdw@google.com (Matt Welsh)' import logging from django.utils import simplejson as json from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from gspeedometer import model from gspeedometer.helpers import error from gspeedometer.helpers import util class Checkin(webapp.RequestHandler): """Checkin request handler.""" def Checkin(self, **unused_args): """Handler for checkin requests.""" if self.request.method.lower() != 'post': raise error.BadRequest('Not a POST request.') checkin = json.loads(self.request.body) logging.info('Got checkin: %s', self.request.body) try: # Extract DeviceInfo device_id = checkin['id'] logging.info('Checkin from device %s', device_id) device_info = model.DeviceInfo.get_or_insert(device_id) device_info.user = users.get_current_user() # Don't want the embedded properties in the device_info structure device_info_dict = dict(checkin) del device_info_dict['properties'] util.ConvertFromDict(device_info, device_info_dict) device_info.put() # Extract DeviceProperties device_properties = model.DeviceProperties(parent=device_info) device_properties.device_info = device_info util.ConvertFromDict(device_properties, checkin['properties']) device_properties.put() device_schedule = GetDeviceSchedule(device_properties) device_schedule_json = EncodeScheduleAsJson(device_schedule) logging.info('Sending checkin response: %s', device_schedule_json) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(device_schedule_json) except Exception, e: logging.error('Got exception during checkin: %s', e) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps([])) def GetDeviceSchedule(device_properties): """Return entries from the global schedule that match this device.""" matched = set() if not device_properties.device_info: return matched schedule = model.Task.all() for task in schedule: if not task.filter: matched.add(task) else: # Does the filter match this device? devices = [] # Match against DeviceProperties try: matching_device_properties = model.DeviceProperties.gql( 'WHERE ' + task.filter) devices += [dp.device_info for dp in matching_device_properties] except db.BadQueryError: logging.warn('Bad filter expression %s', task.filter) # Match against DeviceInfo try: matching_device_info = model.DeviceInfo.gql( 'WHERE ' + task.filter) devices += matching_device_info except db.BadQueryError: logging.warn('Bad filter expression %s', task.filter) for dev in devices: if dev and dev.id == device_properties.device_info.id: matched.add(task) # Un-assign all current tasks from this device for dt in device_properties.device_info.devicetask_set: dt.delete() # Assign matched tasks to this device for task in matched: device_task = model.DeviceTask() device_task.task = task device_task.device_info = device_properties.device_info device_task.put() return matched def EncodeScheduleAsJson(schedule): """Given a list of Tasks, return a JSON string encoding the schedule.""" output = [] for task in schedule: # Don't send the user, tag, or filter fields with the schedule output_task = util.ConvertToDict( task, exclude_fields=['user', 'tag', 'filter']) # Need to add the parameters and key fields output_task['parameters'] = task.Params() output_task['key'] = str(task.key().id_or_name()) output.append(output_task) return json.dumps(output)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Data model for the Speedometer service.""" __author__ = 'mdw@google.com (Matt Welsh)' import logging from google.appengine.api import users from google.appengine.ext import db from gspeedometer import config from gspeedometer.helpers import acl from gspeedometer.helpers import util class DeviceInfo(db.Model): """Represents the static properties of a given device.""" # The unique ID of this device, also used as the key id = db.StringProperty() # The owner of the device user = db.UserProperty() # Manufacturer, model, and OS name manufacturer = db.StringProperty() model = db.StringProperty() os = db.StringProperty() def last_update(self): query = self.deviceproperties_set query.order('-timestamp') try: return query.fetch(1)[0] except IndexError: logging.exception('There are no device properties associated with ' 'the given device') return None def num_updates(self): query = self.deviceproperties_set return query.count() def __str__(self): return 'DeviceInfo <id %s, user %s, device %s-%s-%s>' % ( self.id, self.user, self.manufacturer, self.model, self.os) def LastUpdateTime(self): lastup = self.last_update() if not lastup: return None return lastup.timestamp @classmethod def GetDeviceListWithAcl(cls, cursor=None): """Return a query for devices that can be accessed by the current user.""" query = cls.all() if not acl.UserIsAdmin(): query.filter('user =', users.get_current_user()) if cursor: query.with_cursor(cursor) return query @classmethod def GetDeviceWithAcl(cls, device_id): device = cls.get_by_key_name(device_id) if device and (acl.UserIsAdmin() or device.user == users.get_current_user()): return device else: raise RuntimeError('User cannot access device %s', device_id) class DeviceProperties(db.Model): """Represents the dynamic properties of a given device.""" # Reference to the corresponding DeviceInfo device_info = db.ReferenceProperty(DeviceInfo) # Speedometer app version app_version = db.StringProperty() # Timestamp timestamp = db.DateTimeProperty(auto_now_add=True) # IP address ip_address = db.StringProperty() # OS version os_version = db.StringProperty() # Location location = db.GeoPtProperty() # How location was acquired (e.g., GPS) location_type = db.StringProperty() # Network type (e.g., WiFi, UMTS, etc.) network_type = db.StringProperty() # Carrier carrier = db.StringProperty() # Battery level battery_level = db.IntegerProperty() # Battery charging status is_battery_charging = db.BooleanProperty() # Cell information represented as a string in the form of # 'LAC,CID,RSSI;LAC,CID,RSSI;...', where each semicolon separated # triplet 'LAC,CID,RSSI' are the Location Area Code, cell ID, and RSSI for # one of the cell towers in range cell_info = db.StringProperty() # Receive signal strength of the current cellular connection rssi = db.IntegerProperty() def JSON_DECODE_location(self, inputval): lat = float(inputval['latitude']) lon = float(inputval['longitude']) self.location = db.GeoPt(lat, lon) def JSON_DECODE_timestamp(self, inputval): try: self.timestamp = util.MicrosecondsSinceEpochToTime(int(inputval)) except ValueError: logging.exception('Error occurs while converting timestamp ' '%s to integer', inputval) self.timestamp = None def __str__(self): return 'DeviceProperties <device %s>' % self.device_info class Task(db.Expando): """Represents a measurement task.""" # When created created = db.DateTimeProperty() # Who created this task user = db.UserProperty() # Measurement type type = db.StringProperty() # Tag for this measurement task tag = db.StringProperty() # Query filter to match devices against this task filter = db.StringProperty() # Start and end times start_time = db.DateTimeProperty() end_time = db.DateTimeProperty() # Interval and count interval_sec = db.FloatProperty() count = db.IntegerProperty() # Priority - larger values represent higher priority priority = db.IntegerProperty() def GetParam(self, key): """Return the measurement parameter indexed by the given key.""" return self._dynamic_properties.get('mparam_' + key, None) def Params(self): """Return a dict of all measurement parameters.""" return dict((k[len('mparam_'):], self._dynamic_properties[k]) for k in self.dynamic_properties() if k.startswith('mparam_')) def JSON_DECODE_parameters(self, input_dict): for k, v in input_dict.items(): setattr(self, 'mparam_' + k, v) class Measurement(db.Expando): """Represents a single measurement by a single end-user device.""" # Reference to the corresponding device properties device_properties = db.ReferenceProperty(DeviceProperties) # Measurement type type = db.StringProperty() # Timestamp timestamp = db.DateTimeProperty(auto_now_add=True) # Whether measurement was successful success = db.BooleanProperty() # Optional corresponding task task = db.ReferenceProperty(Task) @classmethod def GetMeasurementListWithAcl(cls, limit=None, device_id=None, start_time=None, end_time=None, exclude_errors=True): """Return a list of measurements that are accessible by the current user.""" if device_id: try: devices = [DeviceInfo.GetDeviceWithAcl(device_id)] except RuntimeError: devices = [] else: devices = list(DeviceInfo.GetDeviceListWithAcl()) if not devices: return [] results = [] limit = limit or config.QUERY_FETCH_LIMIT per_query_limit = max(1, int(limit / len(devices))) for device in devices: query = cls.all() query.ancestor(device.key()) if exclude_errors: query.filter('success =', True) query.order('-timestamp') if start_time: query.filter('timestamp >=', start_time) if end_time: query.filter('timestamp <=', end_time) for result in query.fetch(per_query_limit): results.append(result) return results def GetTaskID(self): try: if not self.task: return None taskid = self.task.key().id() return taskid except db.ReferencePropertyResolveError: logging.exception('Cannot resolve task for measurement %s', self.key().id()) self.task = None # TODO(mdw): Decide if we should do this here. Can be expensive. #self.put() return None def GetParam(self, key): """Return the measurement parameter indexed by the given key.""" return self._dynamic_properties.get('mparam_' + key, None) def Params(self): """Return a dict of all measurement parameters.""" return dict((k[len('mparam_'):], self._dynamic_properties[k]) for k in self.dynamic_properties() if k.startswith('mparam_')) def GetValue(self, key): """Return the measurement value indexed by the given key.""" return self._dynamic_properties.get('mval_' + key, None) def Values(self): """Return a dict of all measurement values.""" return dict((k[len('mval_'):], self._dynamic_properties[k]) for k in self.dynamic_properties() if k.startswith('mval_')) def JSON_DECODE_timestamp(self, inputval): try: self.timestamp = util.MicrosecondsSinceEpochToTime(int(inputval)) except ValueError: logging.exception('Error occurs while converting timestamp ' '%s to integer', inputval) self.timestamp = None def JSON_DECODE_parameters(self, input_dict): for k, v in input_dict.items(): setattr(self, 'mparam_' + k, v) def JSON_DECODE_values(self, input_dict): for k, v in input_dict.items(): # body, headers, and error messages can be fairly long. # Use the Text data type instead if k == 'body' or k == 'headers' or k == 'error': setattr(self, 'mval_' + k, db.Text(v)) else: setattr(self, 'mval_' + k, v) def JSON_DECODE_task_key(self, task_key): # task_key is optional and can be None. # Look up the task_key and set the 'task' field accordingly. # If the task does not exist, just don't set this field if task_key is None: return task = Task.get_by_id(int(task_key)) if not task: return self.task = task def __str__(self): return 'Measurement <device %s, type %s>' % ( self.device_properties, self.type) class DeviceTask(db.Model): """Represents a task currently assigned to a given device.""" task = db.ReferenceProperty(Task) device_info = db.ReferenceProperty(DeviceInfo)
Python
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python2.4 # """Configuration options for the Speedometer service.""" __author__ = 'mdw@google.com (Matt Welsh)' # Set of users with admin privileges ADMIN_USERS = ['mdw@google.com', 'mattp@google.com'] # Set of users with rights to administer tasks SCHEDULE_ADMIN_USERS = ['mdw@google.com', 'mattp@google.com'] NUM_PROPERTIES_IN_LIST = 5 NUM_MEASUREMENTS_IN_LIST = 20 NUM_DEVICES_IN_LIST = 20 GOOGLE_MAP_ZOOM = 15 DEFAULT_GOOGLEMAP_ICON_IMAGE = '/static/green_location_pin.png' GOOGLEMAP_KEY = ('ABQIAAAAXVsx51W4RvTDuDUeIpF0qxRM6wioRijWnXUBkeVfSDD8OvINmRSa' 'z2Wa7XNxJDFBqSTkzyC0aVYxYw') # Default viewport of map is Google's PKV office building in Seattle DEFAULT_MAP_CENTER = (47.6508, -122.3515) DEFAULT_MEASUREMENT_TYPE_FOR_VIEWING = 'ping' # Amount to randomize lat/long of locations on the map LOCATION_FUZZ_FACTOR = 0.001 # The number of markers to show on google map per device GOOGLEMAP_MARKER_LIMIT = 500 # The number of timeseries points to retrieve TIMESERIES_POINT_LIMIT = 100 # The total number of elements to fetch for a given query QUERY_FETCH_LIMIT = 500 # The minimum ping delay in ms that we consider 'slow' SLOW_PING_THRESHOLD_MS = 150 # The minimum dns lookup delay in ms that we consider 'slow' SLOW_DNS_THRESHOLD_MS = 150 # The minimum number of hops reported by traceroute that we # consider a long route LONG_TRACEROUTE_HOP_COUNT_THRESHOLD = 14 # The interval in hours between any two adjacent battery records # to show on the graph BATTERY_INFO_INTERVAL_HOUR = 2 # The maximum time span in days the query covers MAX_QUERY_INTERVAL_DAY = 31 # Timespan over which we consider a device to be active ACTIVE_DAYS = 5
Python
#!/usr/bin/env python # # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # indexes: - kind: Measurement ancestor: yes properties: - name: success - name: timestamp direction: desc - kind: DeviceProperties properties: - name: device_info - name: timestamp direction: desc - kind: Measurement properties: - name: type - name: timestamp direction: desc - kind: Measurement ancestor: yes properties: - name: type - name: timestamp direction: desc - kind: Measurement properties: - name: success - name: timestamp direction: desc # AUTOGENERATED # This index.yaml is automatically updated whenever the dev_appserver # detects that a new type of query is run. If you want to manage the # index.yaml file manually, remove the above marker line (the line # saying "# AUTOGENERATED"). If you want to manage some indexes # manually, move them above the marker line. The index.yaml file is # automatically uploaded to the admin console when you next deploy # your application using appcfg.py.
Python
"""Route and Mapper core classes.""" import re import sys import urllib from util import _url_quote as url_quote from util import controller_scan, RouteException from routes import request_config if sys.version < '2.4': from sets import ImmutableSet as frozenset import threadinglocal def strip_slashes(name): """Remove slashes from the beginning and end of a part/URL.""" if name.startswith('/'): name = name[1:] if name.endswith('/'): name = name[:-1] return name class Route(object): """The Route object holds a route recognition and generation routine. See Route.__init__ docs for usage. """ def __init__(self, routepath, **kargs): """Initialize a route, with a given routepath for matching/generation The set of keyword args will be used as defaults. Usage:: >>> from routes.base import Route >>> newroute = Route(':controller/:action/:id') >>> newroute.defaults {'action': 'index', 'id': None} >>> newroute = Route('date/:year/:month/:day', controller="blog", ... action="view") >>> newroute = Route('archives/:page', controller="blog", ... action="by_page", requirements = { 'page':'\d{1,2}' }) >>> newroute.reqs {'page': '\\\d{1,2}'} .. Note:: Route is generally not called directly, a Mapper instance connect method should be used to add routes. """ self.routepath = routepath self.sub_domains = False self.prior = None self.encoding = kargs.pop('_encoding', 'utf-8') self.decode_errors = 'replace' # Don't bother forming stuff we don't need if its a static route self.static = kargs.get('_static', False) self.filter = kargs.pop('_filter', None) self.absolute = kargs.pop('_absolute', False) # Pull out the member/collection name if present, this applies only to # map.resource self.member_name = kargs.pop('_member_name', None) self.collection_name = kargs.pop('_collection_name', None) self.parent_resource = kargs.pop('_parent_resource', None) # Pull out route conditions self.conditions = kargs.pop('conditions', None) # Determine if explicit behavior should be used self.explicit = kargs.pop('_explicit', False) # reserved keys that don't count reserved_keys = ['requirements'] # special chars to indicate a natural split in the URL self.done_chars = ('/', ',', ';', '.', '#') # Strip preceding '/' if present if routepath.startswith('/'): routepath = routepath[1:] # Build our routelist, and the keys used in the route self.routelist = routelist = self._pathkeys(routepath) routekeys = frozenset([key['name'] for key in routelist \ if isinstance(key, dict)]) # Build a req list with all the regexp requirements for our args self.reqs = kargs.get('requirements', {}) self.req_regs = {} for key, val in self.reqs.iteritems(): self.req_regs[key] = re.compile('^' + val + '$') # Update our defaults and set new default keys if needed. defaults # needs to be saved (self.defaults, defaultkeys) = self._defaults(routekeys, reserved_keys, kargs) # Save the maximum keys we could utilize self.maxkeys = defaultkeys | routekeys # Populate our minimum keys, and save a copy of our backward keys for # quicker generation later (self.minkeys, self.routebackwards) = self._minkeys(routelist[:]) # Populate our hardcoded keys, these are ones that are set and don't # exist in the route self.hardcoded = frozenset([key for key in self.maxkeys \ if key not in routekeys and self.defaults[key] is not None]) def _pathkeys(self, routepath): """Utility function to walk the route, and pull out the valid dynamic/wildcard keys.""" collecting = False current = '' done_on = '' var_type = '' just_started = False routelist = [] for char in routepath: if char in [':', '*'] and not collecting: just_started = True collecting = True var_type = char if len(current) > 0: routelist.append(current) current = '' elif collecting and just_started: just_started = False if char == '(': done_on = ')' else: current = char done_on = self.done_chars + ('-',) elif collecting and char not in done_on: current += char elif collecting: collecting = False routelist.append(dict(type=var_type, name=current)) if char in self.done_chars: routelist.append(char) done_on = var_type = current = '' else: current += char if collecting: routelist.append(dict(type=var_type, name=current)) elif current: routelist.append(current) return routelist def _minkeys(self, routelist): """Utility function to walk the route backwards Will also determine the minimum keys we can handle to generate a working route. routelist is a list of the '/' split route path defaults is a dict of all the defaults provided for the route """ minkeys = [] backcheck = routelist[:] gaps = False backcheck.reverse() for part in backcheck: if not isinstance(part, dict) and part not in self.done_chars: gaps = True continue elif not isinstance(part, dict): continue key = part['name'] if self.defaults.has_key(key) and not gaps: continue minkeys.append(key) gaps = True return (frozenset(minkeys), backcheck) def _defaults(self, routekeys, reserved_keys, kargs): """Creates default set with values stringified Put together our list of defaults, stringify non-None values and add in our action/id default if they use it and didn't specify it defaultkeys is a list of the currently assumed default keys routekeys is a list of the keys found in the route path reserved_keys is a list of keys that are not """ defaults = {} # Add in a controller/action default if they don't exist if 'controller' not in routekeys and 'controller' not in kargs \ and not self.explicit: kargs['controller'] = 'content' if 'action' not in routekeys and 'action' not in kargs \ and not self.explicit: kargs['action'] = 'index' defaultkeys = frozenset([key for key in kargs.keys() \ if key not in reserved_keys]) for key in defaultkeys: if kargs[key] != None: defaults[key] = unicode(kargs[key]) else: defaults[key] = None if 'action' in routekeys and not defaults.has_key('action') \ and not self.explicit: defaults['action'] = 'index' if 'id' in routekeys and not defaults.has_key('id') \ and not self.explicit: defaults['id'] = None newdefaultkeys = frozenset([key for key in defaults.keys() \ if key not in reserved_keys]) return (defaults, newdefaultkeys) def makeregexp(self, clist): """Create a regular expression for matching purposes Note: This MUST be called before match can function properly. clist should be a list of valid controller strings that can be matched, for this reason makeregexp should be called by the web framework after it knows all available controllers that can be utilized. """ (reg, noreqs, allblank) = self.buildnextreg(self.routelist, clist) if not reg: reg = '/' reg = reg + '(/)?' + '$' if not reg.startswith('/'): reg = '/' + reg reg = '^' + reg self.regexp = reg self.regmatch = re.compile(reg) def buildnextreg(self, path, clist): """Recursively build our regexp given a path, and a controller list. Returns the regular expression string, and two booleans that can be ignored as they're only used internally by buildnextreg. """ if path: part = path[0] else: part = '' reg = '' # noreqs will remember whether the remainder has either a string # match, or a non-defaulted regexp match on a key, allblank remembers # if the rest could possible be completely empty (rest, noreqs, allblank) = ('', True, True) if len(path[1:]) > 0: self.prior = part (rest, noreqs, allblank) = self.buildnextreg(path[1:], clist) if isinstance(part, dict) and part['type'] == ':': var = part['name'] partreg = '' # First we plug in the proper part matcher if self.reqs.has_key(var): partreg = '(?P<' + var + '>' + self.reqs[var] + ')' elif var == 'controller': partreg = '(?P<' + var + '>' + '|'.join(map(re.escape, clist)) partreg += ')' elif self.prior in ['/', '#']: partreg = '(?P<' + var + '>[^' + self.prior + ']+?)' else: if not rest: partreg = '(?P<' + var + '>[^%s]+?)' % '/' else: partreg = '(?P<' + var + '>[^%s]+?)' % ''.join(self.done_chars) if self.reqs.has_key(var): noreqs = False if not self.defaults.has_key(var): allblank = False noreqs = False # Now we determine if its optional, or required. This changes # depending on what is in the rest of the match. If noreqs is # true, then its possible the entire thing is optional as there's # no reqs or string matches. if noreqs: # The rest is optional, but now we have an optional with a # regexp. Wrap to ensure that if we match anything, we match # our regexp first. It's still possible we could be completely # blank as we have a default if self.reqs.has_key(var) and self.defaults.has_key(var): reg = '(' + partreg + rest + ')?' # Or we have a regexp match with no default, so now being # completely blank form here on out isn't possible elif self.reqs.has_key(var): allblank = False reg = partreg + rest # If the character before this is a special char, it has to be # followed by this elif self.defaults.has_key(var) and \ self.prior in (',', ';', '.'): reg = partreg + rest # Or we have a default with no regexp, don't touch the allblank elif self.defaults.has_key(var): reg = partreg + '?' + rest # Or we have a key with no default, and no reqs. Not possible # to be all blank from here else: allblank = False reg = partreg + rest # In this case, we have something dangling that might need to be # matched else: # If they can all be blank, and we have a default here, we know # its safe to make everything from here optional. Since # something else in the chain does have req's though, we have # to make the partreg here required to continue matching if allblank and self.defaults.has_key(var): reg = '(' + partreg + rest + ')?' # Same as before, but they can't all be blank, so we have to # require it all to ensure our matches line up right else: reg = partreg + rest elif isinstance(part, dict) and part['type'] == '*': var = part['name'] if noreqs: if self.defaults.has_key(var): reg = '(?P<' + var + '>.*)' + rest else: reg = '(?P<' + var + '>.*)' + rest allblank = False noreqs = False else: if allblank and self.defaults.has_key(var): reg = '(?P<' + var + '>.*)' + rest elif self.defaults.has_key(var): reg = '(?P<' + var + '>.*)' + rest else: allblank = False noreqs = False reg = '(?P<' + var + '>.*)' + rest elif part and part[-1] in self.done_chars: if allblank: reg = re.escape(part[:-1]) + '(' + re.escape(part[-1]) + rest reg += ')?' else: allblank = False reg = re.escape(part) + rest # We have a normal string here, this is a req, and it prevents us from # being all blank else: noreqs = False allblank = False reg = re.escape(part) + rest return (reg, noreqs, allblank) def match(self, url, environ=None, sub_domains=False, sub_domains_ignore=None, domain_match=''): """Match a url to our regexp. While the regexp might match, this operation isn't guaranteed as there's other factors that can cause a match to fail even though the regexp succeeds (Default that was relied on wasn't given, requirement regexp doesn't pass, etc.). Therefore the calling function shouldn't assume this will return a valid dict, the other possible return is False if a match doesn't work out. """ # Static routes don't match, they generate only if self.static: return False if url.endswith('/') and len(url) > 1: url = url[:-1] match = self.regmatch.match(url) if not match: return False if not environ: environ = {} sub_domain = None if environ.get('HTTP_HOST') and sub_domains: host = environ['HTTP_HOST'].split(':')[0] sub_match = re.compile('^(.+?)\.%s$' % domain_match) subdomain = re.sub(sub_match, r'\1', host) if subdomain not in sub_domains_ignore and host != subdomain: sub_domain = subdomain if self.conditions: if self.conditions.has_key('method') and \ environ.get('REQUEST_METHOD') not in self.conditions['method']: return False # Check sub-domains? use_sd = self.conditions.get('sub_domain') if use_sd and not sub_domain: return False if isinstance(use_sd, list) and sub_domain not in use_sd: return False matchdict = match.groupdict() result = {} extras = frozenset(self.defaults.keys()) - frozenset(matchdict.keys()) for key, val in matchdict.iteritems(): if key != 'path_info' and self.encoding: # change back into python unicode objects from the URL # representation try: val = val and urllib.unquote_plus(val).decode(self.encoding, self.decode_errors) except UnicodeDecodeError: return False if not val and self.defaults.has_key(key) and self.defaults[key]: result[key] = self.defaults[key] else: result[key] = val for key in extras: result[key] = self.defaults[key] # Add the sub-domain if there is one if sub_domains: result['sub_domain'] = sub_domain # If there's a function, call it with environ and expire if it # returns False if self.conditions and self.conditions.has_key('function') and \ not self.conditions['function'](environ, result): return False return result def generate(self, _ignore_req_list=False, _append_slash=False, **kargs): """Generate a URL from ourself given a set of keyword arguments Toss an exception if this set of keywords would cause a gap in the url. """ # Verify that our args pass any regexp requirements if not _ignore_req_list: for key in self.reqs.keys(): val = kargs.get(key) if val and not self.req_regs[key].match(unicode(val)): return False # Verify that if we have a method arg, its in the method accept list. # Also, method will be changed to _method for route generation meth = kargs.get('method') if meth: if self.conditions and 'method' in self.conditions \ and meth.upper() not in self.conditions['method']: return False kargs.pop('method') routelist = self.routebackwards urllist = [] gaps = False for part in routelist: if isinstance(part, dict) and part['type'] == ':': arg = part['name'] # For efficiency, check these just once has_arg = kargs.has_key(arg) has_default = self.defaults.has_key(arg) # Determine if we can leave this part off # First check if the default exists and wasn't provided in the # call (also no gaps) if has_default and not has_arg and not gaps: continue # Now check to see if there's a default and it matches the # incoming call arg if (has_default and has_arg) and unicode(kargs[arg]) == \ unicode(self.defaults[arg]) and not gaps: continue # We need to pull the value to append, if the arg is None and # we have a default, use that if has_arg and kargs[arg] is None and has_default and not gaps: continue # Otherwise if we do have an arg, use that elif has_arg: val = kargs[arg] elif has_default and self.defaults[arg] is not None: val = self.defaults[arg] # No arg at all? This won't work else: return False urllist.append(url_quote(val, self.encoding)) if has_arg: del kargs[arg] gaps = True elif isinstance(part, dict) and part['type'] == '*': arg = part['name'] kar = kargs.get(arg) if kar is not None: urllist.append(url_quote(kar, self.encoding)) gaps = True elif part and part[-1] in self.done_chars: if not gaps and part in self.done_chars: continue elif not gaps: urllist.append(part[:-1]) gaps = True else: gaps = True urllist.append(part) else: gaps = True urllist.append(part) urllist.reverse() url = ''.join(urllist) if not url.startswith('/'): url = '/' + url extras = frozenset(kargs.keys()) - self.maxkeys if extras: if _append_slash and not url.endswith('/'): url += '/' url += '?' url += urllib.urlencode([(key, kargs[key]) for key in kargs \ if key in extras and \ (key != 'action' or key != 'controller')]) elif _append_slash and not url.endswith('/'): url += '/' return url class Mapper(object): """Mapper handles URL generation and URL recognition in a web application. Mapper is built handling dictionary's. It is assumed that the web application will handle the dictionary returned by URL recognition to dispatch appropriately. URL generation is done by passing keyword parameters into the generate function, a URL is then returned. """ def __init__(self, controller_scan=controller_scan, directory=None, always_scan=False, register=True, explicit=False): """Create a new Mapper instance All keyword arguments are optional. ``controller_scan`` Function reference that will be used to return a list of valid controllers used during URL matching. If ``directory`` keyword arg is present, it will be passed into the function during its call. This option defaults to a function that will scan a directory for controllers. ``directory`` Passed into controller_scan for the directory to scan. It should be an absolute path if using the default ``controller_scan`` function. ``always_scan`` Whether or not the ``controller_scan`` function should be run during every URL match. This is typically a good idea during development so the server won't need to be restarted anytime a controller is added. ``register`` Boolean used to determine if the Mapper should use ``request_config`` to register itself as the mapper. Since it's done on a thread-local basis, this is typically best used during testing though it won't hurt in other cases. ``explicit`` Boolean used to determine if routes should be connected with implicit defaults of:: {'controller':'content','action':'index','id':None} When set to True, these defaults will not be added to route connections and ``url_for`` will not use Route memory. Additional attributes that may be set after mapper initialization (ie, map.ATTRIBUTE = 'something'): ``encoding`` Used to indicate alternative encoding/decoding systems to use with both incoming URL's, and during Route generation when passed a Unicode string. Defaults to 'utf-8'. ``decode_errors`` How to handle errors in the encoding, generally ignoring any chars that don't convert should be sufficient. Defaults to 'ignore'. """ self.matchlist = [] self.maxkeys = {} self.minkeys = {} self.urlcache = {} self._created_regs = False self._created_gens = False self.prefix = None self.req_data = threadinglocal.local() self.directory = directory self.always_scan = always_scan self.controller_scan = controller_scan self._regprefix = None self._routenames = {} self.debug = False self.append_slash = False self.sub_domains = False self.sub_domains_ignore = [] self.domain_match = '[^\.\/]+?\.[^\.\/]+' self.explicit = explicit self.encoding = 'utf-8' self.decode_errors = 'ignore' if register: config = request_config() config.mapper = self def _envget(self): return getattr(self.req_data, 'environ', None) def _envset(self, env): self.req_data.environ = env def _envdel(self): del self.req_data.environ environ = property(_envget, _envset, _envdel) def connect(self, *args, **kargs): """Create and connect a new Route to the Mapper. Usage: .. code-block:: Python m = Mapper() m.connect(':controller/:action/:id') m.connect('date/:year/:month/:day', controller="blog", action="view") m.connect('archives/:page', controller="blog", action="by_page", requirements = { 'page':'\d{1,2}' }) m.connect('category_list', 'archives/category/:section', controller='blog', action='category', section='home', type='list') m.connect('home', '', controller='blog', action='view', section='home') """ routename = None if len(args) > 1: routename = args[0] args = args[1:] if '_explicit' not in kargs: kargs['_explicit'] = self.explicit route = Route(*args, **kargs) # Apply encoding and errors if its not the defaults and the route # didn't have one passed in. if (self.encoding != 'utf-8' or self.decode_errors != 'ignore') and \ '_encoding' not in kargs: route.encoding = self.encoding route.decode_errors = self.decode_errors self.matchlist.append(route) if routename: self._routenames[routename] = route if route.static: return exists = False for key in self.maxkeys: if key == route.maxkeys: self.maxkeys[key].append(route) exists = True break if not exists: self.maxkeys[route.maxkeys] = [route] self._created_gens = False def _create_gens(self): """Create the generation hashes for route lookups""" # Use keys temporailly to assemble the list to avoid excessive # list iteration testing with "in" controllerlist = {} actionlist = {} # Assemble all the hardcoded/defaulted actions/controllers used for route in self.matchlist: if route.static: continue if route.defaults.has_key('controller'): controllerlist[route.defaults['controller']] = True if route.defaults.has_key('action'): actionlist[route.defaults['action']] = True # Setup the lists of all controllers/actions we'll add each route # to. We include the '*' in the case that a generate contains a # controller/action that has no hardcodes controllerlist = controllerlist.keys() + ['*'] actionlist = actionlist.keys() + ['*'] # Go through our list again, assemble the controllers/actions we'll # add each route to. If its hardcoded, we only add it to that dict key. # Otherwise we add it to every hardcode since it can be changed. gendict = {} # Our generated two-deep hash for route in self.matchlist: if route.static: continue clist = controllerlist alist = actionlist if 'controller' in route.hardcoded: clist = [route.defaults['controller']] if 'action' in route.hardcoded: alist = [unicode(route.defaults['action'])] for controller in clist: for action in alist: actiondict = gendict.setdefault(controller, {}) actiondict.setdefault(action, ([], {}))[0].append(route) self._gendict = gendict self._created_gens = True def create_regs(self, clist=None): """Creates regular expressions for all connected routes""" if clist is None: if self.directory: clist = self.controller_scan(self.directory) else: clist = self.controller_scan() for key, val in self.maxkeys.iteritems(): for route in val: route.makeregexp(clist) # Create our regexp to strip the prefix if self.prefix: self._regprefix = re.compile(self.prefix + '(.*)') self._created_regs = True def _match(self, url): """Internal Route matcher Matches a URL against a route, and returns a tuple of the match dict and the route object if a match is successfull, otherwise it returns empty. For internal use only. """ if not self._created_regs and self.controller_scan: self.create_regs() elif not self._created_regs: raise RouteException("You must generate the regular expressions before matching.") if self.always_scan: self.create_regs() matchlog = [] if self.prefix: if re.match(self._regprefix, url): url = re.sub(self._regprefix, r'\1', url) if not url: url = '/' else: return (None, None, matchlog) for route in self.matchlist: if route.static: if self.debug: matchlog.append(dict(route=route, static=True)) continue match = route.match(url, self.environ, self.sub_domains, self.sub_domains_ignore, self.domain_match) if self.debug: matchlog.append(dict(route=route, regexp=bool(match))) if match: return (match, route, matchlog) return (None, None, matchlog) def match(self, url): """Match a URL against against one of the routes contained. Will return None if no valid match is found. .. code-block:: Python resultdict = m.match('/joe/sixpack') """ if not url: raise RouteException('No URL provided, the minimum URL necessary' ' to match is "/".') result = self._match(url) if self.debug: return result[0], result[1], result[2] if result[0]: return result[0] return None def routematch(self, url): """Match a URL against against one of the routes contained. Will return None if no valid match is found, otherwise a result dict and a route object is returned. .. code-block:: Python resultdict, route_obj = m.match('/joe/sixpack') """ result = self._match(url) if self.debug: return result[0], result[1], result[2] if result[0]: return result[0], result[1] return None def generate(self, **kargs): """Generate a route from a set of keywords Returns the url text, or None if no URL could be generated. .. code-block:: Python m.generate(controller='content',action='view',id=10) """ # Generate ourself if we haven't already if not self._created_gens: self._create_gens() if self.append_slash: kargs['_append_slash'] = True if not self.explicit: if 'controller' not in kargs: kargs['controller'] = 'content' if 'action' not in kargs: kargs['action'] = 'index' controller = kargs.get('controller', None) action = kargs.get('action', None) # If the URL didn't depend on the SCRIPT_NAME, we'll cache it # keyed by just by kargs; otherwise we need to cache it with # both SCRIPT_NAME and kargs: cache_key = unicode(kargs).encode('utf8') if self.environ: cache_key_script_name = '%s:%s' % ( self.environ.get('SCRIPT_NAME', ''), cache_key) else: cache_key_script_name = cache_key # Check the url cache to see if it exists, use it if it does for key in [cache_key, cache_key_script_name]: if key in self.urlcache: return self.urlcache[key] actionlist = self._gendict.get(controller) or self._gendict.get('*') if not actionlist: return None (keylist, sortcache) = actionlist.get(action) or \ actionlist.get('*', (None, None)) if not keylist: return None keys = frozenset(kargs.keys()) cacheset = False cachekey = unicode(keys) cachelist = sortcache.get(cachekey) if cachelist: keylist = cachelist else: cacheset = True newlist = [] for route in keylist: if len(route.minkeys-keys) == 0: newlist.append(route) keylist = newlist def keysort(a, b): """Sorts two sets of sets, to order them ideally for matching.""" am = a.minkeys a = a.maxkeys b = b.maxkeys lendiffa = len(keys^a) lendiffb = len(keys^b) # If they both match, don't switch them if lendiffa == 0 and lendiffb == 0: return 0 # First, if a matches exactly, use it if lendiffa == 0: return -1 # Or b matches exactly, use it if lendiffb == 0: return 1 # Neither matches exactly, return the one with the most in # common if cmp(lendiffa, lendiffb) != 0: return cmp(lendiffa, lendiffb) # Neither matches exactly, but if they both have just as much # in common if len(keys&b) == len(keys&a): # Then we return the shortest of the two return cmp(len(a), len(b)) # Otherwise, we return the one that has the most in common else: return cmp(len(keys&b), len(keys&a)) keylist.sort(keysort) if cacheset: sortcache[cachekey] = keylist for route in keylist: fail = False for key in route.hardcoded: kval = kargs.get(key) if not kval: continue if kval != route.defaults[key]: fail = True break if fail: continue path = route.generate(**kargs) if path: if self.prefix: path = self.prefix + path if self.environ and self.environ.get('SCRIPT_NAME', '') != '' \ and not route.absolute: path = self.environ['SCRIPT_NAME'] + path key = cache_key_script_name else: key = cache_key if self.urlcache is not None: self.urlcache[key] = str(path) return str(path) else: continue return None def resource(self, member_name, collection_name, **kwargs): """Generate routes for a controller resource The member_name name should be the appropriate singular version of the resource given your locale and used with members of the collection. The collection_name name will be used to refer to the resource collection methods and should be a plural version of the member_name argument. By default, the member_name name will also be assumed to map to a controller you create. The concept of a web resource maps somewhat directly to 'CRUD' operations. The overlying things to keep in mind is that mapping a resource is about handling creating, viewing, and editing that resource. All keyword arguments are optional. ``controller`` If specified in the keyword args, the controller will be the actual controller used, but the rest of the naming conventions used for the route names and URL paths are unchanged. ``collection`` Additional action mappings used to manipulate/view the entire set of resources provided by the controller. Example:: map.resource('message', 'messages', collection={'rss':'GET'}) # GET /message;rss (maps to the rss action) # also adds named route "rss_message" ``member`` Additional action mappings used to access an individual 'member' of this controllers resources. Example:: map.resource('message', 'messages', member={'mark':'POST'}) # POST /message/1;mark (maps to the mark action) # also adds named route "mark_message" ``new`` Action mappings that involve dealing with a new member in the controller resources. Example:: map.resource('message', 'messages', new={'preview':'POST'}) # POST /message/new;preview (maps to the preview action) # also adds a url named "preview_new_message" ``path_prefix`` Prepends the URL path for the Route with the path_prefix given. This is most useful for cases where you want to mix resources or relations between resources. ``name_prefix`` Perpends the route names that are generated with the name_prefix given. Combined with the path_prefix option, it's easy to generate route names and paths that represent resources that are in relations. Example:: map.resource('message', 'messages', controller='categories', path_prefix='/category/:category_id', name_prefix="category_") # GET /category/7/message/1 # has named route "category_message" ``parent_resource`` A ``dict`` containing information about the parent resource, for creating a nested resource. It should contain the ``member_name`` and ``collection_name`` of the parent resource. This ``dict`` will be available via the associated ``Route`` object which can be accessed during a request via ``request.environ['routes.route']`` If ``parent_resource`` is supplied and ``path_prefix`` isn't, ``path_prefix`` will be generated from ``parent_resource`` as "<parent collection name>/:<parent member name>_id". If ``parent_resource`` is supplied and ``name_prefix`` isn't, ``name_prefix`` will be generated from ``parent_resource`` as "<parent member name>_". Example:: >>> from routes.util import url_for >>> m = Mapper() >>> m.resource('location', 'locations', ... parent_resource=dict(member_name='region', ... collection_name='regions')) >>> # path_prefix is "regions/:region_id" >>> # name prefix is "region_" >>> url_for('region_locations', region_id=13) '/regions/13/locations' >>> url_for('region_new_location', region_id=13) '/regions/13/locations/new' >>> url_for('region_location', region_id=13, id=60) '/regions/13/locations/60' >>> url_for('region_edit_location', region_id=13, id=60) '/regions/13/locations/60;edit' Overriding generated ``path_prefix``:: >>> m = Mapper() >>> m.resource('location', 'locations', ... parent_resource=dict(member_name='region', ... collection_name='regions'), ... path_prefix='areas/:area_id') >>> # name prefix is "region_" >>> url_for('region_locations', area_id=51) '/areas/51/locations' Overriding generated ``name_prefix``:: >>> m = Mapper() >>> m.resource('location', 'locations', ... parent_resource=dict(member_name='region', ... collection_name='regions'), ... name_prefix='') >>> # path_prefix is "regions/:region_id" >>> url_for('locations', region_id=51) '/regions/51/locations' """ collection = kwargs.pop('collection', {}) member = kwargs.pop('member', {}) new = kwargs.pop('new', {}) path_prefix = kwargs.pop('path_prefix', None) name_prefix = kwargs.pop('name_prefix', None) parent_resource = kwargs.pop('parent_resource', None) # Generate ``path_prefix`` if ``path_prefix`` wasn't specified and # ``parent_resource`` was. Likewise for ``name_prefix``. Make sure # that ``path_prefix`` and ``name_prefix`` *always* take precedence if # they are specified--in particular, we need to be careful when they # are explicitly set to "". if parent_resource is not None: if path_prefix is None: path_prefix = '%s/:%s_id' % (parent_resource['collection_name'], parent_resource['member_name']) if name_prefix is None: name_prefix = '%s_' % parent_resource['member_name'] else: if path_prefix is None: path_prefix = '' if name_prefix is None: name_prefix = '' # Ensure the edit and new actions are in and GET member['edit'] = 'GET' new.update({'new': 'GET'}) # Make new dict's based off the old, except the old values become keys, # and the old keys become items in a list as the value def swap(dct, newdct): """Swap the keys and values in the dict, and uppercase the values from the dict during the swap.""" for key, val in dct.iteritems(): newdct.setdefault(val.upper(), []).append(key) return newdct collection_methods = swap(collection, {}) member_methods = swap(member, {}) new_methods = swap(new, {}) # Insert create, update, and destroy methods collection_methods.setdefault('POST', []).insert(0, 'create') member_methods.setdefault('PUT', []).insert(0, 'update') member_methods.setdefault('DELETE', []).insert(0, 'delete') # If there's a path prefix option, use it with the controller controller = strip_slashes(collection_name) path_prefix = strip_slashes(path_prefix) if path_prefix: path = path_prefix + '/' + controller else: path = controller collection_path = path new_path = path + "/new" member_path = path + "/:(id)" options = {'controller':kwargs.get('controller', controller)} options = { 'controller': kwargs.get('controller', controller), '_member_name': member_name, '_collection_name': collection_name, '_parent_resource': parent_resource, } def requirements_for(meth): """Returns a new dict to be used for all route creation as the route options""" opts = options.copy() if method != 'any': opts['conditions'] = {'method':[meth.upper()]} return opts # Add the routes for handling collection methods for method, lst in collection_methods.iteritems(): primary = (method != 'GET' and lst.pop(0)) or None route_options = requirements_for(method) for action in lst: route_options['action'] = action route_name = "%s%s_%s" % (name_prefix, action, collection_name) self.connect(route_name, "%s;%s" % (collection_path, action), **route_options) self.connect("formatted_" + route_name, "%s.:(format);%s" % \ (collection_path, action), **route_options) if primary: route_options['action'] = primary self.connect(collection_path, **route_options) self.connect("%s.:(format)" % collection_path, **route_options) # Specifically add in the built-in 'index' collection method and its # formatted version self.connect(name_prefix + collection_name, collection_path, action='index', conditions={'method':['GET']}, **options) self.connect("formatted_" + name_prefix + collection_name, collection_path + ".:(format)", action='index', conditions={'method':['GET']}, **options) # Add the routes that deal with new resource methods for method, lst in new_methods.iteritems(): route_options = requirements_for(method) for action in lst: path = (action == 'new' and new_path) or "%s;%s" % (new_path, action) name = "new_" + member_name if action != 'new': name = action + "_" + name route_options['action'] = action self.connect(name_prefix + name, path, **route_options) path = (action == 'new' and new_path + '.:(format)') or \ "%s.:(format);%s" % (new_path, action) self.connect("formatted_" + name_prefix + name, path, **route_options) requirements_regexp = '[\w\-_]+' # Add the routes that deal with member methods of a resource for method, lst in member_methods.iteritems(): route_options = requirements_for(method) route_options['requirements'] = {'id':requirements_regexp} if method not in ['POST', 'GET', 'any']: primary = lst.pop(0) else: primary = None for action in lst: route_options['action'] = action self.connect("%s%s_%s" % (name_prefix, action, member_name), "%s;%s" % (member_path, action), **route_options) self.connect("formatted_%s%s_%s" % (name_prefix, action, member_name), "%s.:(format);%s" % (member_path, action), **route_options) if primary: route_options['action'] = primary self.connect(member_path, **route_options) # Specifically add the member 'show' method route_options = requirements_for('GET') route_options['action'] = 'show' route_options['requirements'] = {'id':requirements_regexp} self.connect(name_prefix + member_name, member_path, **route_options) self.connect("formatted_" + name_prefix + member_name, member_path + ".:(format)", **route_options)
Python
try: import threading except ImportError: # No threads, so "thread local" means process-global class local(object): pass else: try: local = threading.local except AttributeError: # Added in 2.4, but now we'll have to define it ourselves import thread class local(object): def __init__(self): self.__dict__['__objs'] = {} def __getattr__(self, attr, g=thread.get_ident): try: return self.__dict__['__objs'][g()][attr] except KeyError: raise AttributeError( "No variable %s defined for the thread %s" % (attr, g())) def __setattr__(self, attr, value, g=thread.get_ident): self.__dict__['__objs'].setdefault(g(), {})[attr] = value def __delattr__(self, attr, g=thread.get_ident): try: del self.__dict__['__objs'][g()][attr] except KeyError: raise AttributeError( "No variable %s defined for thread %s" % (attr, g()))
Python
"""Utility functions for use in templates / controllers *PLEASE NOTE*: Many of these functions expect an initialized RequestConfig object. This is expected to have been initialized for EACH REQUEST by the web framework. """ import os import re import urllib from routes import request_config def _screenargs(kargs): """ Private function that takes a dict, and screens it against the current request dict to determine what the dict should look like that is used. This is responsible for the requests "memory" of the current. """ config = request_config() if config.mapper.explicit and config.mapper.sub_domains: return _subdomain_check(config, kargs) elif config.mapper.explicit: return kargs controller_name = kargs.get('controller') if controller_name and controller_name.startswith('/'): # If the controller name starts with '/', ignore route memory kargs['controller'] = kargs['controller'][1:] return kargs elif controller_name and not kargs.has_key('action'): # Fill in an action if we don't have one, but have a controller kargs['action'] = 'index' memory_kargs = getattr(config, 'mapper_dict', {}).copy() # Remove keys from memory and kargs if kargs has them as None for key in [key for key in kargs.keys() if kargs[key] is None]: del kargs[key] if memory_kargs.has_key(key): del memory_kargs[key] # Merge the new args on top of the memory args memory_kargs.update(kargs) # Setup a sub-domain if applicable if config.mapper.sub_domains: memory_kargs = _subdomain_check(config, memory_kargs) return memory_kargs def _subdomain_check(config, kargs): """Screen the kargs for a subdomain and alter it appropriately depending on the current subdomain or lack therof.""" if config.mapper.sub_domains: subdomain = kargs.pop('sub_domain', None) fullhost = config.environ.get('HTTP_HOST') or \ config.environ.get('SERVER_NAME') hostmatch = fullhost.split(':') host = hostmatch[0] port = '' if len(hostmatch) > 1: port += ':' + hostmatch[1] sub_match = re.compile('^.+?\.(%s)$' % config.mapper.domain_match) domain = re.sub(sub_match, r'\1', host) if subdomain and not host.startswith(subdomain) and \ subdomain not in config.mapper.sub_domains_ignore: kargs['_host'] = subdomain + '.' + domain + port elif (subdomain in config.mapper.sub_domains_ignore or \ subdomain is None) and domain != host: kargs['_host'] = domain + port return kargs else: return kargs def _url_quote(string, encoding): """A Unicode handling version of urllib.quote_plus.""" if encoding: return urllib.quote_plus(unicode(string).encode(encoding), '/') else: return urllib.quote_plus(str(string), '/') def url_for(*args, **kargs): """Generates a URL All keys given to url_for are sent to the Routes Mapper instance for generation except for:: anchor specified the anchor name to be appened to the path host overrides the default (current) host if provided protocol overrides the default (current) protocol if provided qualified creates the URL with the host/port information as needed The URL is generated based on the rest of the keys. When generating a new URL, values will be used from the current request's parameters (if present). The following rules are used to determine when and how to keep the current requests parameters: * If the controller is present and begins with '/', no defaults are used * If the controller is changed, action is set to 'index' unless otherwise specified For example, if the current request yielded a dict of {'controller': 'blog', 'action': 'view', 'id': 2}, with the standard ':controller/:action/:id' route, you'd get the following results:: url_for(id=4) => '/blog/view/4', url_for(controller='/admin') => '/admin', url_for(controller='admin') => '/admin/view/2' url_for(action='edit') => '/blog/edit/2', url_for(action='list', id=None) => '/blog/list' **Static and Named Routes** If there is a string present as the first argument, a lookup is done against the named routes table to see if there's any matching routes. The keyword defaults used with static routes will be sent in as GET query arg's if a route matches. If no route by that name is found, the string is assumed to be a raw URL. Should the raw URL begin with ``/`` then appropriate SCRIPT_NAME data will be added if present, otherwise the string will be used as the url with keyword args becoming GET query args. """ anchor = kargs.get('anchor') host = kargs.get('host') protocol = kargs.get('protocol') qualified = kargs.pop('qualified', None) # Remove special words from kargs, convert placeholders for key in ['anchor', 'host', 'protocol']: if kargs.get(key): del kargs[key] if kargs.has_key(key+'_'): kargs[key] = kargs.pop(key+'_') config = request_config() route = None static = False encoding = config.mapper.encoding url = '' if len(args) > 0: route = config.mapper._routenames.get(args[0]) if route and route.defaults.has_key('_static'): static = True url = route.routepath # No named route found, assume the argument is a relative path if not route: static = True url = args[0] if url.startswith('/') and hasattr(config, 'environ') \ and config.environ.get('SCRIPT_NAME'): url = config.environ.get('SCRIPT_NAME') + url if static: if kargs: url += '?' query_args = [] for key, val in kargs.iteritems(): query_args.append("%s=%s" % ( urllib.quote_plus(unicode(key).encode(encoding)), urllib.quote_plus(unicode(val).encode(encoding)))) url += '&'.join(query_args) if not static: if route: newargs = route.defaults.copy() newargs.update(kargs) # If this route has a filter, apply it if route.filter: newargs = route.filter(newargs) # Handle sub-domains newargs = _subdomain_check(config, newargs) else: newargs = _screenargs(kargs) anchor = newargs.pop('_anchor', None) or anchor host = newargs.pop('_host', None) or host protocol = newargs.pop('_protocol', None) or protocol url = config.mapper.generate(**newargs) if anchor: url += '#' + _url_quote(anchor, encoding) if host or protocol or qualified: if not host and not qualified: # Ensure we don't use a specific port, as changing the protocol # means that we most likely need a new port host = config.host.split(':')[0] elif not host: host = config.host if not protocol: protocol = config.protocol if url is not None: url = protocol + '://' + host + url if not isinstance(url, str) and url is not None: raise Exception("url_for can only return a string or None, got " " unicode instead: %s" % url) return url def redirect_to(*args, **kargs): """Issues a redirect based on the arguments. Redirect's *should* occur as a "302 Moved" header, however the web framework may utilize a different method. All arguments are passed to url_for to retrieve the appropriate URL, then the resulting URL it sent to the redirect function as the URL. """ target = url_for(*args, **kargs) config = request_config() return config.redirect(target) def controller_scan(directory=None): """Scan a directory for python files and use them as controllers""" if directory is None: return [] def find_controllers(dirname, prefix=''): """Locate controllers in a directory""" controllers = [] for fname in os.listdir(dirname): filename = os.path.join(dirname, fname) if os.path.isfile(filename) and \ re.match('^[^_]{1,1}.*\.py$', fname): controllers.append(prefix + fname[:-3]) elif os.path.isdir(filename): controllers.extend(find_controllers(filename, prefix=prefix+fname+'/')) return controllers def longest_first(fst, lst): """Compare the length of one string to another, shortest goes first""" return cmp(len(lst), len(fst)) controllers = find_controllers(directory) controllers.sort(longest_first) return controllers class RouteException(Exception): """Tossed during Route exceptions""" pass
Python
"""Provides common classes and functions most users will want access to.""" import threadinglocal, sys class _RequestConfig(object): """ RequestConfig thread-local singleton The Routes RequestConfig object is a thread-local singleton that should be initialized by the web framework that is utilizing Routes. """ __shared_state = threadinglocal.local() def __getattr__(self, name): return getattr(self.__shared_state, name) def __setattr__(self, name, value): """ If the name is environ, load the wsgi envion with load_wsgi_environ and set the environ """ if name == 'environ': self.load_wsgi_environ(value) return self.__shared_state.__setattr__(name, value) return self.__shared_state.__setattr__(name, value) def __delattr__(self, name): delattr(self.__shared_state, name) def load_wsgi_environ(self, environ): """ Load the protocol/server info from the environ and store it. Also, match the incoming URL if there's already a mapper, and store the resulting match dict in mapper_dict. """ if environ.get('HTTPS') or environ.get('wsgi.url_scheme') == 'https': self.__shared_state.protocol = 'https' else: self.__shared_state.protocol = 'http' if hasattr(self, 'mapper'): self.mapper.environ = environ if 'PATH_INFO' in environ and hasattr(self, 'mapper'): mapper = self.mapper path = environ['PATH_INFO'] result = mapper.routematch(path) if result is not None: self.__shared_state.mapper_dict = result[0] self.__shared_state.route = result[1] else: self.__shared_state.mapper_dict = None self.__shared_state.route = None if environ.get('HTTP_HOST'): self.__shared_state.host = environ['HTTP_HOST'] else: self.__shared_state.host = environ['SERVER_NAME'] if environ['wsgi.url_scheme'] == 'https': if environ['SERVER_PORT'] != '443': self.__shared_state.host += ':' + environ['SERVER_PORT'] else: if environ['SERVER_PORT'] != '80': self.__shared_state.host += ':' + environ['SERVER_PORT'] def request_config(original=False): """ Returns the Routes RequestConfig object. To get the Routes RequestConfig: >>> from routes import * >>> config = request_config() The following attributes must be set on the config object every request: mapper mapper should be a Mapper instance thats ready for use host host is the hostname of the webapp protocol protocol is the protocol of the current request mapper_dict mapper_dict should be the dict returned by mapper.match() redirect redirect should be a function that issues a redirect, and takes a url as the sole argument prefix (optional) Set if the application is moved under a URL prefix. Prefix will be stripped before matching, and prepended on generation environ (optional) Set to the WSGI environ for automatic prefix support if the webapp is underneath a 'SCRIPT_NAME' Setting the environ will use information in environ to try and populate the host/protocol/mapper_dict options if you've already set a mapper. **Using your own requst local** If you have your own request local object that you'd like to use instead of the default thread local provided by Routes, you can configure Routes to use it:: from routes import request_config() config = request_config() if hasattr(config, 'using_request_local'): config.request_local = YourLocalCallable config = request_config() Once you have configured request_config, its advisable you retrieve it again to get the object you wanted. The variable you assign to request_local is assumed to be a callable that will get the local config object you wish. This example tests for the presence of the 'using_request_local' attribute which will be present if you haven't assigned it yet. This way you can avoid repeat assignments of the request specific callable. Should you want the original object, perhaps to change the callable its using or stop this behavior, call request_config(original=True). """ obj = _RequestConfig() if hasattr(obj, 'request_local') and original is False: return getattr(obj, 'request_local')() else: obj.using_request_local = False return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
Python
"""Routes WSGI Middleware""" import re import urllib import logging try: from paste.wsgiwrappers import WSGIRequest except: pass from routes.base import request_config log = logging.getLogger('routes.middleware') class RoutesMiddleware(object): """Routing middleware that handles resolving the PATH_INFO in addition to optionally recognizing method overriding.""" def __init__(self, wsgi_app, mapper, use_method_override=True, path_info=True): """Create a Route middleware object Using the use_method_override keyword will require Paste to be installed, and your application should use Paste's WSGIRequest object as it will properly handle POST issues with wsgi.input should Routes check it. If path_info is True, then should a route var contain path_info, the SCRIPT_NAME and PATH_INFO will be altered accordingly. This should be used with routes like: .. code-block:: Python map.connect('blog/*path_info', controller='blog', path_info='') """ self.app = wsgi_app self.mapper = mapper self.use_method_override = use_method_override self.path_info = path_info log.debug("""Initialized with method overriding = %s, and path info altering = %s""", use_method_override, path_info) def __call__(self, environ, start_response): """Resolves the URL in PATH_INFO, and uses wsgi.routing_args to pass on URL resolver results.""" config = request_config() config.mapper = self.mapper old_method = None if self.use_method_override: req = WSGIRequest(environ) req.errors = 'ignore' if '_method' in environ.get('QUERY_STRING', '') and \ '_method' in req.GET: old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.GET['_method'].upper() log.debug("_method found in QUERY_STRING, altering request" " method to %s", environ['REQUEST_METHOD']) elif environ['REQUEST_METHOD'] == 'POST' and \ 'application/x-www-form-urlencoded' in environ.get('CONTENT_TYPE', '') \ and'_method' in req.POST: old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.POST['_method'].upper() log.debug("_method found in POST data, altering request " "method to %s", environ['REQUEST_METHOD']) config.environ = environ match = config.mapper_dict route = config.route if old_method: environ['REQUEST_METHOD'] = old_method urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO']) if not match: match = {} log.debug("No route matched for %s", urlinfo) else: log.debug("Matched %s", urlinfo) log.debug("Route path: '%s', defaults: %s", route.routepath, route.defaults) log.debug("Match dict: %s", match) for key, val in match.iteritems(): if val and isinstance(val, basestring): match[key] = urllib.unquote_plus(val) environ['wsgiorg.routing_args'] = ((), match) environ['routes.route'] = route # If the route included a path_info attribute and it should be used to # alter the environ, we'll pull it out if self.path_info and match.get('path_info'): oldpath = environ['PATH_INFO'] newpath = match.get('path_info') or '' environ['PATH_INFO'] = newpath if not environ['PATH_INFO'].startswith('/'): environ['PATH_INFO'] = '/' + environ['PATH_INFO'] environ['SCRIPT_NAME'] += re.sub(r'^(.*?)/' + newpath + '$', r'\1', oldpath) if environ['SCRIPT_NAME'].endswith('/'): environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1] response = self.app(environ, start_response) del config.environ del self.mapper.environ return response
Python
maxVf = 200 # Generating the header head = """// Copyright qiuc12@gmail.com // This file is generated autmatically by python. DONT MODIFY IT! #pragma once #include <OleAuto.h> class FakeDispatcher; HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...); extern "C" void DualProcessCommandWrap(); class FakeDispatcherBase : public IDispatch { private:""" pattern = """ \tvirtual HRESULT __stdcall fv{0}(char x) {{ \t\tva_list va = &x; \t\tHRESULT ret = ProcessCommand({0}, va); \t\tva_end(va); \t\treturn ret; \t}} """ pattern = """ \tvirtual HRESULT __stdcall fv{0}();""" end = """ protected: \tconst static int kMaxVf = {0}; }}; """ f = open("FakeDispatcherBase.h", "w") f.write(head) for i in range(0, maxVf): f.write(pattern.format(i)) f.write(end.format(maxVf)) f.close() head = """; Copyright qiuc12@gmail.com ; This file is generated automatically by python. DON'T MODIFY IT! """ f = open("FakeDispatcherBase.asm", "w") f.write(head) f.write(".386\n") f.write(".model flat\n") f.write("_DualProcessCommandWrap proto\n") ObjFormat = "?fv{0}@FakeDispatcherBase@@EAGJXZ" for i in range(0, maxVf): f.write("PUBLIC " + ObjFormat.format(i) + "\n") f.write(".code\n") for i in range(0, maxVf): f.write(ObjFormat.format(i) + " proc\n") f.write(" push {0}\n".format(i)) f.write(" jmp _DualProcessCommandWrap\n") f.write(ObjFormat.format(i) + " endp\n") f.write("\nend\n") f.close()
Python
#!/usr/bin/env python # This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import hashlib, re from androguard.core.androconf import error, warning, debug, set_debug, get_debug from androguard.core.bytecodes import dvm from androguard.core.analysis import analysis import elsim DEFAULT_SIGNATURE = analysis.SIGNATURE_L0_4 def filter_sim_value_meth( v ) : if v >= 0.2 : return 1.0 return v class CheckSumMeth : def __init__(self, m1, sim) : self.m1 = m1 self.sim = sim self.buff = "" self.entropy = 0.0 self.signature = None code = m1.m.get_code() if code != None : bc = code.get_bc() for i in bc.get() : self.buff += dvm.clean_name_instruction( i ) self.buff += dvm.static_operand_instruction( i ) self.entropy, _ = sim.entropy( self.buff ) def get_signature(self) : if self.signature == None : self.signature = self.m1.vmx.get_method_signature( self.m1.m, predef_sign = DEFAULT_SIGNATURE ).get_string() self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature def get_signature_entropy(self) : if self.signature == None : self.signature = self.m1.vmx.get_method_signature( self.m1.m, predef_sign = DEFAULT_SIGNATURE ).get_string() self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature_entropy def get_entropy(self) : return self.entropy def get_buff(self) : return self.buff def filter_checksum_meth_basic( m1, sim ) : return CheckSumMeth( m1, sim ) def filter_sim_meth_old( m1, m2, sim ) : a1 = m1.checksum a2 = m2.checksum e1 = a1.get_entropy() e2 = a2.get_entropy() return (max(e1, e2) - min(e1, e2)) def filter_sim_meth_basic( sim, m1, m2 ) : ncd1, _ = sim.ncd( m1.checksum.get_signature(), m2.checksum.get_signature() ) return ncd1 # ncd2, _ = sim.ncd( m1.checksum.get_buff(), m2.checksum.get_buff() ) # return (ncd1 + ncd2) / 2.0 def filter_sort_meth_basic( j, x, value ) : z = sorted(x.iteritems(), key=lambda (k,v): (v,k)) if get_debug() : for i in z : debug("\t %s %f" %(i[0].get_info(), i[1])) if z[:1][0][1] > value : return [] return z[:1] def filter_sim_bb_basic( sim, bb1, bb2 ) : ncd, _ = sim.ncd( bb1.checksum.get_buff(), bb2.checksum.get_buff() ) return ncd class CheckSumBB : def __init__(self, basic_block, sim) : self.basic_block = basic_block self.buff = "" for i in self.basic_block.bb.ins : self.buff += dvm.clean_name_instruction( i ) self.buff += dvm.static_operand_instruction( i ) #self.hash = hashlib.sha256( self.buff + "%d%d" % (len(basic_block.childs), len(basic_block.fathers)) ).hexdigest() self.hash = hashlib.sha256( self.buff ).hexdigest() def get_buff(self) : return self.buff def get_hash(self) : return self.hash def filter_checksum_bb_basic( basic_block, sim ) : return CheckSumBB( basic_block, sim ) DIFF_INS_TAG = { "ORIG" : 0, "ADD" : 1, "REMOVE" : 2 } class DiffBB : def __init__(self, bb1, bb2, info) : self.bb1 = bb1 self.bb2 = bb2 self.info = info self.start = self.bb1.start self.end = self.bb1.end self.name = self.bb1.name self.di = None self.ins = [] def diff_ins(self, di) : self.di = di off_add = {} off_rm = {} for i in self.di.add_ins : off_add[ i[0] ] = i for i in self.di.remove_ins : off_rm[ i[0] ] = i nb = 0 for i in self.bb1.ins : ok = False if nb in off_add : debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output())) self.ins.append( off_add[ nb ][2] ) setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] ) del off_add[ nb ] if nb in off_rm : debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output())) self.ins.append( off_rm[ nb ][2] ) setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] ) del off_rm[ nb ] ok = True if ok == False : self.ins.append( i ) debug("%d %s %s" % (nb, i.get_name(), i.get_output())) setattr( i, "diff_tag", DIFF_INS_TAG["ORIG"] ) nb += 1 #print nb, off_add, off_rm nbmax = nb if off_add != {} : nbmax = sorted(off_add)[-1] if off_rm != {} : nbmax = max(nbmax, sorted(off_rm)[-1]) while nb <= nbmax : if nb in off_add : debug("%d ADD %s %s" % (nb, off_add[ nb ][2].get_name(), off_add[ nb ][2].get_output())) self.ins.append( off_add[ nb ][2] ) setattr( off_add[ nb ][2], "diff_tag", DIFF_INS_TAG["ADD"] ) del off_add[ nb ] if nb in off_rm : debug("%d RM %s %s" % (nb, off_rm[ nb ][2].get_name(), off_rm[ nb ][2].get_output())) self.ins.append( off_rm[ nb ][2] ) setattr( off_rm[ nb ][2], "diff_tag", DIFF_INS_TAG["REMOVE"] ) del off_rm[ nb ] nb += 1 #print off_add, off_rm def set_childs(self, abb) : self.childs = self.bb1.childs for i in self.ins : if i == self.bb2.ins[-1] : childs = [] for c in self.bb2.childs : if c[2].name in abb : debug("SET %s %s" % (c[2], abb[ c[2].name ])) childs.append( (c[0], c[1], abb[ c[2].name ]) ) else : debug("SET ORIG %s" % str(c)) childs.append( c ) i.childs = childs def show(self) : print "\tADD INSTRUCTIONS :" for i in self.di.add_ins : print "\t\t", i[0], i[1], i[2].get_name(), i[2].get_output() print "\tREMOVE INSTRUCTIONS :" for i in self.di.remove_ins : print "\t\t", i[0], i[1], i[2].get_name(), i[2].get_output() class NewBB : def __init__(self, bb) : self.bb = bb self.start = self.bb.start self.end = self.bb.end self.name = self.bb.name self.ins = self.bb.ins def set_childs(self, abb) : childs = [] for c in self.bb.childs : if c[2].name in abb : debug("SET %s %s " % (c[2], abb[ c[2].name ])) childs.append( (c[0], c[1], abb[ c[2].name ]) ) else : debug("SET ORIG %s" % str(c)) childs.append( c ) self.childs = childs class DiffINS : def __init__(self, add_ins, remove_ins) : self.add_ins = add_ins self.remove_ins = remove_ins DIFF_BB_TAG = { "ORIG" : 0, "DIFF" : 1, "NEW" : 2 } class Method : def __init__(self, vm, vmx, m) : self.m = m self.vm = vm self.vmx = vmx self.mx = vmx.get_method( m ) self.sort_h = [] self.hash = {} self.sha256 = None def get_info(self) : return "%s %s %s %d" % (self.m.get_class_name(), self.m.get_name(), self.m.get_descriptor(), self.m.get_length()) def get_length(self) : return self.m.get_length() def set_checksum(self, fm) : self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() self.checksum = fm def add_attribute(self, func_meth, func_checksum_bb) : bb = {} bbhash = {} fm = func_meth( self.m, self.sim ) for i in self.mx.basic_blocks.get() : bb[ i.name ] = func_checksum_bb( i ) try : bbhash[ bb[ i.name ].get_hash() ].append( bb[ i.name ] ) except KeyError : bbhash[ bb[ i.name ].get_hash() ] = [] bbhash[ bb[ i.name ].get_hash() ].append( bb[ i.name ] ) self.checksum = fm self.bb = bb self.bb_sha256 = bbhash self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() def diff(self, func_sim_bb, func_diff_ins): if self.sort_h == [] : self.dbb = {} self.nbb = {} return bb1 = self.bb ### Dict for diff basic blocks ### vm1 basic block : vm2 basic blocks -> value (0.0 to 1.0) diff_bb = {} ### List to get directly all diff basic blocks direct_diff_bb = [] ### Dict for new basic blocks new_bb = {} ### Reverse Dict with matches diff basic blocks associated_bb = {} for b1 in bb1 : diff_bb[ bb1[ b1 ] ] = {} debug("%s 0x%x" % (b1, bb1[ b1 ].basic_block.end)) for i in self.sort_h : bb2 = i[0].bb b_z = diff_bb[ bb1[ b1 ] ] bb2hash = i[0].bb_sha256 # If b1 is in bb2 : # we can have one or more identical basic blocks to b1, we must add them if bb1[ b1 ].get_hash() in bb2hash : for equal_bb in bb2hash[ bb1[ b1 ].get_hash() ] : b_z[ equal_bb.basic_block.name ] = 0.0 # If b1 is not in bb2 : # we must check similarities between all bb2 else : for b2 in bb2 : b_z[ b2 ] = func_sim_bb( bb1[ b1 ], bb2[ b2 ], self.sim ) sorted_bb = sorted(b_z.iteritems(), key=lambda (k,v): (v,k)) debug("\t\t%s" % sorted_bb[:2]) for new_diff in sorted_bb : associated_bb[ new_diff[0] ] = bb1[ b1 ].basic_block if new_diff[1] == 0.0 : direct_diff_bb.append( new_diff[0] ) if sorted_bb[0][1] != 0.0 : diff_bb[ bb1[ b1 ] ] = (bb2[ sorted_bb[0][0] ], sorted_bb[0][1]) direct_diff_bb.append( sorted_bb[0][0] ) else : del diff_bb[ bb1[ b1 ] ] for i in self.sort_h : bb2 = i[0].bb for b2 in bb2 : if b2 not in direct_diff_bb : new_bb[ b2 ] = bb2[ b2 ] dbb = {} nbb = {} # Add all different basic blocks for d in diff_bb : dbb[ d.basic_block.name ] = DiffBB( d.basic_block, diff_bb[ d ][0].basic_block, diff_bb[ d ] ) # Add all new basic blocks for n in new_bb : nbb[ new_bb[ n ].basic_block ] = NewBB( new_bb[ n ].basic_block ) if n in associated_bb : del associated_bb[ n ] self.dbb = dbb self.nbb = nbb # Found diff instructions for d in dbb : func_diff_ins( dbb[d], self.sim ) # Set new childs for diff basic blocks # The instructions will be tag with a new flag "childs" for d in dbb : dbb[ d ].set_childs( associated_bb ) # Set new childs for new basic blocks for d in nbb : nbb[ d ].set_childs( associated_bb ) # Create and tag all (orig/diff/new) basic blocks self.create_bbs() def create_bbs(self) : dbb = self.dbb nbb = self.nbb # For same block : # tag = 0 # For diff block : # tag = 1 # For new block : # tag = 2 l = [] for bb in self.mx.basic_blocks.get() : if bb.name not in dbb : # add the original basic block bb.bb_tag = DIFF_BB_TAG["ORIG"] l.append( bb ) else : # add the diff basic block dbb[ bb.name ].bb_tag = DIFF_BB_TAG["DIFF"] l.append( dbb[ bb.name ] ) for i in nbb : # add the new basic block nbb[ i ].bb_tag = DIFF_BB_TAG["NEW"] l.append( nbb[ i ] ) # Sorted basic blocks by addr (orig, new, diff) l = sorted(l, key = lambda x : x.start) self.bbs = l def getsha256(self) : return self.sha256 def get_length(self) : if self.m.get_code() == None : return 0 return self.m.get_code().get_length() def show(self, details=False, exclude=[]) : print self.m.get_class_name(), self.m.get_name(), self.m.get_descriptor(), print "with", for i in self.sort_h : print i[0].m.get_class_name(), i[0].m.get_name(), i[0].m.get_descriptor(), i[1] print "\tDIFF BASIC BLOCKS :" for d in self.dbb : print "\t\t", self.dbb[d].bb1.name, " --->", self.dbb[d].bb2.name, ":", self.dbb[d].info[1] if details : self.dbb[d].show() print "\tNEW BASIC BLOCKS :" for b in self.nbb : print "\t\t", self.nbb[b].name # show diff ! if details : bytecode.PrettyShow2( self.bbs, exclude ) def show2(self, details=False) : print self.m.get_class_name(), self.m.get_name(), self.m.get_descriptor(), print self.get_length() for i in self.sort_h : print "\t", i[0].m.get_class_name(), i[0].m.get_name(), i[0].m.get_descriptor(), i[1] if details : bytecode.PrettyShow1( self.mx.basic_blocks.get() ) def filter_element_meth_basic(el, e) : return Method( e.vm, e.vmx, el ) class BasicBlock : def __init__(self, bb) : self.bb = bb def set_checksum(self, fm) : self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() self.checksum = fm def getsha256(self) : return self.sha256 def get_info(self) : return self.bb.name def show(self) : print self.bb.name def filter_element_bb_basic(el, e) : return BasicBlock( el ) def filter_sort_bb_basic( j, x, value ) : z = sorted(x.iteritems(), key=lambda (k,v): (v,k)) if get_debug() : for i in z : debug("\t %s %f" %(i[0].get_info(), i[1])) if z[:1][0][1] > value : return [] return z[:1] import re class FilterSkip : def __init__(self, size, regexp) : self.size = size self.regexp = regexp def skip(self, m) : if self.size != None and m.get_length() < self.size : return True if self.regexp != None and re.match(self.regexp, m.m.get_class_name()) != None : return True return False def set_regexp(self, e) : self.regexp = e def set_size(self, e) : if e != None : self.size = int(e) else : self.size = e class FilterNone : def skip(self, e) : return False FILTERS_DALVIK_SIM = { elsim.FILTER_ELEMENT_METH : filter_element_meth_basic, elsim.FILTER_CHECKSUM_METH : filter_checksum_meth_basic, elsim.FILTER_SIM_METH : filter_sim_meth_basic, elsim.FILTER_SORT_METH : filter_sort_meth_basic, elsim.FILTER_SORT_VALUE : 0.4, elsim.FILTER_SKIPPED_METH : FilterSkip(None, None), elsim.FILTER_SIM_VALUE_METH : filter_sim_value_meth, } class StringVM : def __init__(self, el) : self.el = el def set_checksum(self, fm) : self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() self.checksum = fm def get_length(self) : return len(self.el) def getsha256(self) : return self.sha256 def get_info(self) : return len(self.el), repr(self.el) def filter_element_meth_string(el, e) : return StringVM( el ) class CheckSumString : def __init__(self, m1, sim) : self.m1 = m1 self.sim = sim self.buff = self.m1.el def get_buff(self) : return self.buff def filter_checksum_meth_string( m1, sim ) : return CheckSumString( m1, sim ) def filter_sim_meth_string( sim, m1, m2 ) : ncd1, _ = sim.ncd( m1.checksum.get_buff(), m2.checksum.get_buff() ) return ncd1 def filter_sort_meth_string( j, x, value ) : z = sorted(x.iteritems(), key=lambda (k,v): (v,k)) if get_debug() : for i in z : debug("\t %s %f" %(i[0].get_info(), i[1])) if z[:1][0][1] > value : return [] return z[:1] FILTERS_DALVIK_SIM_STRING = { elsim.FILTER_ELEMENT_METH : filter_element_meth_string, elsim.FILTER_CHECKSUM_METH : filter_checksum_meth_string, elsim.FILTER_SIM_METH : filter_sim_meth_string, elsim.FILTER_SORT_METH : filter_sort_meth_string, elsim.FILTER_SORT_VALUE : 0.8, elsim.FILTER_SKIPPED_METH : FilterNone(), elsim.FILTER_SIM_VALUE_METH : filter_sim_value_meth, } FILTERS_DALVIK_BB = { elsim.FILTER_ELEMENT_METH : filter_element_bb_basic, elsim.FILTER_CHECKSUM_METH : filter_checksum_bb_basic, elsim.FILTER_SIM_METH : filter_sim_bb_basic, elsim.FILTER_SORT_METH : filter_sort_bb_basic, elsim.FILTER_SORT_VALUE : 0.8, elsim.FILTER_SKIPPED_METH : FilterNone(), elsim.FILTER_SIM_VALUE_METH : filter_sim_value_meth, } class ProxyDalvik : def __init__(self, vm, vmx) : self.vm = vm self.vmx = vmx def get_elements(self) : for i in self.vm.get_methods() : yield i class ProxyDalvikMethod : def __init__(self, el) : self.el = el def get_elements(self) : for j in self.el.mx.basic_blocks.get() : yield j class ProxyDalvikStringMultiple : def __init__(self, vm, vmx) : self.vm = vm self.vmx = vmx def get_elements(self) : for i in self.vmx.get_tainted_variables().get_strings() : yield i[1] #for i in self.vm.get_strings() : # yield i class ProxyDalvikStringOne : def __init__(self, vm, vmx) : self.vm = vm self.vmx = vmx def get_elements(self) : yield ''.join( self.vm.get_strings() ) def LCS(X, Y): m = len(X) n = len(Y) # An (m+1) times (n+1) matrix C = [[0] * (n+1) for i in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if X[i-1] == Y[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(C[i][j-1], C[i-1][j]) return C def getDiff(C, X, Y, i, j, a, r): if i > 0 and j > 0 and X[i-1] == Y[j-1]: getDiff(C, X, Y, i-1, j-1, a, r) debug(" " + "%02X" % ord(X[i-1])) else: if j > 0 and (i == 0 or C[i][j-1] >= C[i-1][j]): getDiff(C, X, Y, i, j-1, a, r) a.append( (j-1, Y[j-1]) ) debug(" + " + "%02X" % ord(Y[j-1])) elif i > 0 and (j == 0 or C[i][j-1] < C[i-1][j]): getDiff(C, X, Y, i-1, j, a, r) r.append( (i-1, X[i-1]) ) debug(" - " + "%02X" % ord(X[i-1])) def toString( bb, hS, rS ) : map_x = {} S = "" idx = 0 nb = 0 for i in bb.ins : ident = dvm.clean_name_instruction( i ) ident += dvm.static_operand_instruction( i ) if ident not in hS : hS[ ident ] = len(hS) rS[ chr( hS[ ident ] ) ] = ident S += chr( hS[ ident ] ) map_x[ nb ] = idx idx += i.get_length() nb += 1 return S, map_x class DiffInstruction : def __init__(self, bb, instruction) : self.bb = bb self.pos_instruction = instruction[0] self.offset = instruction[1] self.ins = instruction[2] def show(self) : print hex(self.bb.bb.start + self.offset), self.pos_instruction, self.ins.get_name(), self.ins.show_buff( self.bb.bb.start + self.offset ) class DiffBasicBlock : def __init__(self, x, y, added, deleted) : self.basic_block_x = x self.basic_block_y = y self.added = sorted(added, key=lambda x : x[1]) self.deleted = sorted(deleted, key=lambda x : x[1]) def get_added_elements(self) : for i in self.added : yield DiffInstruction( self.basic_block_x, i ) def get_deleted_elements(self) : for i in self.deleted : yield DiffInstruction( self.basic_block_y, i ) def filter_diff_bb(x, y) : final_add = [] final_rm = [] hS = {} rS = {} X, map_x = toString( x.bb, hS, rS ) Y, map_y = toString( y.bb, hS, rS ) debug("%s %d" % (repr(X), len(X))) debug("%s %d" % (repr(Y), len(Y))) m = len(X) n = len(Y) C = LCS( X, Y ) a = [] r = [] getDiff(C, X, Y, m, n, a, r) debug(a) debug(r) #set_debug() #print map_x, map_y, a, r debug("DEBUG ADD") for i in a : debug(" \t %s %s %s" % (i[0], y.bb.ins[ i[0] ].get_name(), y.bb.ins[ i[0] ].get_output())) final_add.append( (i[0], map_y[i[0]], y.bb.ins[ i[0] ]) ) debug("DEBUG REMOVE") for i in r : debug(" \t %s %s %s" % (i[0], x.bb.ins[ i[0] ].get_name(), x.bb.ins[ i[0] ].get_output())) final_rm.append( (i[0], map_x[i[0]], x.bb.ins[ i[0] ]) ) return DiffBasicBlock( y, x, final_add, final_rm ) FILTERS_DALVIK_DIFF_BB = { elsim.DIFF : filter_diff_bb, } class ProxyDalvikBasicBlock : def __init__(self, esim) : self.esim = esim def get_elements(self) : x = elsim.split_elements( self.esim, self.esim.get_similar_elements() ) for i in x : yield i, x[i] class DiffDalvikMethod : def __init__(self, m1, m2, els, eld) : self.m1 = m1 self.m2 = m2 self.els = els self.eld = eld def get_info_method(self, m) : return m.m.get_class_name(), m.m.get_name(), m.m.get_descriptor() def show(self) : print "[", self.get_info_method(self.m1), "]", "<->", "[", self.get_info_method(self.m2), "]" self.eld.show() self.els.show() self._show_elements( "NEW", self.els.get_new_elements() ) def _show_elements(self, info, elements) : for i in elements : print i.bb, hex(i.bb.start), hex(i.bb.end) #, i.bb.childs idx = i.bb.start for j in i.bb.ins : print "\t" + info, hex(idx), j.show(idx) print idx += j.get_length() print "\n" LIST_EXTERNAL_LIBS = [ "Lcom/google/gson", "Lorg/codehaus", "Lcom/openfeint", "Lcom/facebook", "Lorg/anddev", "Lcom/badlogic", "Lcom/rabbit", "Lme/kiip", "Lorg/cocos2d", "Ltwitter4j", "Lcom/paypal", "Lcom/electrotank", "Lorg/acra", "Lorg/apache", "Lcom/google/beintoogson", "Lcom/beintoo", "Lcom/scoreloop", "Lcom/MoreGames", #AD not covered "Lcom/mobfox", "Lcom/sponsorpay", "Lde/madvertise", "Lcom/tremorvideo", "Lcom/tapjoy", "Lcom/heyzap", ]
Python
""" Implementation of Charikar similarity hashes in Python. Most useful for creating 'fingerprints' of documents or metadata so you can quickly find duplicates or cluster items. Part of python-hashes by sangelone. See README and LICENSE. """ from hashtype import hashtype class simhash(hashtype): def create_hash(self, tokens): """Calculates a Charikar simhash with appropriate bitlength. Input can be any iterable, but for strings it will automatically break it into words first, assuming you don't want to iterate over the individual characters. Returns nothing. Reference used: http://dsrg.mff.cuni.cz/~holub/sw/shash """ if type(tokens) == str: tokens = tokens.split() v = [0]*self.hashbits for t in [self._string_hash(x) for x in tokens]: bitmask = 0 for i in xrange(self.hashbits): bitmask = 1 << i if t & bitmask: v[i] += 1 else: v[i] -= 1 fingerprint = 0 for i in xrange(self.hashbits): if v[i] >= 0: fingerprint += 1 << i self.hash = fingerprint def _string_hash(self, v): "A variable-length version of Python's builtin hash. Neat!" if v == "": return 0 else: x = ord(v[0])<<7 m = 1000003 mask = 2**self.hashbits-1 for c in v: x = ((x*m)^ord(c)) & mask x ^= len(v) if x == -1: x = -2 return x def similarity(self, other_hash): """Calculate how different this hash is from another simhash. Returns a float from 0.0 to 1.0 (inclusive) """ if type(other_hash) != simhash: raise Exception('Hashes must be of same type to find similarity') b = self.hashbits if b!= other_hash.hashbits: raise Exception('Hashes must be of equal size to find similarity') return float(b - self.hamming_distance(other_hash)) / b
Python
# This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import zlib, bz2 import math def entropy(data): entropy = 0.0 if len(data) == 0 : return entropy for x in range(256): p_x = float(data.count(chr(x)))/len(data) if p_x > 0: entropy += - p_x*math.log(p_x, 2) return entropy try : from ctypes import cdll, c_float, c_double, c_int, c_uint, c_void_p, Structure, addressof, cast, c_size_t #struct libsimilarity { # void *orig; # unsigned int size_orig; # void *cmp; # unsigned size_cmp; # unsigned int *corig; # unsigned int *ccmp; # # float res; #}; class LIBSIMILARITY_T(Structure) : _fields_ = [("orig", c_void_p), ("size_orig", c_size_t), ("cmp", c_void_p), ("size_cmp", c_size_t), ("corig", c_size_t), ("ccmp", c_size_t), ("res", c_float), ] def new_zero_native() : return c_size_t( 0 ) NATIVE_LIB = True except : NATIVE_LIB = False def new_zero_python() : return 0 ZLIB_COMPRESS = 0 BZ2_COMPRESS = 1 SMAZ_COMPRESS = 2 LZMA_COMPRESS = 3 XZ_COMPRESS = 4 SNAPPY_COMPRESS = 5 VCBLOCKSORT_COMPRESS = 6 H_COMPRESSOR = { "BZ2" : BZ2_COMPRESS, "ZLIB" : ZLIB_COMPRESS, "LZMA" : LZMA_COMPRESS, "XZ" : XZ_COMPRESS, "SNAPPY" : SNAPPY_COMPRESS, } HR_COMPRESSOR = { BZ2_COMPRESS : "BZ2", ZLIB_COMPRESS : "ZLIB", LZMA_COMPRESS : "LZMA", XZ_COMPRESS : "XZ", SNAPPY_COMPRESS : "SNAPPY", } class SIMILARITYBase(object) : def __init__(self, native_lib=False) : self.ctype = ZLIB_COMPRESS self.__caches = { ZLIB_COMPRESS : {}, BZ2_COMPRESS : {}, SMAZ_COMPRESS : {}, LZMA_COMPRESS : {}, XZ_COMPRESS : {}, SNAPPY_COMPRESS : {}, VCBLOCKSORT_COMPRESS : {}, } self.__rcaches = { ZLIB_COMPRESS : {}, BZ2_COMPRESS : {}, SMAZ_COMPRESS : {}, LZMA_COMPRESS : {}, XZ_COMPRESS : {}, SNAPPY_COMPRESS : {}, VCBLOCKSORT_COMPRESS : {}, } self.__ecaches = {} self.level = 9 if native_lib == True : self.new_zero = new_zero_native else : self.new_zero = new_zero_python def set_level(self, level) : self.level = level def get_in_caches(self, s) : try : return self.__caches[ self.ctype ][ zlib.adler32( s ) ] except KeyError : return self.new_zero() def get_in_rcaches(self, s1, s2) : try : return self.__rcaches[ self.ctype ][ zlib.adler32( s1 + s2 ) ] except KeyError : try : return self.__rcaches[ self.ctype ][ zlib.adler32( s2 + s1 ) ] except KeyError : return -1, -1 def add_in_caches(self, s, v) : h = zlib.adler32( s ) if h not in self.__caches[ self.ctype ] : self.__caches[ self.ctype ][ h ] = v def add_in_rcaches(self, s, v, r) : h = zlib.adler32( s ) if h not in self.__rcaches[ self.ctype ] : self.__rcaches[ self.ctype ][ h ] = (v, r) def clear_caches(self) : for i in self.__caches : self.__caches[i] = {} def add_in_ecaches(self, s, v, r) : h = zlib.adler32( s ) if h not in self.__ecaches : self.__ecaches[ h ] = (v, r) def get_in_ecaches(self, s1) : try : return self.__ecaches[ zlib.adler32( s1 ) ] except KeyError : return -1, -1 def __nb_caches(self, caches) : nb = 0 for i in caches : nb += len(caches[i]) return nb def set_compress_type(self, t): self.ctype = t def show(self) : print "ECACHES", len(self.__ecaches) print "RCACHES", self.__nb_caches( self.__rcaches ) print "CACHES", self.__nb_caches( self.__caches ) class SIMILARITYNative(SIMILARITYBase) : def __init__(self, path="./libsimilarity/libsimilarity.so") : super(SIMILARITYNative, self).__init__(True) self._u = cdll.LoadLibrary( path ) self._u.compress.restype = c_uint self._u.ncd.restype = c_int self._u.ncs.restype = c_int self._u.cmid.restype = c_int self._u.entropy.restype = c_double self._u.levenshtein.restype = c_uint self._u.kolmogorov.restype = c_uint self._u.bennett.restype = c_double self._u.RDTSC.restype = c_double self.__libsim_t = LIBSIMILARITY_T() self.set_compress_type( ZLIB_COMPRESS ) def raz(self) : del self._u del self.__libsim_t def compress(self, s1) : res = self._u.compress( self.level, cast( s1, c_void_p ), len( s1 ) ) return res def _sim(self, s1, s2, func) : end, ret = self.get_in_rcaches( s1, s2 ) if end != -1 : return end, ret self.__libsim_t.orig = cast( s1, c_void_p ) self.__libsim_t.size_orig = len(s1) self.__libsim_t.cmp = cast( s2, c_void_p ) self.__libsim_t.size_cmp = len(s2) corig = self.get_in_caches(s1) ccmp = self.get_in_caches(s2) self.__libsim_t.corig = addressof( corig ) self.__libsim_t.ccmp = addressof( ccmp ) ret = func( self.level, addressof( self.__libsim_t ) ) self.add_in_caches(s1, corig) self.add_in_caches(s2, ccmp) self.add_in_rcaches(s1+s2, self.__libsim_t.res, ret) return self.__libsim_t.res, ret def ncd(self, s1, s2) : return self._sim( s1, s2, self._u.ncd ) def ncs(self, s1, s2) : return self._sim( s1, s2, self._u.ncs ) def cmid(self, s1, s2) : return self._sim( s1, s2, self._u.cmid ) def kolmogorov(self, s1) : ret = self._u.kolmogorov( self.level, cast( s1, c_void_p ), len( s1 ) ) return ret, 0 def bennett(self, s1) : ret = self._u.bennett( self.level, cast( s1, c_void_p ), len( s1 ) ) return ret, 0 def entropy(self, s1) : end, ret = self.get_in_ecaches( s1 ) if end != -1 : return end, ret res = self._u.entropy( cast( s1, c_void_p ), len( s1 ) ) self.add_in_ecaches( s1, res, 0 ) return res, 0 def RDTSC(self) : return self._u.RDTSC() def levenshtein(self, s1, s2) : res = self._u.levenshtein( cast( s1, c_void_p ), len( s1 ), cast( s2, c_void_p ), len( s2 ) ) return res, 0 def set_compress_type(self, t): self.ctype = t self._u.set_compress_type(t) class SIMILARITYPython(SIMILARITYBase) : def __init__(self) : super(SIMILARITYPython, self).__init__() def set_compress_type(self, t): self.ctype = t if self.ctype != ZLIB_COMPRESS and self.ctype != BZ2_COMPRESS : print "warning: compressor %s is not supported (use zlib default compressor)" % HR_COMPRESSOR[ t ] self.ctype = ZLIB_COMPRESS def compress(self, s1) : return len(self._compress(s1)) def _compress(self, s1) : if self.ctype == ZLIB_COMPRESS : return zlib.compress( s1, self.level ) elif self.ctype == BZ2_COMPRESS : return bz2.compress( s1, self.level ) def _sim(self, s1, s2, func) : end, ret = self.get_in_rcaches( s1, s2 ) if end != -1 : return end, ret corig = self.get_in_caches(s1) ccmp = self.get_in_caches(s2) res, corig, ccmp, ret = func( s1, s2, corig, ccmp ) self.add_in_caches(s1, corig) self.add_in_caches(s2, ccmp) self.add_in_rcaches(s1+s2, res, ret) return res, ret def _ncd(self, s1, s2, s1size=0, s2size=0) : if s1size == 0 : s1size = self.compress(s1) if s2size == 0 : s2size = self.compress(s2) s3size = self.compress(s1+s2) smax = max(s1size, s2size) smin = min(s1size, s2size) res = (abs(s3size - smin)) / float(smax) if res > 1.0 : res = 1.0 return res, s1size, s2size, 0 def ncd(self, s1, s2) : return self._sim( s1, s2, self._ncd ) def ncs(self, s1, s2) : return self._sim( s1, s2, self._u.ncs ) def entropy(self, s1) : end, ret = self.get_in_ecaches( s1 ) if end != -1 : return end, ret res = entropy( s1 ) self.add_in_ecaches( s1, res, 0 ) return res, 0 class SIMILARITY : def __init__(self, path="./libsimilarity/libsimilarity.so", native_lib=True) : if native_lib == True and NATIVE_LIB == True: try : self.s = SIMILARITYNative( path ) except : self.s = SIMILARITYPython() else : self.s = SIMILARITYPython() def raz(self) : return self.s.raz() def set_level(self, level) : return self.s.set_level(level) def compress(self, s1) : return self.s.compress(s1) def ncd(self, s1, s2) : return self.s.ncd(s1, s2) def ncs(self, s1, s2) : return self.s.ncs(s1, s2) def cmid(self, s1, s2) : return self.s.cmid(s1, s2) def kolmogorov(self, s1) : return self.s.kolmogorov(s1) def bennett(self, s1) : return self.s.bennett(s1) def entropy(self, s1) : return self.s.entropy(s1) def RDTSC(self) : return self.s.RDTSC() def levenshtein(self, s1, s2) : return self.s.levenshtein(s1, s2) def set_compress_type(self, t): return self.s.set_compress_type(t) def show(self) : self.s.show()
Python
# This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import json class DBFormat: def __init__(self, filename): self.filename = filename self.D = {} try : fd = open(self.filename, "r") self.D = json.load( fd ) fd.close() except IOError : import logging logging.info("OOOOOPS") pass self.H = {} for i in self.D : self.H[i] = {} for j in self.D[i] : self.H[i][j] = {} for k in self.D[i][j] : self.H[i][j][k] = set() for e in self.D[i][j][k] : self.H[i][j][k].add( e ) def add_element(self, name, sname, sclass, elem): try : if elem not in self.D[ name ][ sname ][ sclass ] : self.D[ name ][ sname ][ sclass ].append( elem ) except KeyError : if name not in self.D : self.D[ name ] = {} self.D[ name ][ sname ] = {} self.D[ name ][ sname ][ sclass ] = [] self.D[ name ][ sname ][ sclass ].append( elem ) elif sname not in self.D[ name ] : self.D[ name ][ sname ] = {} self.D[ name ][ sname ][ sclass ] = [] self.D[ name ][ sname ][ sclass ].append( elem ) elif sclass not in self.D[ name ][ sname ] : self.D[ name ][ sname ][ sclass ] = [] self.D[ name ][ sname ][ sclass ].append( elem ) def is_present(self, elem) : for i in self.D : if elem in self.D[i] : return True, i return False, None def elems_are_presents(self, elems) : ret = {} for i in self.H: ret[i] = {} for j in self.H[i] : ret[i][j] = {} for k in self.H[i][j] : val = [self.H[i][j][k].intersection(elems), len(self.H[i][j][k])] ret[i][j][k] = val if ((float(len(val[0]))/(val[1])) * 100) >= 50 : #if len(ret[j][0]) >= (ret[j][1] / 2.0) : val.append(True) else: val.append(False) return ret def show(self) : for i in self.D : print i, ":" for j in self.D[i] : print "\t", j, len(self.D[i][j]) for k in self.D[i][j] : print "\t\t", k, len(self.D[i][j][k]) def save(self): fd = open(self.filename, "w") json.dump(self.D, fd) fd.close() def simhash(x) : import simhash return simhash.simhash(x)
Python
#!/usr/bin/env python # This file is part of Elsim. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import logging, re from similarity.similarity_db import * from androguard.core.analysis import analysis DEFAULT_SIGNATURE = analysis.SIGNATURE_SEQUENCE_BB def show_res(ret) : for i in ret : for j in ret[i] : for k in ret[i][j] : val = ret[i][j][k] if len(val[0]) == 1 and val[1] > 1: continue print "\t", i, j, k, len(val[0]), val[1] def eval_res_per_class(ret) : z = {} for i in ret : for j in ret[i] : for k in ret[i][j] : val = ret[i][j][k] # print val, k if len(val[0]) == 1 and val[1] > 1 : continue if len(val[0]) == 0: continue if j not in z : z[j] = {} val_percentage = (len(val[0]) / float(val[1]) ) * 100 if (val_percentage != 0) : z[j][k] = val_percentage return z def eval_res(ret) : sorted_elems = {} for i in ret : sorted_elems[i] = [] for j in ret[i] : final_value = 0 total_value = 0 elems = set() # print i, j, final_value for k in ret[i][j] : val = ret[i][j][k] total_value += 1 if len(val[0]) == 1 and val[1] > 1: continue ratio = (len(val[0]) / float(val[1])) #print "\t", k, len(val[0]), val[1], ratio if ratio > 0.2 : if len(val[0]) > 10 or ratio > 0.8 : final_value += ratio elems.add( (k, ratio, len(val[0])) ) if final_value != 0 : #print "---->", i, j, (final_value/total_value)*100#, elems sorted_elems[i].append( (j, (final_value/total_value)*100, elems) ) if len(sorted_elems[i]) == 0 : del sorted_elems[i] return sorted_elems def show_sorted_elems(sorted_elems): for i in sorted_elems : print i v = sorted(sorted_elems[i], key=lambda x: x[1]) v.reverse() for j in v : print "\t", j[0], j[1] ############################################################ class ElsimDB : def __init__(self, vm, vmx, database_path) : self.vm = vm self.vmx = vmx self.db = DBFormat( database_path ) def percentages_ad(self) : elems_hash = set() for _class in self.vm.get_classes() : for method in _class.get_methods() : code = method.get_code() if code == None : continue buff_list = self.vmx.get_method_signature( method, predef_sign = DEFAULT_SIGNATURE ).get_list() for i in buff_list : elem_hash = long(simhash( i )) elems_hash.add( elem_hash ) ret = self.db.elems_are_presents( elems_hash ) sorted_ret = eval_res(ret) info = [] for i in sorted_ret : v = sorted(sorted_ret[i], key=lambda x: x[1]) v.reverse() for j in v : info.append( [j[0], j[1]] ) return info def percentages_code(self, exclude_list) : libs = re.compile('|'.join( "(" + i + ")" for i in exclude_list)) classes_size = 0 classes_db_size = 0 classes_edb_size = 0 classes_udb_size = 0 for _class in self.vm.get_classes() : class_size = 0 elems_hash = set() for method in _class.get_methods() : code = method.get_code() if code == None : continue buff_list = self.vmx.get_method_signature( method, predef_sign = DEFAULT_SIGNATURE ).get_list() for i in buff_list : elem_hash = long(simhash( i )) elems_hash.add( elem_hash ) class_size += method.get_length() classes_size += class_size if class_size == 0 : continue ret = self.db.elems_are_presents( elems_hash ) sort_ret = eval_res_per_class( ret ) if sort_ret == {} : if libs.search(_class.get_name()) != None : classes_edb_size += class_size else : classes_udb_size += class_size else : classes_db_size += class_size return (classes_db_size/float(classes_size)) * 100, (classes_edb_size/float(classes_size)) * 100, (classes_udb_size/float(classes_size)) * 100 def percentages_to_graph(self) : info = { "info" : [], "nodes" : [], "links" : []} N = {} L = {} for _class in self.vm.get_classes() : elems_hash = set() # print _class.get_name() for method in _class.get_methods() : code = method.get_code() if code == None : continue buff_list = self.vmx.get_method_signature( method, predef_sign = DEFAULT_SIGNATURE ).get_list() for i in buff_list : elem_hash = long(simhash( i )) elems_hash.add( elem_hash ) ret = self.db.elems_are_presents( elems_hash ) sort_ret = eval_res_per_class( ret ) if sort_ret != {} : if _class.get_name() not in N : info["nodes"].append( { "name" : _class.get_name().split("/")[-1], "group" : 0 } ) N[_class.get_name()] = len(N) for j in sort_ret : if j not in N : N[j] = len(N) info["nodes"].append( { "name" : j, "group" : 1 } ) key = _class.get_name() + j if key not in L : L[ key ] = { "source" : N[_class.get_name()], "target" : N[j], "value" : 0 } info["links"].append( L[ key ] ) for k in sort_ret[j] : if sort_ret[j][k] > L[ key ]["value"] : L[ key ]["value"] = sort_ret[j][k] return info
Python
#!/usr/bin/env python import sys PATH_INSTALL = "./libelsign" sys.path.append(PATH_INSTALL) from libelsign import libelsign #from libelsign import libelsign2 as libelsign SIGNS = [ [ "Sign1", "a", [ [ 4.4915299415588379, 4.9674844741821289, 4.9468302726745605, 0.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ] ], [ "Sign2", "a && b", [ [ 2.0, 3.0, 4.0, 5.0 ], "OOOPS !!!!!!!!" ], [ [ 2.0, 3.0, 4.0, 8.0], "OOOOOOOOPPPPPS !!!" ] ], ] HSIGNS = {} ELEMS = [ # [ [ 4.4915299415588379, 4.9674844741821289, 4.9468302726745605, 0.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ], [ [ 4.4915299415588379, 4.9674844741821289, 4.9468302726745605, 1.0 ], "FALSE POSITIVE" ], [ [ 2.0, 3.0, 4.0, 5.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ], [ [ 2.0, 3.0, 4.0, 5.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ], [ [ 2.0, 3.0, 4.0, 5.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ], [ [ 2.0, 3.0, 4.0, 5.0 ], "HELLO WORLDDDDDDDDDDDDDDDDDDDDDDD" ], ] HELEMS = {} es = libelsign.Elsign() es.set_debug_log(1) es.set_distance( 'e' ) es.set_method( 'm' ) es.set_weight( [ 2.0, 1.2, 0.5, 0.1, 0.6 ] ) # NCD es.set_sim_method( 0 ) es.set_threshold_low( 0.3 ) es.set_threshold_high( 0.4 ) # SNAPPY es.set_ncd_compression_algorithm( 5 ) for i in range(0, len(SIGNS)) : id = es.add_signature( SIGNS[i][0], SIGNS[i][1], SIGNS[i][2:] ) print SIGNS[i], id HSIGNS[id] = i for i in range(0, len(ELEMS)) : id = es.add_element( ELEMS[i][1], ELEMS[i][0] ) print ELEMS[i], id HELEMS[id] = i print es.check() dt = es.get_debug() debug_nb_sign = dt[0] debug_nb_clusters = dt[1] debug_nb_cmp_clusters = dt[2] debug_nb_elements = dt[3] debug_nb_cmp_elements = dt[4] debug_nb_cmp_max = debug_nb_sign * debug_nb_elements print "[SIGN:%d CLUSTERS:%d CMP_CLUSTERS:%d ELEMENTS:%d CMP_ELEMENTS:%d" % (debug_nb_sign, debug_nb_clusters, debug_nb_cmp_clusters, debug_nb_elements, debug_nb_cmp_elements), print "-> %d %f%%]" % (debug_nb_cmp_max, ((debug_nb_cmp_elements/float(debug_nb_cmp_max)) * 100) )
Python
# This file is part of Elsim. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import sys import json, base64 from androguard.core.bytecodes import apk from androguard.core.bytecodes import dvm #from androguard.core.bytecodes.libdvm import dvmfull as dvm from androguard.core.analysis import analysis from androguard.core import androconf from libelsign.libelsign import Elsign, entropy METHSIM = 0 CLASSSIM = 1 DEFAULT_SIGNATURE = analysis.SIGNATURE_L0_4 def get_signature(vmx, m) : return vmx.get_method_signature(m, predef_sign = DEFAULT_SIGNATURE).get_string() def create_entropies(vmx, m) : default_signature = vmx.get_method_signature(m, predef_sign = DEFAULT_SIGNATURE).get_string() l = [ default_signature, entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Landroid"] } } ).get_string() ), entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Ljava"] } } ).get_string() ), entropy( vmx.get_method_signature(m, "hex" ).get_string() ), entropy( vmx.get_method_signature(m, "L2" ).get_string() ), ] return l def FIX_FORMULA(x, z) : if "0" in x : x = x.replace("and", "&&") x = x.replace("or", "||") for i in range(0, z) : t = "%c" % (ord('a') + i) x = x.replace("%d" % i, t) return x return x class ElfElsign : pass class DalvikElsign : def __init__(self) : self.debug = False self.meth_elsign = Elsign() self.class_elsign = Elsign() def raz(self) : self.meth_elsign.raz() self.class_elsign.raz() def load_config(self, buff) : ################ METHOD ################ methsim = buff["METHSIM"] self.meth_elsign.set_distance( str( methsim["DISTANCE"] ) ) self.meth_elsign.set_method( str( methsim["METHOD"] ) ) self.meth_elsign.set_weight( methsim["WEIGHTS"] )#[ 2.0, 1.2, 0.5, 0.1, 0.6 ] ) #self.meth_elsign.set_cut_element( 1 ) # NCD self.meth_elsign.set_sim_method( 0 ) self.meth_elsign.set_threshold_low( methsim["THRESHOLD_LOW" ] ) self.meth_elsign.set_threshold_high( methsim["THRESHOLD_HIGH"] ) # SNAPPY self.meth_elsign.set_ncd_compression_algorithm( 5 ) ################ CLASS ################ classsim = buff["METHSIM"] self.class_elsign.set_distance( str( classsim["DISTANCE"] ) ) self.class_elsign.set_method( str( classsim["METHOD"] ) ) self.class_elsign.set_weight( classsim["WEIGHTS"] )#[ 2.0, 1.2, 0.5, 0.1, 0.6 ] ) #self.class_elsign.set_cut_element( 1 ) # NCD self.class_elsign.set_sim_method( 0 ) self.class_elsign.set_threshold_low( classsim["THRESHOLD_LOW" ] ) self.class_elsign.set_threshold_high( classsim["THRESHOLD_HIGH"] ) # SNAPPY self.class_elsign.set_ncd_compression_algorithm( 5 ) def add_signature(self, type_signature, x, y, z) : ret = None #print type_signature, x, y, z # FIX ENTROPIES (old version) for j in z : if len(j[0]) == 5 : j[0].pop(0) # FIX FORMULA (old version) y = FIX_FORMULA(y, len(z)) if type_signature == METHSIM : ret = self.meth_elsign.add_signature(x, y, z) elif type_signature == CLASSSIM : ret = self.class_elsign.add_signature(x, y, z) return ret def set_debug(self, debug) : self.debug = debug x = { True : 1, False : 0 } self.meth_elsign.set_debug_log(x[debug]) def load_meths(self, vm, vmx) : if self.debug : print "LM", sys.stdout.flush() # Add methods for METHSIM for method in vm.get_methods() : #s1 = get_signature( vmx, method ) entropies = create_entropies(vmx, method) self.meth_elsign.add_element( entropies[0], entropies[1:] ) del entropies def load_classes(self, vm, vmx) : if self.debug : print "LC", sys.stdout.flush() # Add classes for CLASSSIM for c in vm.get_classes() : value = "" android_entropy = 0.0 java_entropy = 0.0 hex_entropy = 0.0 exception_entropy = 0.0 nb_methods = 0 class_data = c.get_class_data() if class_data == None : continue for m in c.get_methods() : z_tmp = create_entropies( vmx, m ) value += z_tmp[0] android_entropy += z_tmp[1] java_entropy += z_tmp[2] hex_entropy += z_tmp[3] exception_entropy += z_tmp[4] nb_methods += 1 if nb_methods != 0 : self.class_elsign.add_element( value, [ android_entropy/nb_methods, java_entropy/nb_methods, hex_entropy/nb_methods, exception_entropy/nb_methods ] ) del value, z_tmp def check(self, vm, vmx) : self.load_meths(vm, vmx) if self.debug : print "CM", sys.stdout.flush() ret = self.meth_elsign.check() if self.debug : dt = self.meth_elsign.get_debug() debug_nb_sign = dt[0] debug_nb_clusters = dt[1] debug_nb_cmp_clusters = dt[2] debug_nb_elements = dt[3] debug_nb_cmp_elements = dt[4] debug_nb_cmp_max = debug_nb_sign * debug_nb_elements print "[SIGN:%d CLUSTERS:%d CMP_CLUSTERS:%d ELEMENTS:%d CMP_ELEMENTS:%d" % (debug_nb_sign, debug_nb_clusters, debug_nb_cmp_clusters, debug_nb_elements, debug_nb_cmp_elements), try : percentage = debug_nb_cmp_elements/float(debug_nb_cmp_max) except : percentage = 0 finally : print "-> %d %f%%]" % (debug_nb_cmp_max, percentage * 100), print ret[1:], if ret[0] == None : self.load_classes(vm, vmx) if self.debug : print "CC", sys.stdout.flush() ret = self.class_elsign.check() if self.debug : dt = self.class_elsign.get_debug() debug_nb_sign = dt[0] debug_nb_clusters = dt[1] debug_nb_cmp_clusters = dt[2] debug_nb_elements = dt[3] debug_nb_cmp_elements = dt[4] debug_nb_cmp_max = debug_nb_sign * debug_nb_elements print "[SIGN:%d CLUSTERS:%d CMP_CLUSTERS:%d ELEMENTS:%d CMP_ELEMENTS:%d" % (debug_nb_sign, debug_nb_clusters, debug_nb_cmp_clusters, debug_nb_elements, debug_nb_cmp_elements), try : percentage = debug_nb_cmp_elements/float(debug_nb_cmp_max) except : percentage = 0 finally : print "-> %d %f%%]" % (debug_nb_cmp_max, percentage * 100), print ret[1:], return ret[0], ret[1:] class PublicSignature : def __init__(self, database, config, debug=False) : self.debug = debug self.DE = DalvikElsign() self.DE.set_debug( debug ) self.database = database self.config = config print self.database, self.config, debug self._load() def _load(self) : self.DE.load_config( json.loads( open(self.config, "rb").read() ) ) buff = json.loads( open(self.database, "rb").read() ) for i in buff : type_signature = None sub_signatures = [] for j in buff[i][0] : if j[0] == METHSIM : type_signature = METHSIM sub_signatures.append( [ j[2:], str(base64.b64decode( j[1] ) ) ] ) elif j[0] == CLASSSIM : type_signature = CLASSSIM sub_signatures.append( [ j[2:], str(base64.b64decode( j[1] ) ) ] ) if type_signature != None : self.DE.add_signature( type_signature, i, buff[i][1], sub_signatures ) else : print i, "ERROR" def check_apk(self, apk) : if self.debug : print "loading apk..", sys.stdout.flush() classes_dex = apk.get_dex() ret = self._check_dalvik( classes_dex ) return ret def check_dex(self, buff) : """ Check if a signature matches the dex application @param buff : a buffer which represents a dex file @rtype : None if no signatures match, otherwise the name of the signature """ return self._check_dalvik( buff ) def check_dex_direct(self, d, dx) : """ Check if a signature matches the dex application @param buff : a buffer which represents a dex file @rtype : None if no signatures match, otherwise the name of the signature """ return self._check_dalvik_direct( d, dx ) def _check_dalvik(self, buff) : if self.debug : print "loading dex..", sys.stdout.flush() vm = dvm.DalvikVMFormat( buff ) if self.debug : print "analysis..", sys.stdout.flush() vmx = analysis.VMAnalysis( vm ) return self._check_dalvik_direct( vm, vmx ) def _check_dalvik_direct(self, vm, vmx) : # check methods with similarity ret = self.DE.check(vm, vmx) self.DE.raz() del vmx, vm return ret class MSignature : def __init__(self, dbname, dbconfig, debug, ps=PublicSignature) : """ Check if signatures from a database is present in an android application (apk/dex) @param dbname : the filename of the database @param dbconfig : the filename of the configuration """ self.debug = debug self.p = ps( dbname, dbconfig, self.debug ) def load(self) : """ Load the database """ self.p.load() def set_debug(self) : """ Debug mode ! """ self.debug = True self.p.set_debug() def check_apk(self, apk) : """ Check if a signature matches the application @param apk : an L{APK} object @rtype : None if no signatures match, otherwise the name of the signature """ if self.debug : print "loading apk..", sys.stdout.flush() classes_dex = apk.get_dex() ret, l = self.p._check_dalvik( classes_dex ) if ret == None : #ret, l1 = self.p._check_bin( apk ) l1 = [] l.extend( l1 ) return ret, l def check_dex(self, buff) : """ Check if a signature matches the dex application @param buff : a buffer which represents a dex file @rtype : None if no signatures match, otherwise the name of the signature """ return self.p._check_dalvik( buff ) def check_dex_direct(self, d, dx) : """ Check if a signature matches the dex application @param buff : a buffer which represents a dex file @rtype : None if no signatures match, otherwise the name of the signature """ return self.p._check_dalvik_direct( d, dx ) class PublicCSignature : def add_file(self, srules) : l = [] rules = json.loads( srules ) ret_type = androconf.is_android( rules[0]["SAMPLE"] ) if ret_type == "APK" : a = apk.APK( rules[0]["SAMPLE"] ) classes_dex = a.get_dex() elif ret_type == "DEX" : classes_dex = open( rules[0]["SAMPLE"], "rb" ).read() elif ret_type == "ELF" : elf_file = open( rules[0]["SAMPLE"], "rb" ).read() else : return None if ret_type == "APK" or ret_type == "DEX" : vm = dvm.DalvikVMFormat( classes_dex ) vmx = analysis.VMAnalysis( vm ) for i in rules[1:] : x = { i["NAME"] : [] } sign = [] for j in i["SIGNATURE"] : z = [] if j["TYPE"] == "METHSIM" : z.append( METHSIM ) m = vm.get_method_descriptor( j["CN"], j["MN"], j["D"] ) if m == None : print "impossible to find", j["CN"], j["MN"], j["D"] raise("ooo") #print m.get_length() z_tmp = create_entropies( vmx, m ) print z_tmp[0] z_tmp[0] = base64.b64encode( z_tmp[0] ) z.extend( z_tmp ) elif j["TYPE"] == "CLASSSIM" : for c in vm.get_classes() : if j["CN"] == c.get_name() : z.append( CLASSSIM ) value = "" android_entropy = 0.0 java_entropy = 0.0 hex_entropy = 0.0 exception_entropy = 0.0 nb_methods = 0 for m in c.get_methods() : z_tmp = create_entropies( vmx, m ) value += z_tmp[0] android_entropy += z_tmp[1] java_entropy += z_tmp[2] hex_entropy += z_tmp[3] exception_entropy += z_tmp[4] nb_methods += 1 z.extend( [ base64.b64encode(value), android_entropy/nb_methods, java_entropy/nb_methods, hex_entropy/nb_methods, exception_entropy/nb_methods ] ) else : return None sign.append( z ) x[ i["NAME"] ].append( sign ) x[ i["NAME"] ].append( FIX_FORMULA(i["BF"], len(sign)) ) l.append( x ) print l return l def get_info(self, srules) : rules = json.loads( srules ) ret_type = androconf.is_android( rules[0]["SAMPLE"] ) if ret_type == "APK" : a = apk.APK( rules[0]["SAMPLE"] ) classes_dex = a.get_dex() elif ret_type == "DEX" : classes_dex = open( rules[0]["SAMPLE"], "rb" ).read() #elif ret_type == "ELF" : #elf_file = open( rules[0]["SAMPLE"], "rb" ).read() else : return None if ret_type == "APK" or ret_type == "DEX" : vm = dvm.DalvikVMFormat( classes_dex ) vmx = analysis.VMAnalysis( vm ) res = [] for i in rules[1:] : for j in i["SIGNATURE"] : if j["TYPE"] == "METHSIM" : m = vm.get_method_descriptor( j["CN"], j["MN"], j["D"] ) if m == None : print "impossible to find", j["CN"], j["MN"], j["D"] else : res.append( m ) elif j["TYPE"] == "CLASSSIM" : for c in vm.get_classes() : if j["CN"] == c.get_name() : res.append( c ) return vm, vmx, res class CSignature : def __init__(self, pcs=PublicCSignature) : self.pcs = pcs() def add_file(self, srules) : return self.pcs.add_file(srules) def get_info(self, srules) : return self.pcs.get_info(srules) def list_indb(self, output) : from elsim.similarity import similarity s = similarity.SIMILARITY( "./elsim/elsim/similarity/libsimilarity/libsimilarity.so" ) s.set_compress_type( similarity.ZLIB_COMPRESS ) fd = open(output, "r") buff = json.loads( fd.read() ) fd.close() for i in buff : print i for j in buff[i][0] : sign = base64.b64decode(j[1]) print "\t", j[0], "ENTROPIES:", j[2:], "L:%d" % len(sign), "K:%d" % s.kolmogorov(sign)[0] print "\tFORMULA:", buff[i][-1] def check_db(self, output) : ids = {} meth_sim = [] class_sim = [] fd = open(output, "r") buff = json.loads( fd.read() ) fd.close() for i in buff : nb = 0 for ssign in buff[i][0] : if ssign[0] == METHSIM : value = base64.b64decode( ssign[1] ) if value in ids : print "IDENTICAL", ids[ value ], i, nb else : ids[ value ] = (i, nb) meth_sim.append( value ) elif ssign[0] == CLASSSIM : ids[ base64.b64decode( ssign[1] ) ] = (i, nb) class_sim.append( base64.b64decode( ssign[1] ) ) nb += 1 from elsim.similarity import similarity s = similarity.SIMILARITY( "./elsim/elsim/similarity/libsimilarity/libsimilarity.so" ) s.set_compress_type( similarity.SNAPPY_COMPRESS ) self.__check_db( s, ids, meth_sim ) self.__check_db( s, ids, class_sim ) def __check_db(self, s, ids, elem_sim) : from elsim.similarity import similarity problems = {} for i in elem_sim : for j in elem_sim : if i != j : ret = s.ncd( i, j )[0] if ret < 0.3 : ids_cmp = ids[ i ] + ids[ j ] if ids_cmp not in problems : s.set_compress_type( similarity.BZ2_COMPRESS ) ret = s.ncd( i, j )[0] s.set_compress_type( similarity.SNAPPY_COMPRESS ) print "[-] ", ids[ i ], ids[ j ], ret problems[ ids_cmp ] = 0 problems[ ids[ j ] + ids[ i ] ] = 0 def remove_indb(self, signature, output) : fd = open(output, "r") buff = json.loads( fd.read() ) fd.close() del buff[signature] fd = open(output, "w") fd.write( json.dumps( buff ) ) fd.close() def add_indb(self, signatures, output) : if signatures == None : return fd = open(output, "a+") buff = fd.read() if buff == "" : buff = {} else : buff = json.loads( buff ) fd.close() for i in signatures : buff.update( i ) fd = open(output, "w") fd.write( json.dumps( buff ) ) fd.close()
Python
#!/usr/bin/env python # This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import hashlib from elsim import error, warning, debug, set_debug, get_debug import elsim def filter_sim_value_meth( v ) : if v >= 0.2 : return 1.0 return v class CheckSumFunc : def __init__(self, f, sim) : self.f = f self.sim = sim self.buff = "" self.entropy = 0.0 self.signature = None for i in self.f.get_instructions() : self.buff += i.get_mnemonic() self.entropy, _ = sim.entropy( self.buff ) def get_signature(self) : if self.signature == None : self.signature = self.buff self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature def get_signature_entropy(self) : if self.signature == None : self.signature = self.buff self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature_entropy def get_entropy(self) : return self.entropy def get_buff(self) : return self.buff def filter_checksum_meth_basic( f, sim ) : return CheckSumFunc( f, sim ) def filter_sim_meth_basic( sim, m1, m2 ) : #ncd1, _ = sim.ncd( m1.checksum.get_signature(), m2.checksum.get_signature() ) ncd2, _ = sim.ncd( m1.checksum.get_buff(), m2.checksum.get_buff() ) #return (ncd1 + ncd2) / 2.0 return ncd2 def filter_sort_meth_basic( j, x, value ) : z = sorted(x.iteritems(), key=lambda (k,v): (v,k)) if get_debug() : for i in z : debug("\t %s %f" %(i[0].get_info(), i[1])) if z[:1][0][1] > value : return [] return z[:1] class Instruction : def __init__(self, i) : self.mnemonic = i[1] def get_mnemonic(self) : return self.mnemonic class Function : def __init__(self, e, el) : self.function = el def get_instructions(self) : for i in self.function.get_instructions() : yield Instruction(i) def get_nb_instructions(self) : return len(self.function.get_instructions()) def get_info(self) : return "%s" % (self.function.name) def set_checksum(self, fm) : self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() self.checksum = fm def getsha256(self) : return self.sha256 def filter_element_meth_basic(el, e) : return Function( e, el ) class FilterNone : def skip(self, e) : #if e.get_nb_instructions() < 2 : # return True return False FILTERS_X86 = { elsim.FILTER_ELEMENT_METH : filter_element_meth_basic, elsim.FILTER_CHECKSUM_METH : filter_checksum_meth_basic, elsim.FILTER_SIM_METH : filter_sim_meth_basic, elsim.FILTER_SORT_METH : filter_sort_meth_basic, elsim.FILTER_SORT_VALUE : 0.6, elsim.FILTER_SKIPPED_METH : FilterNone(), elsim.FILTER_SIM_VALUE_METH : filter_sim_value_meth, } class ProxyX86IDA : def __init__(self, ipipe) : self.functions = ipipe.get_quick_functions() def get_elements(self) : for i in self.functions : yield self.functions[ i ]
Python
#!/usr/bin/env python # This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import hashlib from elsim import error, warning, debug, set_debug, get_debug import elsim def filter_sim_value_meth( v ) : if v >= 0.2 : return 1.0 return v class CheckSumText : def __init__(self, s1, sim) : self.s1 = s1 self.sim = sim self.buff = s1.string self.entropy = 0.0 self.signature = None def get_signature(self) : if self.signature == None : raise("ooo") self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature def get_signature_entropy(self) : if self.signature == None : raise("ooo") self.signature_entropy, _ = self.sim.entropy( self.signature ) return self.signature_entropy def get_entropy(self) : return self.entropy def get_buff(self) : return self.buff def filter_checksum_meth_basic( m1, sim ) : return CheckSumText( m1, sim ) def filter_sim_meth_basic( sim, m1, m2 ) : from similarity.similarity import XZ_COMPRESS sim.set_compress_type( XZ_COMPRESS ) ncd1, _ = sim.ncd( m1.checksum.get_buff(), m2.checksum.get_buff() ) return ncd1 #ncd1, _ = sim.ncd( m1.checksum.get_signature(), m2.checksum.get_signature() ) #ncd2, _ = sim.ncd( m1.checksum.get_buff(), m2.checksum.get_buff() ) #return (ncd1 + ncd2) / 2.0 def filter_sort_meth_basic( j, x, value ) : z = sorted(x.iteritems(), key=lambda (k,v): (v,k)) if get_debug() : for i in z : debug("\t %s %f" %(i[0].get_info(), i[1])) if z[:1][0][1] > value : return [] return z[:1] class Text : def __init__(self, e, el) : self.string = el nb = 0 for i in range(0, len(self.string)) : if self.string[i] == " " : nb += 1 else : break self.string = self.string[nb:] self.sha256 = None def get_info(self) : return "%d %s" % (len(self.string), repr(self.string)) #return "%d %s" % (len(self.string), "") def set_checksum(self, fm) : self.sha256 = hashlib.sha256( fm.get_buff() ).hexdigest() self.checksum = fm def getsha256(self) : return self.sha256 def filter_element_meth_basic(el, e) : return Text( e, el ) class FilterNone : def skip(self, e): # remove whitespace elements if e.string.isspace() == True : return True if len(e.string) == 0 : return True return False FILTERS_TEXT = { elsim.FILTER_ELEMENT_METH : filter_element_meth_basic, elsim.FILTER_CHECKSUM_METH : filter_checksum_meth_basic, elsim.FILTER_SIM_METH : filter_sim_meth_basic, elsim.FILTER_SORT_METH : filter_sort_meth_basic, elsim.FILTER_SORT_VALUE : 0.6, elsim.FILTER_SKIPPED_METH : FilterNone(), elsim.FILTER_SIM_VALUE_METH : filter_sim_value_meth, } class ProxyText : def __init__(self, buff) : self.buff = buff def get_elements(self) : buff = self.buff.replace("\n"," ") # multi split elements: ".", ",", ":" import re for i in re.split('; |, |-|\.|\?|:', buff) : yield i
Python
# This file is part of Elsim # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. import logging ELSIM_VERSION = 0.2 log_elsim = logging.getLogger("elsim") console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) log_elsim.addHandler(console_handler) log_runtime = logging.getLogger("elsim.runtime") # logs at runtime log_interactive = logging.getLogger("elsim.interactive") # logs in interactive functions log_loading = logging.getLogger("elsim.loading") # logs when loading def set_debug() : log_elsim.setLevel( logging.DEBUG ) def get_debug() : return log_elsim.getEffectiveLevel() == logging.DEBUG def warning(x): log_runtime.warning(x) def error(x) : log_runtime.error(x) raise() def debug(x) : log_runtime.debug(x) from similarity.similarity import * FILTER_ELEMENT_METH = "FILTER_ELEMENT_METH" FILTER_CHECKSUM_METH = "FILTER_CHECKSUM_METH" # function to checksum an element FILTER_SIM_METH = "FILTER_SIM_METH" # function to calculate the similarity between two elements FILTER_SORT_METH = "FILTER_SORT_METH" # function to sort all similar elements FILTER_SORT_VALUE = "FILTER_SORT_VALUE" # value which used in the sort method to eliminate not interesting comparisons FILTER_SKIPPED_METH = "FILTER_SKIPPED_METH" # object to skip elements FILTER_SIM_VALUE_METH = "FILTER_SIM_VALUE_METH" # function to modify values of the similarity BASE = "base" ELEMENTS = "elements" HASHSUM = "hashsum" SIMILAR_ELEMENTS = "similar_elements" HASHSUM_SIMILAR_ELEMENTS = "hash_similar_elements" NEW_ELEMENTS = "newelements" HASHSUM_NEW_ELEMENTS = "hash_new_elements" DELETED_ELEMENTS = "deletedelements" IDENTICAL_ELEMENTS = "identicalelements" INTERNAL_IDENTICAL_ELEMENTS = "internal identical elements" SKIPPED_ELEMENTS = "skippedelements" SIMILARITY_ELEMENTS = "similarity_elements" SIMILARITY_SORT_ELEMENTS = "similarity_sort_elements" class ElsimNeighbors : def __init__(self, x, ys) : import numpy as np from sklearn.neighbors import NearestNeighbors #print x, ys CI = np.array( [x.checksum.get_signature_entropy(), x.checksum.get_entropy()] ) #print CI, x.get_info() #print for i in ys : CI = np.vstack( (CI, [i.checksum.get_signature_entropy(), i.checksum.get_entropy()]) ) #idx = 0 #for i in np.array(CI)[1:] : # print idx+1, i, ys[idx].get_info() # idx += 1 self.neigh = NearestNeighbors(2, 0.4) self.neigh.fit(np.array(CI)) #print self.neigh.kneighbors( CI[0], len(CI) ) self.CI = CI self.ys = ys def cmp_elements(self) : z = self.neigh.kneighbors( self.CI[0], 5 ) l = [] cmp_values = z[0][0] cmp_elements = z[1][0] idx = 1 for i in cmp_elements[1:] : #if cmp_values[idx] > 1.0 : # break #print i, cmp_values[idx], self.ys[ i - 1 ].get_info() l.append( self.ys[ i - 1 ] ) idx += 1 return l def split_elements(el, els) : e1 = {} for i in els : e1[ i ] = el.get_associated_element( i ) return e1 #### # elements : entropy raw, hash, signature # # set elements : hash # hash table elements : hash --> element class Elsim : def __init__(self, e1, e2, F, T=None, C=None, libnative=True, libpath="elsim/elsim/similarity/libsimilarity/libsimilarity.so") : self.e1 = e1 self.e2 = e2 self.F = F self.compressor = SNAPPY_COMPRESS set_debug() if T != None : self.F[ FILTER_SORT_VALUE ] = T if isinstance(libnative, str) : libpath = libnative libnative = True self.sim = SIMILARITY( libpath, libnative ) if C != None : if C in H_COMPRESSOR : self.compressor = H_COMPRESSOR[ C ] self.sim.set_compress_type( self.compressor ) else : self.sim.set_compress_type( self.compressor ) self.filters = {} self._init_filters() self._init_index_elements() self._init_similarity() self._init_sort_elements() self._init_new_elements() def _init_filters(self) : self.filters = {} self.filters[ BASE ] = {} self.filters[ BASE ].update( self.F ) self.filters[ ELEMENTS ] = {} self.filters[ HASHSUM ] = {} self.filters[ IDENTICAL_ELEMENTS ] = set() self.filters[ SIMILAR_ELEMENTS ] = [] self.filters[ HASHSUM_SIMILAR_ELEMENTS ] = [] self.filters[ NEW_ELEMENTS ] = set() self.filters[ HASHSUM_NEW_ELEMENTS ] = [] self.filters[ DELETED_ELEMENTS ] = [] self.filters[ SKIPPED_ELEMENTS ] = [] self.filters[ ELEMENTS ][ self.e1 ] = [] self.filters[ HASHSUM ][ self.e1 ] = [] self.filters[ ELEMENTS ][ self.e2 ] = [] self.filters[ HASHSUM ][ self.e2 ] = [] self.filters[ SIMILARITY_ELEMENTS ] = {} self.filters[ SIMILARITY_SORT_ELEMENTS ] = {} self.set_els = {} self.ref_set_els = {} def _init_index_elements(self) : self.__init_index_elements( self.e1, 1 ) self.__init_index_elements( self.e2 ) def __init_index_elements(self, ce, init=0) : self.set_els[ ce ] = set() self.ref_set_els[ ce ] = {} for ae in ce.get_elements() : e = self.filters[BASE][FILTER_ELEMENT_METH]( ae, ce ) if self.filters[BASE][FILTER_SKIPPED_METH].skip( e ) : self.filters[ SKIPPED_ELEMENTS ].append( e ) continue self.filters[ ELEMENTS ][ ce ].append( e ) fm = self.filters[ BASE ][ FILTER_CHECKSUM_METH ]( e, self.sim ) e.set_checksum( fm ) sha256 = e.getsha256() self.filters[ HASHSUM ][ ce ].append( sha256 ) if sha256 not in self.set_els[ ce ] : self.set_els[ ce ].add( sha256 ) self.ref_set_els[ ce ][ sha256 ] = e def _init_similarity(self) : intersection_elements = self.set_els[ self.e2 ].intersection( self.set_els[ self.e1 ] ) difference_elements = self.set_els[ self.e2 ].difference( intersection_elements ) self.filters[IDENTICAL_ELEMENTS].update([ self.ref_set_els[ self.e1 ][ i ] for i in intersection_elements ]) available_e2_elements = [ self.ref_set_els[ self.e2 ][ i ] for i in difference_elements ] # Check if some elements in the first file has been modified for j in self.filters[ELEMENTS][self.e1] : self.filters[ SIMILARITY_ELEMENTS ][ j ] = {} #debug("SIM FOR %s" % (j.get_info())) if j.getsha256() not in self.filters[HASHSUM][self.e2] : #eln = ElsimNeighbors( j, available_e2_elements ) #for k in eln.cmp_elements() : for k in available_e2_elements : #debug("%s" % k.get_info()) self.filters[SIMILARITY_ELEMENTS][ j ][ k ] = self.filters[BASE][FILTER_SIM_METH]( self.sim, j, k ) if j.getsha256() not in self.filters[HASHSUM_SIMILAR_ELEMENTS] : self.filters[SIMILAR_ELEMENTS].append(j) self.filters[HASHSUM_SIMILAR_ELEMENTS].append( j.getsha256() ) def _init_sort_elements(self) : deleted_elements = [] for j in self.filters[SIMILAR_ELEMENTS] : #debug("SORT FOR %s" % (j.get_info())) sort_h = self.filters[BASE][FILTER_SORT_METH]( j, self.filters[SIMILARITY_ELEMENTS][ j ], self.filters[BASE][FILTER_SORT_VALUE] ) self.filters[SIMILARITY_SORT_ELEMENTS][ j ] = set( i[0] for i in sort_h ) ret = True if sort_h == [] : ret = False if ret == False : deleted_elements.append( j ) for j in deleted_elements : self.filters[ DELETED_ELEMENTS ].append( j ) self.filters[ SIMILAR_ELEMENTS ].remove( j ) def __checksort(self, x, y) : return y in self.filters[SIMILARITY_SORT_ELEMENTS][ x ] def _init_new_elements(self) : # Check if some elements in the second file are totally new ! for j in self.filters[ELEMENTS][self.e2] : # new elements can't be in similar elements if j not in self.filters[SIMILAR_ELEMENTS] : # new elements hashes can't be in first file if j.getsha256() not in self.filters[HASHSUM][self.e1] : ok = True # new elements can't be compared to another one for diff_element in self.filters[SIMILAR_ELEMENTS] : if self.__checksort( diff_element, j ) : ok = False break if ok : if j.getsha256() not in self.filters[HASHSUM_NEW_ELEMENTS] : self.filters[NEW_ELEMENTS].add( j ) self.filters[HASHSUM_NEW_ELEMENTS].append( j.getsha256() ) def get_similar_elements(self) : """ Return the similar elements @rtype : a list of elements """ return self.get_elem( SIMILAR_ELEMENTS ) def get_new_elements(self) : """ Return the new elements @rtype : a list of elements """ return self.get_elem( NEW_ELEMENTS ) def get_deleted_elements(self) : """ Return the deleted elements @rtype : a list of elements """ return self.get_elem( DELETED_ELEMENTS ) def get_internal_identical_elements(self, ce) : """ Return the internal identical elements @rtype : a list of elements """ return self.get_elem( INTERNAL_IDENTICAL_ELEMENTS ) def get_identical_elements(self) : """ Return the identical elements @rtype : a list of elements """ return self.get_elem( IDENTICAL_ELEMENTS ) def get_skipped_elements(self) : return self.get_elem( SKIPPED_ELEMENTS ) def get_elem(self, attr) : return [ x for x in self.filters[attr] ] def show_element(self, i, details=True) : print "\t", i.get_info() if details : if i.getsha256() == None : pass elif i.getsha256() in self.ref_set_els[self.e2] : print "\t\t-->", self.ref_set_els[self.e2][ i.getsha256() ].get_info() else : for j in self.filters[ SIMILARITY_SORT_ELEMENTS ][ i ] : print "\t\t-->", j.get_info(), self.filters[ SIMILARITY_ELEMENTS ][ i ][ j ] def get_element_info(self, i) : l = [] if i.getsha256() == None : pass elif i.getsha256() in self.ref_set_els[self.e2] : l.append( [ i, self.ref_set_els[self.e2][ i.getsha256() ] ] ) else : for j in self.filters[ SIMILARITY_SORT_ELEMENTS ][ i ] : l.append( [i, j, self.filters[ SIMILARITY_ELEMENTS ][ i ][ j ] ] ) return l def get_associated_element(self, i) : return list(self.filters[ SIMILARITY_SORT_ELEMENTS ][ i ])[0] def get_similarity_value(self, new=True) : values = [] self.sim.set_compress_type( BZ2_COMPRESS ) for j in self.filters[SIMILAR_ELEMENTS] : k = self.get_associated_element( j ) value = self.filters[BASE][FILTER_SIM_METH]( self.sim, j, k ) # filter value value = self.filters[BASE][FILTER_SIM_VALUE_METH]( value ) values.append( value ) values.extend( [ self.filters[BASE][FILTER_SIM_VALUE_METH]( 0.0 ) for i in self.filters[IDENTICAL_ELEMENTS] ] ) if new == True : values.extend( [ self.filters[BASE][FILTER_SIM_VALUE_METH]( 1.0 ) for i in self.filters[NEW_ELEMENTS] ] ) else : values.extend( [ self.filters[BASE][FILTER_SIM_VALUE_METH]( 1.0 ) for i in self.filters[DELETED_ELEMENTS] ] ) self.sim.set_compress_type( self.compressor ) similarity_value = 0.0 for i in values : similarity_value += (1.0 - i) if len(values) == 0 : return 0.0 return (similarity_value/len(values)) * 100 def show(self): print "Elements:" print "\t IDENTICAL:\t", len(self.get_identical_elements()) print "\t SIMILAR: \t", len(self.get_similar_elements()) print "\t NEW:\t\t", len(self.get_new_elements()) print "\t DELETED:\t", len(self.get_deleted_elements()) print "\t SKIPPED:\t", len(self.get_skipped_elements()) #self.sim.show() ADDED_ELEMENTS = "added elements" DELETED_ELEMENTS = "deleted elements" LINK_ELEMENTS = "link elements" DIFF = "diff" class Eldiff : def __init__(self, elsim, F) : self.elsim = elsim self.F = F self._init_filters() self._init_diff() def _init_filters(self) : self.filters = {} self.filters[ BASE ] = {} self.filters[ BASE ].update( self.F ) self.filters[ ELEMENTS ] = {} self.filters[ ADDED_ELEMENTS ] = {} self.filters[ DELETED_ELEMENTS ] = {} self.filters[ LINK_ELEMENTS ] = {} def _init_diff(self) : for i, j in self.elsim.get_elements() : self.filters[ ADDED_ELEMENTS ][ j ] = [] self.filters[ DELETED_ELEMENTS ][ i ] = [] x = self.filters[ BASE ][ DIFF ]( i, j ) self.filters[ ADDED_ELEMENTS ][ j ].extend( x.get_added_elements() ) self.filters[ DELETED_ELEMENTS ][ i ].extend( x.get_deleted_elements() ) self.filters[ LINK_ELEMENTS ][ j ] = i #self.filters[ LINK_ELEMENTS ][ i ] = j def show(self) : for bb in self.filters[ LINK_ELEMENTS ] : #print "la" print bb.get_info(), self.filters[ LINK_ELEMENTS ][ bb ].get_info() print "Added Elements(%d)" % (len(self.filters[ ADDED_ELEMENTS ][ bb ])) for i in self.filters[ ADDED_ELEMENTS ][ bb ] : print "\t", i.show() print "Deleted Elements(%d)" % (len(self.filters[ DELETED_ELEMENTS ][ self.filters[ LINK_ELEMENTS ][ bb ] ])) for i in self.filters[ DELETED_ELEMENTS ][ self.filters[ LINK_ELEMENTS ][ bb ] ] : print "\t", i.show() print def get_added_elements(self) : return self.filters[ ADDED_ELEMENTS ] def get_deleted_elements(self) : return self.filters[ DELETED_ELEMENTS ]
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys sys.path.append("./") PATH_INSTALL = "../androguard" sys.path.append(PATH_INSTALL) from optparse import OptionParser from elsim.similarity.similarity import * from androguard.core import androconf from androguard.core.bytecodes import apk, dvm from androguard.core.analysis import analysis DEFAULT_SIGNATURE = analysis.SIGNATURE_SEQUENCE_BB option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 1 } option_1 = { 'name' : ('-o', '--output'), 'help' : 'file : use these filenames', 'nargs' : 1 } option_2 = { 'name' : ('-n', '--name'), 'help' : 'file : use these filenames', 'nargs' : 1 } option_3 = { 'name' : ('-s', '--subname'), 'help' : 'file : use these filenames', 'nargs' : 1 } option_4 = { 'name' : ('-d', '--display'), 'help' : 'display the file in human readable format', 'action' : 'count' } option_5 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } options = [option_0, option_1, option_2, option_3, option_4] ############################################################ def main(options, arguments) : if options.input != None and options.output != None and options.name != None and options.subname != None : ret_type = androconf.is_android( options.input ) if ret_type == "APK" : a = apk.APK( options.input ) d1 = dvm.DalvikVMFormat( a.get_dex() ) elif ret_type == "DEX" : d1 = dvm.DalvikVMFormat( open(options.input, "rb").read() ) dx1 = analysis.VMAnalysis( d1 ) n = SIMILARITY( "elsim/similarity/libsimilarity/libsimilarity.so" ) n.set_compress_type( ZLIB_COMPRESS ) db = DBFormat( options.output ) for _class in d1.get_classes() : for method in _class.get_methods() : code = method.get_code() if code == None : continue if method.get_length() < 50 or method.get_name() == "<clinit>" : continue buff_list = dx1.get_method_signature( method, predef_sign = DEFAULT_SIGNATURE ).get_list() if len(set(buff_list)) == 1 : continue print method.get_class_name(), method.get_name(), method.get_descriptor(), method.get_length(), len(buff_list) for i in buff_list : db.add_element( options.name, options.subname, _class.get_name(), long(n.simhash(i)) ) db.save() elif options.version != None : print "Androapptodb version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Elsim. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Elsim is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Elsim is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Elsim. If not, see <http://www.gnu.org/licenses/>. from optparse import OptionParser import sys sys.path.append("./") from elsim.elsim import Elsim, ELSIM_VERSION from elsim.elsim_text import ProxyText, FILTERS_TEXT option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 2 } option_1 = { 'name' : ('-d', '--display'), 'help' : 'display the file in human readable format', 'action' : 'count' } option_2 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } options = [option_0, option_1, option_2] ############################################################ def main(options, arguments) : if options.input != None : el = Elsim( ProxyText( open(options.input[0], "rb").read() ), ProxyText( open(options.input[1], "rb").read() ), FILTERS_TEXT, libpath="elsim/similarity/libsimilarity/libsimilarity.so") el.show() print "\t--> sentences: %f%% of similarities" % el.get_similarity_value() if options.display : print "SIMILAR sentences:" diff_methods = el.get_similar_elements() for i in diff_methods : el.show_element( i ) print "IDENTICAL sentences:" new_methods = el.get_identical_elements() for i in new_methods : el.show_element( i ) print "NEW sentences:" new_methods = el.get_new_elements() for i in new_methods : el.show_element( i, False ) print "DELETED sentences:" del_methods = el.get_deleted_elements() for i in del_methods : el.show_element( i ) print "SKIPPED sentences:" skip_methods = el.get_skipped_elements() for i in skip_methods : el.show_element( i ) elif options.version != None : print "example text sim %s" % ELSIM_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Elsim. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os sys.path.append("./") PATH_INSTALL = "../androguard" sys.path.append(PATH_INSTALL) from optparse import OptionParser from elsim.elsim_db import * from elsim.elsim_dalvik import LIST_EXTERNAL_LIBS from elsim.similarity.similarity_db import * from androguard.core import androconf from androguard.core.bytecodes import apk, dvm from androguard.core.analysis import analysis DEFAULT_SIGNATURE = analysis.SIGNATURE_SEQUENCE_BB option_0 = { 'name' : ('-i', '--input'), 'help' : 'use this filename', 'nargs' : 1 } option_1 = { 'name' : ('-b', '--database'), 'help' : 'path of the database', 'nargs' : 1 } option_2 = { 'name' : ('-l', '--listdatabase'), 'help' : 'display information in the database', 'action' : 'count' } option_3 = { 'name' : ('-d', '--directory'), 'help' : 'use this directory', 'nargs' : 1 } option_4 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } options = [option_0, option_1, option_2, option_3, option_4] def check_one_file(d1, dx1) : print "Similarities ...." e = ElsimDB( d1, dx1, options.database ) print e.percentages_ad() print e.percentages_code(LIST_EXTERNAL_LIBS) def check_one_directory(directory) : for root, dirs, files in os.walk( directory, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f print "filename: %s ..." % real_filename ret_type = androconf.is_android( real_filename ) if ret_type == "APK" : a = apk.APK( real_filename ) d1 = dvm.DalvikVMFormat( a.get_dex() ) elif ret_type == "DEX" : d1 = dvm.DalvikVMFormat( open(real_filename, "rb").read() ) dx1 = analysis.VMAnalysis( d1 ) check_one_file( d1, dx1 ) def main(options, arguments) : if options.input != None and options.database != None : ret_type = androconf.is_android( options.input ) if ret_type == "APK" : a = apk.APK( options.input ) d1 = dvm.DalvikVMFormat( a.get_dex() ) elif ret_type == "DEX" : d1 = dvm.DalvikVMFormat( open(options.input, "rb").read() ) dx1 = analysis.VMAnalysis( d1 ) check_one_file(d1, dx1) elif options.directory != None and options.database != None : check_one_directory( options.directory ) elif options.database != None and options.listdatabase != None : db = DBFormat( options.database ) db.show() elif options.version != None : print "Androappindb version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. TYPE_DESCRIPTOR = { 'V': 'void', 'Z': 'boolean', 'B': 'byte', 'S': 'short', 'C': 'char', 'I': 'int', 'J': 'long', 'F': 'float', 'D': 'double', 'STR': 'String', 'StringBuilder': 'String' } ACCESS_FLAGS_CLASSES = { 0x1 : 'public', 0x2 : 'private', 0x4 : 'protected', 0x8 : 'static', 0x10 : 'final', 0x200 : 'interface', 0x400 : 'abstract', 0x1000: 'synthetic', 0x2000: 'annotation', 0x4000: 'enum' } ACCESS_FLAGS_FIELDS = { 0x1 : 'public', 0x2 : 'private', 0x4 : 'protected', 0x8 : 'static', 0x10 : 'final', 0x40 : 'volatile', 0x80 : 'transient', 0x1000: 'synthetic', 0x4000: 'enum' } ACCESS_FLAGS_METHODS = { 0x1 : 'public', 0x2 : 'private', 0x4 : 'protected', 0x8 : 'static', 0x10 : 'final', 0x20 : 'synchronized', 0x40 : 'bridge', 0x80 : 'varargs', 0x100 : 'native', 0x400 : 'abstract', 0x800 : 'strict', 0x1000 : 'synthetic', 0x10000: '', # ACC_CONSTRUCTOR 0x20000: 'synchronized' } TYPE_LEN = { 'J': 2, 'D': 2 } DEBUG_MODES = { 'off': -1, 'error': 0, 'log': 1, 'debug': 2 } DEBUG_LEVEL = 'log' class wrap_stream(object): def __init__(self): self.val = [] def write(self, s): self.val.append(s) def clean(self): self.val = [] def __str__(self): return ''.join(self.val) 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 = clsdict.keys() for classname in classlist: parts_name = classname.split('$') if len(parts_name) > 2: parts_name = ['$'.join(parts_name[:-1]), parts_name[-1]] if len(parts_name) > 1: mainclass, innerclass = parts_name innerclass = innerclass[:-1] # remove ';' of the name mainclass += ';' if mainclass in clsdict: clsdict[mainclass].add_subclass(innerclass, clsdict[classname]) clsdict[classname].name = innerclass done[classname] = clsdict[classname] del clsdict[classname] samelist = False elif mainclass in done: cls = done[mainclass] cls.add_subclass(innerclass, clsdict[classname]) clsdict[classname].name = innerclass done[classname] = done[mainclass] del clsdict[classname] samelist = False def get_type_size(param): ''' Return the number of register needed by the type @param ''' return TYPE_LEN.get(param, 1) def get_type(atype, size=None): ''' Retrieve the type of a descriptor (e.g : I) ''' if atype.startswith('java.lang'): atype = atype.replace('java.lang.', '') res = TYPE_DESCRIPTOR.get(atype.lstrip('java.lang')) if res is None: if atype[0] == 'L': res = atype[1:-1].replace('/', '.') elif atype[0] == '[': if size is None: res = '%s[]' % get_type(atype[1:]) else: res = '%s[%s]' % (get_type(atype[1:]), size) else: res = atype log('Unknown descriptor: "%s".' % atype, 'debug') return res 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 [] def log(s, mode): def _log(s): print '%s' % s def _log_debug(s): print 'DEBUG: %s' % s def _log_error(s): print 'ERROR: %s' % s exit() if mode is None: return mode = DEBUG_MODES.get(mode) if mode <= DEBUG_MODES[DEBUG_LEVEL]: if mode == DEBUG_MODES['log']: _log(s) elif mode == DEBUG_MODES['debug']: _log_debug(s) elif mode == DEBUG_MODES['error']: _log_error(s)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys sys.path.append('./') from androguard.core import androgen from androguard.core.analysis import analysis import Structure import Util import copy class This(): def __init__(self, cls): self.cls = cls self.used = False self.content = self def get_type(self): return self.cls.name def value(self): return 'this' def get_name(self): return 'this' class Var(): def __init__(self, name, typeDesc, type, size, content): self.name = name self.type = type self.size = size self.content = content self.param = False self.typeDesc = typeDesc self.used = 0 def get_content(self): return self.content def get_type(self): return self.typeDesc def init(self): if self.typeDesc == 'Z': return '%s = %s;\n' % (self.decl(), ['false', 'true'][self.content]) if self.typeDesc in Util.TYPE_DESCRIPTOR: return '%s = %s;\n' % (self.decl(), self.content) return '%s %s = %s;\n' % (self.type, self.name, self.content.value()) def value(self): if self.used < 1 and self.typeDesc in Util.TYPE_DESCRIPTOR: return self.name if self.content is not None: return self.content.value() self.used += 1 return self.name def int_value(self): return self.content.int_value() def get_name(self): if self.type is 'void': return self.content.value() self.used += 1 return self.name def neg(self): return self.content.neg() def dump(self, indent): if str(self.content.value()).startswith('ret'): return ' ' * indent + self.content.value() + ';\n' #return ' ' * indent + self.content.value() + ';(%d)\n' % self.used #if self.type is 'void': # if self.content.value() != 'this': # return ' ' * indent + '%s;(%d)\n' % (self.content.value(), self.used) # return '' return ' ' * indent + '%s %s = %s;\n' % (self.type, self.name, self.content.value()) #return ' ' * indent + '%s %s = %s;(%d)\n' % (self.type, self.name, # self.content.value(), self.used) def decl(self): return '%s %s' % (self.type, self.name) def __repr__(self): if self.content: return 'var(%s==%s==%s)' % (self.type, self.name, self.content) return 'var(%s===%s)' % (self.type, self.name) class Variable(): def __init__(self): self.nbVars = {} self.vars = [] def newVar(self, typeDesc, content=None): n = self.nbVars.setdefault(typeDesc, 1) self.nbVars[typeDesc] += 1 size = Util.get_type_size(typeDesc) _type = Util.get_type(typeDesc) if _type: type = _type.split('.')[-1] Util.log('typeDesc : %s' % typeDesc, 'debug') if type.endswith('[]'): name = '%sArray%d' % (type.strip('[]'), n) else: name = '%sVar%d' % (type, n) var = Var(name, typeDesc, type, size, content) self.vars.append(var) return var def startBlock(self): self.varscopy = copy.deepcopy(self.nbVars) def endBlock(self): self.nbVars = self.varscopy class DvMethod(): def __init__(self, methanalysis, this): self.memory = {} self.method = methanalysis.get_method() self.name = self.method.get_name() self.lparams = [] self.variables = Variable() self.tabsymb = {} if self.name == '<init>': self.name = self.method.get_class_name()[1:-1].split('/')[-1] self.basic_blocks = methanalysis.basic_blocks.bb code = self.method.get_code() access = self.method.get_access() self.access = [flag for flag in Util.ACCESS_FLAGS_METHODS if flag & access] desc = self.method.get_descriptor() self.type = Util.get_type(desc.split(')')[-1]) self.paramsType = Util.get_params_type(desc) Util.log('Searching loops in method %s' % self.name, 'debug') exceptions = methanalysis.exceptions.exceptions Util.log('METHOD : %s' % self.name, 'debug') #print "excepts :", [ e.exceptions for e in exceptions ] self.graph = Structure.ConstructAST(self.basic_blocks, exceptions) #androguard.bytecode.method2png('graphs/%s#%s.png' % \ # (self.method.get_class_name().split('/')[-1][:-1], self.name), # methanalysis) if code is None: Util.log('CODE NONE : %s %s' % (self.name, self.method.get_class_name()), 'debug') else: start = code.registers_size.get_value() - code.ins_size.get_value() # 0x8 == Static : 'this' is not passed as a parameter if 0x8 in self.access: self._add_parameters(start) else: self.memory[start] = this self._add_parameters(start + 1) self.ins = [] self.cur = 0 def _add_parameters(self, start): size = 0 for paramType in self.paramsType: param = self.variables.newVar(paramType) self.tabsymb[param.get_name()] = param param.param = True self.memory[start + size] = param self.lparams.append(param) size += param.size def process(self): if self.graph is None: return Util.log('METHOD : %s' % self.name, 'debug') Util.log('Processing %s' % self.graph.first_node(), 'debug') node = self.graph.first_node() blockins = node.process(self.memory, self.tabsymb, self.variables, 0, None, None) if blockins: self.ins.append(blockins) def debug(self, code=None): if code is None: code = [] Util.log('Dump of method :', 'debug') for j in self.memory.values(): Util.log(j, 'debug') Util.log('Dump of ins :', 'debug') acc = [] for i in self.access: if i == 0x10000: self.type = None else: acc.append(Util.ACCESS_FLAGS_METHODS.get(i)) if self.type: proto = ' %s %s %s(' % (' '.join(acc), self.type, self.name) else: proto = ' %s %s(' % (' '.join(acc), self.name) if self.paramsType: proto += ', '.join(['%s' % param.decl() for param in self.lparams]) proto += ')\n {\n' # for _, v in sorted(self.tabsymb.iteritems(), key=lambda x: x[0]): # if not (v in self.lparams): # proto += '%s%s' % (' ' * 2, v.init()) Util.log(proto, 'debug') code.append(proto) for i in self.ins: Util.log('%s' % i, 'debug') code.append(''.join([' ' * 2 + '%s\n' % ii for ii in i.splitlines()])) Util.log('}', 'debug') code.append(' }') return ''.join(code) def __repr__(self): return 'Method %s' % self.name class DvClass(): def __init__(self, dvclass, bca): self.name = dvclass.get_name() self.package = dvclass.get_name().rsplit('/', 1)[0][1:].replace('/', '.') self.this = This(self) lmethods = [(method.get_idx(), DvMethod(bca.get_method(method), self.this)) for method in dvclass.get_methods()] self.methods = dict(lmethods) self.fields = {} for field in dvclass.get_fields(): self.fields[field.get_name()] = field self.access = [] self.prototype = None self.subclasses = {} self.code = [] self.inner = False Util.log('Class : %s' % self.name, 'log') Util.log('Methods added :', 'log') for index, meth in self.methods.iteritems(): Util.log('%s (%s, %s)' % (index, meth.method.get_class_name(), meth.name), 'log') Util.log('\n', 'log') access = dvclass.format.get_value().access_flags access = [flag for flag in Util.ACCESS_FLAGS_CLASSES if flag & access] for i in access: self.access.append(Util.ACCESS_FLAGS_CLASSES.get(i)) self.prototype = '%s class %s' % (' '.join(self.access), self.name) self.interfaces = dvclass._interfaces self.superclass = dvclass._sname def add_subclass(self, innername, dvclass): self.subclasses[innername] = dvclass dvclass.inner = True def get_methods(self): meths = copy.copy(self.methods) for cls in self.subclasses.values(): meths.update(cls.get_methods()) return meths def select_meth(self, nb): if nb in self.methods: self.methods[nb].process() self.code.append(self.methods[nb].debug()) elif self.subclasses.values(): for cls in self.subclasses.values(): cls.select_meth(nb) else: Util.log('Method %s not found.' % nb, 'error') def show_code(self): if not self.inner and self.package: Util.log('package %s;\n' % self.package, 'log') if self.superclass is not None: self.superclass = self.superclass[1:-1].replace('/', '.') if self.superclass.split('.')[-1] == 'Object': self.superclass = None if self.superclass is not None: self.prototype += ' extends %s' % self.superclass if self.interfaces is not None: self.interfaces = self.interfaces[1:-1].split(' ') self.prototype += ' implements %s' % ', '.join( [n[1:-1].replace('/', '.') for n in self.interfaces]) Util.log('%s {' % self.prototype, 'log') for field in self.fields.values(): access = [Util.ACCESS_FLAGS_FIELDS.get(flag) for flag in Util.ACCESS_FLAGS_FIELDS if flag & field.get_access()] type = Util.get_type(field.get_descriptor()) name = field.get_name() Util.log('\t%s %s %s;' % (' '.join(access), type, name), 'log') Util.log('', 'log') for cls in self.subclasses.values(): cls.show_code() for ins in self.code: Util.log(ins, 'log') Util.log('}', 'log') def process(self): Util.log('SUBCLASSES : %s' % self.subclasses, 'debug') for cls in self.subclasses.values(): cls.process() Util.log('METHODS : %s' % self.methods, 'debug') for meth in self.methods: self.select_meth(meth) def __str__(self): return 'Class name : %s.' % self.name def __repr__(self): if self.subclasses == {}: return 'Class(%s)' % self.name return 'Class(%s) -- Subclasses(%s)' % (self.name, self.subclasses) class DvMachine(): def __init__(self, name): vm = androgen.AndroguardS(name).get_vm() bca = analysis.VMAnalysis(vm) self.vm = vm self.bca = bca ldict = [(dvclass.get_name(), DvClass(dvclass, bca)) for dvclass in vm.get_classes()] self.classes = dict(ldict) Util.merge_inner(self.classes) def get_class(self, className): for name, cls in self.classes.iteritems(): if className in name: return cls def process_class(self, cls): if cls is None: Util.log('No class to process.', 'error') else: cls.process() def process_method(self, cls, meth): if cls is None: Util.log('No class to process.', 'error') else: cls.select_meth(meth) def show_code(self, cls): if cls is None: Util.log('Class not found.', 'error') else: cls.show_code() if __name__ == '__main__': Util.DEBUG_LEVEL = 'debug' # MACHINE = DvMachine('examples/android/TestsAndroguard/bin/classes.dex') MACHINE = DvMachine('examples/android/TestsAndroguard/bin/droiddream.dex') from pprint import pprint temp = Util.wrap_stream() Util.log('===========================', 'log') Util.log('dvclass.get_Classes :', 'log') pprint(MACHINE.classes, temp) Util.log(temp, 'log') Util.log('===========================', 'log') CLS = raw_input('Choose a class: ') if CLS == '*': for CLS in MACHINE.classes: Util.log('CLS : %s' % CLS, 'log') cls = MACHINE.get_class(CLS) if cls is None: Util.log('%s not found.' % CLS, 'error') else: MACHINE.process_class(cls) Util.log('\n\nDump of code:', 'log') Util.log('===========================', 'log') for CLS in MACHINE.classes: MACHINE.show_code(MACHINE.get_class(CLS)) Util.log('===========================', 'log') else: cls = MACHINE.get_class(CLS) if cls is None: Util.log('%s not found.' % CLS, 'error') else: Util.log('======================', 'log') temp.clean() pprint(cls.get_methods(), temp) Util.log(temp, 'log') Util.log('======================', 'log') METH = raw_input('Method: ') if METH == '*': Util.log('CLASS = %s' % cls, 'log') MACHINE.process_class(cls) else: MACHINE.process_method(cls, int(METH)) Util.log('\n\nDump of code:', 'log') Util.log('===========================', 'log') MACHINE.show_code(cls)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import struct import Util CONDS = { '==' : '!=', '!=' : '==', '<' : '>=', '<=' : '>', '>=' : '<', '>' : '<=' } EXPR = 0 INST = 1 COND = 2 def get_invoke_params(params, params_type, memory): res = [] i = 0 while i < len(params_type): param = params[i] res.append(memory[param]) i += Util.get_type_size(params_type[i]) return res class Instruction(object): def __init__(self, ins): self.ins = ins self.ops = ins.get_operands() def get_reg(self): return [self.register] class AssignInstruction(Instruction): def __init__(self, ins): super(AssignInstruction, self).__init__(ins) self.lhs = self.ops[0][1] if len(self.ops) > 1: self.rhs = int(self.ops[1][1]) else: self.rhs = None def symbolic_process(self, memory, tabsymb, varsgen): Util.log('Default symbolic processing for this binary expression.', 'debug') if self.rhs is None: self.rhs = memory.get('heap') memory['heap'] = None Util.log('value :: %s' % self.rhs, 'debug') else: self.rhs = memory[self.rhs] var = varsgen.newVar(self.rhs.get_type(), self.rhs) tabsymb[var.get_name()] = var memory[self.lhs] = var self.lhs = var Util.log('Ins : %s = %s' % (var.get_name(), self.rhs), 'debug') def get_reg(self): return [self.lhs] def value(self): return '%s = %s' % (self.lhs.get_name(), self.rhs.value()) def get_type(self): return self.rhs.get_type() class StaticInstruction(Instruction): def __init__(self, ins): super(StaticInstruction, self).__init__(ins) self.register = self.ops[0][1] self.loc = Util.get_type(self.ops[1][2]) #FIXME remove name of class self.type = self.ops[1][3] self.name = self.ops[1][4] self.op = '%s.%s = %s' def get_reg(self): pass def symbolic_process(self, memory, tabsymb, varsgen): self.register = memory[self.register] def value(self): return self.op % (self.loc, self.name, self.register.value()) class InstanceInstruction(Instruction): def __init__(self, ins): super(InstanceInstruction, self).__init__(ins) self.rhs = self.ops[0][1] self.lhs = self.ops[1][1] self.name = self.ops[2][4] self.location = self.ops[2][2] # [1:-1].replace( '/', '.' ) self.type = 'V' self.op = '%s.%s = %s' def symbolic_process(self, memory, tabsymb, varsgen): self.rhs = memory[self.rhs] self.lhs = memory[self.lhs] def get_reg(self): Util.log('%s has no dest register.' % repr(self), 'debug') def value(self): return self.op % (self.lhs.value(), self.name, self.rhs.value()) def get_type(self): return self.type class InvokeInstruction(Instruction): def __init__(self, ins): super(InvokeInstruction, self).__init__(ins) self.register = self.ops[0][1] self.type = Util.get_type(self.ops[-1][2]) self.paramsType = Util.get_params_type(self.ops[-1][3]) self.returnType = Util.get_type(self.ops[-1][4]) self.methCalled = self.ops[-1][-1] def get_type(self): return self.returnType class ArrayInstruction(Instruction): def __init__(self, ins): super(ArrayInstruction, self).__init__(ins) self.source = self.ops[0][1] self.array = self.ops[1][1] self.index = self.ops[2][1] self.op = '%s[%s] = %s' def symbolic_process(self, memory, tabsymb, varsgen): self.source = memory[self.source] self.array = memory[self.array] self.index = memory[self.index] def value(self): if self.index.get_type() != 'I': return self.op % (self.array.value(), self.index.int_value(), self.source.value()) else: return self.op % (self.array.value(), self.index.value(), self.source.value()) def get_reg(self): Util.log('%s has no dest register.' % repr(self), 'debug') class ReturnInstruction(Instruction): def __init__(self, ins): super(ReturnInstruction, self).__init__(ins) if len(self.ops) > 0: self.register = self.ops[0][1] else: self.register = None def symbolic_process(self, memory, tabsymb, varsgen): if self.register is None: self.type = 'V' else: self.returnValue = memory[self.register] self.type = self.returnValue.get_type() def get_type(self): return self.type def value(self): if self.register is None: return 'return' else: return 'return %s' % self.returnValue.value() class Expression(object): def __init__(self, ins): self.ins = ins self.ops = ins.get_operands() def get_reg(self): return [self.register] def value(self): return '(expression %s has no value implemented)' % repr(self) def get_type(self): return '(expression %s has no type defined)' % repr(self) def symbolic_process(self, memory, tabsymb, varsgen): Util.log('Symbolic processing not implemented for this expression.', 'debug') class RefExpression(Expression): def __init__(self, ins): super(RefExpression, self).__init__(ins) self.register = self.ops[0][1] class BinaryExpression(Expression): def __init__(self, ins): super(BinaryExpression, self).__init__(ins) if len(self.ops) < 3: self.lhs = self.ops[0][1] self.rhs = self.ops[1][1] else: self.lhs = self.ops[1][1] self.rhs = self.ops[2][1] self.register = self.ops[0][1] def symbolic_process(self, memory, tabsymb, varsgen): Util.log('Default symbolic processing for this binary expression.', 'debug') self.lhs = memory[self.lhs] self.rhs = memory[self.rhs] var = varsgen.newVar(self.type, self) tabsymb[var.get_name()] = var memory[self.register] = var Util.log('Ins : %s' % self.op, 'debug') def value(self): return '(%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) def get_type(self): return self.type class BinaryExpressionLit(Expression): def __init__(self, ins): super(BinaryExpressionLit, self).__init__(ins) self.register = self.ops[0][1] self.lhs = self.ops[1][1] self.rhs = self.ops[2][1] def symbolic_process(self, memory, tabsymb, varsgen): Util.log('Default symbolic processing for this binary expression.', 'debug') self.lhs = memory[self.lhs] var = varsgen.newVar(self.type, self) tabsymb[var.get_name()] = var memory[self.register] = var Util.log('Ins : %s' % self.op, 'debug') def value(self): return '(%s %s %s)' % (self.lhs.value(), self.op, self.rhs) def get_type(self): return self.type class UnaryExpression(Expression): def __init__(self, ins): super(UnaryExpression, self).__init__(ins) self.register = self.ops[0][1] self.source = int(self.ops[1][1]) def symbolic_process(self, memory, tabsymb, varsgen): self.source = memory[self.source] var = varsgen.newVar(self.type, self) tabsymb[var.get_name()] = var memory[self.register] = var def value(self): if self.op.startswith('('): return self.source.value() #TEMP to avoir to much parenthesis return '(%s %s)' % (self.op, self.source.value()) def get_type(self): return self.type class IdentifierExpression(Expression): def __init__(self, ins): super(IdentifierExpression, self).__init__(ins) self.register = self.ops[0][1] def get_reg(self): return [self.register] def symbolic_process(self, memory, tabsymb, varsgen): var = varsgen.newVar(self.type, self) tabsymb[var.get_name()] = var memory[self.register] = var self.register = var def value(self): return '%s = %s' % (self.register.name, self.val) def get_type(self): return self.type class ConditionalExpression(Expression): def __init__(self, ins): super(ConditionalExpression, self).__init__(ins) self.lhs = self.ops[0][1] self.rhs = self.ops[1][1] def neg(self): self.op = CONDS[self.op] def get_reg(self): return '(condition expression %s has no dest register.)' % self def symbolic_process(self, memory, tabsymb, varsgen): self.lhs = memory[self.lhs] self.rhs = memory[self.rhs] def value(self): return '(%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) class ConditionalZExpression(Expression): def __init__(self, ins): super(ConditionalZExpression, self).__init__(ins) self.test = int(self.ops[0][1]) def get_reg(self): return '(zcondition expression %s has no dest register.)' % self def neg(self): self.op = CONDS[self.op] def symbolic_process(self, memory, tabsymb, varsgen): self.test = memory[self.test] def value(self): if self.test.get_type() == 'Z': return '(%s %s %s)' % (self.test.lhs.value(), self.op, self.test.rhs.value()) return '(%s %s 0)' % (self.test.value(), self.op) def get_type(self): return 'V' class ArrayExpression(Expression): def __init__(self, ins): super(ArrayExpression, self).__init__(ins) self.register = self.ops[0][1] self.ref = self.ops[1][1] self.idx = self.ops[2][1] self.op = '%s[%s]' def symbolic_process(self, memory, tabsymb, varsgen): self.ref = memory[self.ref] self.idx = memory[self.idx] self.type = self.ref.get_type()[1:] memory[self.register] = self Util.log('Ins : %s' % self.op, 'debug') def get_type(self): return self.type def value(self): return self.op % (self.ref.value(), self.idx.value()) class InstanceExpression(Expression): def __init__(self, ins): super(InstanceExpression, self).__init__(ins) self.register = self.ops[0][1] self.location = self.ops[-1][2] self.type = self.ops[-1][3] self.name = self.ops[-1][4] self.retType = self.ops[-1][-1] self.objreg = self.ops[1][1] self.op = '%s.%s' def symbolic_process(self, memory, tabsymb, varsgen): self.obj = memory[self.objreg] memory[self.register] = self Util.log('Ins : %s' % self.op, 'debug') def value(self): return self.op % (self.obj.value(), self.name) def get_type(self): return self.type class StaticExpression(Expression): def __init__(self, ins): super(StaticExpression, self).__init__(ins) self.register = self.ops[0][1] location = self.ops[1][2][1:-1] #FIXME if 'java/lang' in location: self.location = location.split('/')[-1] else: self.location = location.replace('/', '.') self.type = self.ops[1][3] #[1:-1].replace('/', '.') self.name = self.ops[1][4] self.op = '%s.%s' def symbolic_process(self, memory, tabsymb, varsgen): memory[self.register] = self def value(self): return self.op % (self.location, self.name) def get_type(self): return self.type # nop class Nop(UnaryExpression): def __init__(self, ins): Util.log('Nop %s' % ins, 'debug') self.op = '' def symbolic_process(self, memory, tabsymb, varsgen): pass def value(self): return '' # move vA, vB ( 4b, 4b ) class Move(AssignInstruction): def __init__(self, ins): super(Move, self).__init__(ins) Util.log('Move %s' % self.ops, 'debug') # move/from16 vAA, vBBBB ( 8b, 16b ) class MoveFrom16(AssignInstruction): def __init__(self, ins): super(MoveFrom16, self).__init__(ins) Util.log('MoveFrom16 %s' % self.ops, 'debug') # move/16 vAAAA, vBBBB ( 16b, 16b ) class Move16(AssignInstruction): def __init__(self, ins): super(Move16, self).__init__(ins) Util.log('Move16 %s' % self.ops, 'debug') # move-wide vA, vB ( 4b, 4b ) class MoveWide(AssignInstruction): def __init__(self, ins): super(MoveWide, self).__init__(ins) Util.log('MoveWide %s' % self.ops, 'debug') # move-wide/from16 vAA, vBBBB ( 8b, 16b ) class MoveWideFrom16(AssignInstruction): def __init__(self, ins): super(MoveWideFrom16, self).__init__(ins) Util.log('MoveWideFrom16 : %s' % self.ops, 'debug') # move-wide/16 vAAAA, vBBBB ( 16b, 16b ) class MoveWide16(AssignInstruction): def __init__(self, ins): super(MoveWide16, self).__init__(ins) Util.log('MoveWide16 %s' % self.ops, 'debug') # move-object vA, vB ( 4b, 4b ) class MoveObject(AssignInstruction): def __init__(self, ins): super(MoveObject, self).__init__(ins) Util.log('MoveObject %s' % self.ops, 'debug') # move-object/from16 vAA, vBBBB ( 8b, 16b ) class MoveObjectFrom16(AssignInstruction): def __init__(self, ins): super(MoveObjectFrom16, self).__init__(ins) Util.log('MoveObjectFrom16 : %s' % self.ops, 'debug') # move-object/16 vAAAA, vBBBB ( 16b, 16b ) class MoveObject16(AssignInstruction): def __init__(self, ins): super(MoveObject16, self).__init__(ins) Util.log('MoveObject16 : %s' % self.ops, 'debug') # move-result vAA ( 8b ) class MoveResult(AssignInstruction): def __init__(self, ins): super(MoveResult, self).__init__(ins) Util.log('MoveResult : %s' % self.ops, 'debug') def __str__(self): return 'Move res in v' + str(self.ops[0][1]) # move-result-wide vAA ( 8b ) class MoveResultWide(AssignInstruction): def __init__(self, ins): super(MoveResultWide, self).__init__(ins) Util.log('MoveResultWide : %s' % self.ops, 'debug') def __str__(self): return 'MoveResultWide in v' + str(self.ops[0][1]) # move-result-object vAA ( 8b ) class MoveResultObject(AssignInstruction): def __init__(self, ins): super(MoveResultObject, self).__init__(ins) Util.log('MoveResultObject : %s' % self.ops, 'debug') def __str__(self): return 'MoveResObj in v' + str(self.ops[0][1]) # move-exception vAA ( 8b ) class MoveException(Expression): def __init__(self, ins): super(MoveException, self).__init__(ins) Util.log('MoveException : %s' % self.ops, 'debug') # return-void class ReturnVoid(ReturnInstruction): def __init__(self, ins): super(ReturnVoid, self).__init__(ins) Util.log('ReturnVoid', 'debug') def __str__(self): return 'Return' # return vAA ( 8b ) class Return(ReturnInstruction): def __init__(self, ins): super(Return, self).__init__(ins) Util.log('Return : %s' % self.ops, 'debug') def __str__(self): return 'Return (%s)' % str(self.returnValue) # return-wide vAA ( 8b ) class ReturnWide(ReturnInstruction): def __init__(self, ins): super(ReturnWide, self).__init__(ins) Util.log('ReturnWide : %s' % self.ops, 'debug') def __str__(self): return 'ReturnWide (%s)' % str(self.returnValue) # return-object vAA ( 8b ) class ReturnObject(ReturnInstruction): def __init__(self, ins): super(ReturnObject, self).__init__(ins) Util.log('ReturnObject : %s' % self.ops, 'debug') def __str__(self): return 'ReturnObject (%s)' % str(self.returnValue) # const/4 vA, #+B ( 4b, 4b ) class Const4(IdentifierExpression): def __init__(self, ins): super(Const4, self).__init__(ins) Util.log('Const4 : %s' % self.ops, 'debug') self.val = int(self.ops[1][1]) self.type = 'I' Util.log('==> %s' % self.val, 'debug') def __str__(self): return 'Const4 : %s' % str(self.val) # const/16 vAA, #+BBBB ( 8b, 16b ) class Const16(IdentifierExpression): def __init__(self, ins): super(Const16, self).__init__(ins) Util.log('Const16 : %s' % self.ops, 'debug') self.val = int(self.ops[1][1]) self.type = 'I' Util.log('==> %s' % self.val, 'debug') def __str__(self): return 'Const16 : %s' % str(self.val) # const vAA, #+BBBBBBBB ( 8b, 32b ) class Const(IdentifierExpression): def __init__(self, ins): super(Const, self).__init__(ins) Util.log('Const : %s' % self.ops, 'debug') self.val = ((0xFFFF & self.ops[2][1]) << 16) | ((0xFFFF & self.ops[1][1])) self.type = 'F' Util.log('==> %s' % self.val, 'debug') def value(self): return struct.unpack('f', struct.pack('L', self.val))[0] def int_value(self): return self.val def __str__(self): return 'Const : ' + str(self.val) # const/high16 vAA, #+BBBB0000 ( 8b, 16b ) class ConstHigh16(IdentifierExpression): def __init__(self, ins): super(ConstHigh16, self).__init__(ins) Util.log('ConstHigh16 : %s' % self.ops, 'debug') self.val = struct.unpack('f', struct.pack('i', self.ops[1][1] << 16))[0] self.type = 'F' Util.log('==> %s' % self.val, 'debug') def __str__(self): return 'ConstHigh16 : %s' % str(self.val) # const-wide/16 vAA, #+BBBB ( 8b, 16b ) class ConstWide16(IdentifierExpression): def __init__(self, ins): super(ConstWide16, self).__init__(ins) Util.log('ConstWide16 : %s' % self.ops, 'debug') self.type = 'J' self.val = struct.unpack('d', struct.pack('d', self.ops[1][1]))[0] Util.log('==> %s' % self.val, 'debug') def get_reg(self): return [self.register, self.register + 1] def __str__(self): return 'Constwide16 : %s' % str(self.val) # const-wide/32 vAA, #+BBBBBBBB ( 8b, 32b ) class ConstWide32(IdentifierExpression): def __init__(self, ins): super(ConstWide32, self).__init__(ins) Util.log('ConstWide32 : %s' % self.ops, 'debug') self.type = 'J' val = ((0xFFFF & self.ops[2][1]) << 16) | ((0xFFFF & self.ops[1][1])) self.val = struct.unpack('d', struct.pack('d', val))[0] Util.log('==> %s' % self.val, 'debug') def get_reg(self): return [self.register, self.register + 1] def __str__(self): return 'Constwide32 : %s' % str(self.val) # const-wide vAA, #+BBBBBBBBBBBBBBBB ( 8b, 64b ) class ConstWide(IdentifierExpression): def __init__(self, ins): super(ConstWide, self).__init__(ins) Util.log('ConstWide : %s' % self.ops, 'debug') val = self.ops[1:] val = (0xFFFF & val[0][1]) | ((0xFFFF & val[1][1]) << 16) | (\ (0xFFFF & val[2][1]) << 32) | ((0xFFFF & val[3][1]) << 48) self.type = 'D' self.val = struct.unpack('d', struct.pack('Q', val))[0] Util.log('==> %s' % self.val, 'debug') def get_reg(self): return [self.register, self.register + 1] def __str__(self): return 'ConstWide : %s' % str(self.val) # const-wide/high16 vAA, #+BBBB000000000000 ( 8b, 16b ) class ConstWideHigh16(IdentifierExpression): def __init__(self, ins): super(ConstWideHigh16, self).__init__(ins) Util.log('ConstWideHigh16 : %s' % self.ops, 'debug') self.val = struct.unpack('d', struct.pack('Q', 0xFFFFFFFFFFFFFFFF & int(self.ops[1][1]) << 48))[0] self.type = 'D' Util.log('==> %s' % self.val, 'debug') def get_reg(self): return [self.register, self.register + 1] def __str__(self): return 'ConstWide : %s' % str(self.val) # const-string vAA ( 8b ) class ConstString(IdentifierExpression): def __init__(self, ins): super(ConstString, self).__init__(ins) Util.log('ConstString : %s' % self.ops, 'debug') self.val = '%s' % self.ops[1][2] self.type = 'STR' Util.log('==> %s' % self.val, 'debug') def __str__(self): return 'ConstString : %s' % str(self.val) # const-string/jumbo vAA ( 8b ) class ConstStringJumbo(IdentifierExpression): pass # const-class vAA ( 8b ) class ConstClass(IdentifierExpression): def __init__(self, ins): super(ConstClass, self).__init__(ins) Util.log('ConstClass : %s' % self.ops, 'debug') self.type = '%s' % self.ops[1][2] self.val = self.type Util.log('==> %s' % self.val, 'debug') def __str__(self): return 'ConstClass : %s' % str(self.val) # monitor-enter vAA ( 8b ) class MonitorEnter(RefExpression): def __init__(self, ins): super(MonitorEnter, self).__init__(ins) Util.log('MonitorEnter : %s' % self.ops, 'debug') self.op = 'synchronized( %s )' def symbolic_process(self, memory, tabsymb, varsgen): self.register = memory[self.register] def get_type(self): return self.register.get_type() def get_reg(self): Util.log('MonitorEnter has no dest register', 'debug') def value(self): return self.op % self.register.value() # monitor-exit vAA ( 8b ) class MonitorExit(RefExpression): def __init__(self, ins): super(MonitorExit, self).__init__(ins) Util.log('MonitorExit : %s' % self.ops, 'debug') self.op = '' def symbolic_process(self, memory, tabsymb, varsgen): self.register = memory[self.register] def get_type(self): return self.register.get_type() def get_reg(self): Util.log('MonitorExit has no dest register', 'debug') def value(self): return '' # check-cast vAA ( 8b ) class CheckCast(RefExpression): def __init__(self, ins): super(CheckCast, self).__init__(ins) Util.log('CheckCast: %s' % self.ops, 'debug') self.register = self.ops[0][1] def symbolic_process(self, memory, tabsymb, varsgen): self.register = memory[self.register] def get_type(self): Util.log('type : %s ' % self.register, 'debug') return self.register.get_type() def get_reg(self): Util.log('CheckCast has no dest register', 'debug') # instance-of vA, vB ( 4b, 4b ) class InstanceOf(BinaryExpression): def __init__(self, ins): super(InstanceOf, self).__init__(ins) Util.log('InstanceOf : %s' % self.ops, 'debug') # array-length vA, vB ( 4b, 4b ) class ArrayLength(RefExpression): def __init__(self, ins): super(ArrayLength, self).__init__(ins) Util.log('ArrayLength: %s' % self.ops, 'debug') self.src = self.ops[1][1] self.op = '%s.length' def symbolic_process(self, memory, tabsymb, varsgen): self.src = memory[self.src] memory[self.register] = self def value(self): return self.op % self.src.value() def get_type(self): return self.src.get_type() # new-instance vAA ( 8b ) class NewInstance(RefExpression): def __init__(self, ins): super(NewInstance, self).__init__(ins) Util.log('NewInstance : %s' % self.ops, 'debug') self.type = self.ops[-1][-1] self.op = 'new %s' def symbolic_process(self, memory, tabsymb, varsgen): self.type = Util.get_type(self.type) memory[self.register] = self def value(self): return self.op % self.type def get_type(self): return self.type def __str__(self): return 'New ( %s )' % self.type # new-array vA, vB ( 8b, size ) class NewArray(RefExpression): def __init__(self, ins): super(NewArray, self).__init__(ins) Util.log('NewArray : %s' % self.ops, 'debug') self.size = int(self.ops[1][1]) self.type = self.ops[-1][-1] self.op = 'new %s' def symbolic_process(self, memory, tabsymb, varsgen): self.size = memory[self.size] memory[self.register] = self def value(self): return self.op % Util.get_type(self.type, self.size.value()) def get_type(self): return self.type def __str__(self): return 'NewArray( %s )' % self.type # filled-new-array {vD, vE, vF, vG, vA} ( 4b each ) class FilledNewArray(UnaryExpression): pass # filled-new-array/range {vCCCC..vNNNN} ( 16b ) class FilledNewArrayRange(UnaryExpression): pass # fill-array-data vAA, +BBBBBBBB ( 8b, 32b ) class FillArrayData(UnaryExpression): def __init__(self, ins): super(FillArrayData, self).__init__(ins) Util.log('FillArrayData : %s' % self.ops, 'debug') def symbolic_process(self, memory, tabsymb, varsgen): self.type = memory[self.register].get_type() def value(self): return self.ins.get_op_value() def get_type(self): return self.type def get_reg(self): Util.log('FillArrayData has no dest register.', 'debug') # throw vAA ( 8b ) class Throw(RefExpression): pass # goto +AA ( 8b ) class Goto(Expression): pass # goto/16 +AAAA ( 16b ) class Goto16(Expression): pass # goto/32 +AAAAAAAA ( 32b ) class Goto32(Expression): pass # packed-switch vAA, +BBBBBBBB ( reg to test, 32b ) class PackedSwitch(Instruction): def __init__(self, ins): super(PackedSwitch, self).__init__(ins) Util.log('PackedSwitch : %s' % self.ops, 'debug') self.register = self.ops[0][1] def symbolic_process(self, memory, tabsymb, varsgen): self.register = memory[self.register] def value(self): return self.register.value() def get_reg(self): Util.log('PackedSwitch has no dest register.', 'debug') # sparse-switch vAA, +BBBBBBBB ( reg to test, 32b ) class SparseSwitch(UnaryExpression): pass # cmpl-float vAA, vBB, vCC ( 8b, 8b, 8b ) class CmplFloat(BinaryExpression): def __init__(self, ins): super(CmplFloat, self).__init__(ins) Util.log('CmpglFloat : %s' % self.ops, 'debug') self.op = '==' self.type = 'F' def __str__(self): return 'CmplFloat (%s < %s ?)' % (self.rhs.value(), self.lhs.value()) # cmpg-float vAA, vBB, vCC ( 8b, 8b, 8b ) class CmpgFloat(BinaryExpression): def __init__(self, ins): super(CmpgFloat, self).__init__(ins) Util.log('CmpgFloat : %s' % self.ops, 'debug') self.op = '==' self.type = 'F' def __str__(self): return 'CmpgFloat (%s > %s ?)' % (self.rhs.value(), self.lhs.value()) # cmpl-double vAA, vBB, vCC ( 8b, 8b, 8b ) class CmplDouble(BinaryExpression): def __init__(self, ins): super(CmplDouble, self).__init__(ins) Util.log('CmplDouble : %s' % self.ops, 'debug') self.op = '==' self.type = 'D' def __str__(self): return 'CmplDouble (%s < %s ?)' % (self.rhs.value(), self.lhs.value()) # cmpg-double vAA, vBB, vCC ( 8b, 8b, 8b ) class CmpgDouble(BinaryExpression): def __init__(self, ins): super(CmpgDouble, self).__init__(ins) Util.log('CmpgDouble : %s' % self.ops, 'debug') self.op = '==' self.type = 'D' def __str__(self): return 'CmpgDouble (%s > %s ?)' % (self.rhs.value(), self.lhs.value()) # cmp-long vAA, vBB, vCC ( 8b, 8b, 8b ) class CmpLong(BinaryExpression): def __init__(self, ins): super(CmpLong, self).__init__(ins) Util.log('CmpLong : %s' % self.ops, 'debug') self.op = '==' self.type = 'J' def __str__(self): return 'CmpLong (%s == %s ?)' % (self.rhs.value(), self.lhs.value()) # if-eq vA, vB, +CCCC ( 4b, 4b, 16b ) class IfEq(ConditionalExpression): def __init__(self, ins): super(IfEq, self).__init__(ins) Util.log('IfEq : %s' % self.ops, 'debug') self.op = '==' def __str__(self): return 'IfEq (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-ne vA, vB, +CCCC ( 4b, 4b, 16b ) class IfNe(ConditionalExpression): def __init__(self, ins): super(IfNe, self).__init__(ins) Util.log('IfNe : %s' % self.ops, 'debug') self.op = '!=' def __str__(self): return 'IfNe (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-lt vA, vB, +CCCC ( 4b, 4b, 16b ) class IfLt(ConditionalExpression): def __init__(self, ins): super(IfLt, self).__init__(ins) Util.log('IfLt : %s' % self.ops, 'debug') self.op = '<' def __str__(self): return 'IfLt (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-ge vA, vB, +CCCC ( 4b, 4b, 16b ) class IfGe(ConditionalExpression): def __init__(self, ins): super(IfGe, self).__init__(ins) Util.log('IfGe : %s' % self.ops, 'debug') self.op = '>=' def __str__(self): return 'IfGe (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-gt vA, vB, +CCCC ( 4b, 4b, 16b ) class IfGt(ConditionalExpression): def __init__(self, ins): super(IfGt, self).__init__(ins) Util.log('IfGt : %s' % self.ops, 'debug') self.op = '>' def __str__(self): return 'IfGt (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-le vA, vB, +CCCC ( 4b, 4b, 16b ) class IfLe(ConditionalExpression): def __init__(self, ins): super(IfLe, self).__init__(ins) Util.log('IfLe : %s' % self.ops, 'debug') self.op = '<=' def __str__(self): return 'IfLe (%s %s %s)' % (self.lhs.value(), self.op, self.rhs.value()) # if-eqz vAA, +BBBB ( 8b, 16b ) class IfEqz(ConditionalZExpression): def __init__(self, ins): super(IfEqz, self).__init__(ins) Util.log('IfEqz : %s' % self.ops, 'debug') self.op = '==' def get_reg(self): Util.log('IfEqz has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': if self.op == '==': return '!%s' % self.test.value() else: return '%s' % self.test.value() return '%s %s 0' % (self.test.value(), self.op) def __str__(self): return 'IfEqz (%s)' % (self.test.value()) # if-nez vAA, +BBBB ( 8b, 16b ) class IfNez(ConditionalZExpression): def __init__(self, ins): super(IfNez, self).__init__(ins) Util.log('IfNez : %s' % self.ops, 'debug') self.op = '!=' def get_reg(self): Util.log('IfNez has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': if self.op == '==': return '%s' % self.test.value() else: return '!%s' % self.test.value() return '%s %s 0' % (self.test.value(), self.op) def __str__(self): return 'IfNez (%s)' % self.test.value() # if-ltz vAA, +BBBB ( 8b, 16b ) class IfLtz(ConditionalZExpression): def __init__(self, ins): super(IfLtz, self).__init__(ins) Util.log('IfLtz : %s' % self.ops, 'debug') self.op = '<' def get_reg(self): Util.log('IfLtz has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': return '(%s %s %s)' % (self.test.content.first.value(), self.op, self.test.content.second.value()) return '(%s %s 0)' % (self.test.value(), self.op) def __str__(self): return 'IfLtz (%s)' % self.test.value() # if-gez vAA, +BBBB ( 8b, 16b ) class IfGez(ConditionalZExpression): def __init__(self, ins): super(IfGez, self).__init__(ins) Util.log('IfGez : %s' % self.ops, 'debug') self.op = '>=' def get_reg(self): Util.log('IfGez has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': return '(%s %s %s)' % (self.test.content.first.value(), self.op, self.test.content.second.value()) return '(%s %s 0)' % (self.test.value(), self.op) def __str__(self): return 'IfGez (%s)' % self.test.value() # if-gtz vAA, +BBBB ( 8b, 16b ) class IfGtz(ConditionalZExpression): def __init__(self, ins): super(IfGtz, self).__init__(ins) Util.log('IfGtz : %s' % self.ops, 'debug') self.test = int(self.ops[0][1]) self.op = '>' def get_reg(self): Util.log('IfGtz has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': return '(%s %s %s)' % (self.test.content.first.value(), self.op, self.test.content.second.value()) return '(%s %s 0)' % (self.test.value(), self.op) def __str__(self): return 'IfGtz (%s)' % self.test.value() # if-lez vAA, +BBBB (8b, 16b ) class IfLez(ConditionalZExpression): def __init__(self, ins): super(IfLez, self).__init__(ins) Util.log('IfLez : %s' % self.ops, 'debug') self.test = int(self.ops[0][1]) self.op = '<=' def get_reg(self): Util.log('IfLez has no dest register', 'debug') def value(self): if self.test.get_type() == 'Z': return '(%s %s %s)' % (self.test.content.first.value(), self.op, self.test.content.second.value()) return '(%s %s 0)' % (self.test.value(), self.op) def __str__(self): return 'IfLez (%s)' % self.test.value() #FIXME: check type all aget # aget vAA, vBB, vCC ( 8b, 8b, 8b ) class AGet(ArrayExpression): def __init__(self, ins): super(AGet, self).__init__(ins) Util.log('AGet : %s' % self.ops, 'debug') # aget-wide vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetWide(ArrayExpression): def __init__(self, ins): super(AGetWide, self).__init__(ins) Util.log('AGetWide : %s' % self.ops, 'debug') # aget-object vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetObject(ArrayExpression): def __init__(self, ins): super(AGetObject, self).__init__(ins) Util.log('AGetObject : %s' % self.ops, 'debug') # aget-boolean vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetBoolean(ArrayExpression): def __init__(self, ins): super(AGetBoolean, self).__init__(ins) Util.log('AGetBoolean : %s' % self.ops, 'debug') # aget-byte vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetByte(ArrayExpression): def __init__(self, ins): super(AGetByte, self).__init__(ins) Util.log('AGetByte : %s' % self.ops, 'debug') # aget-char vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetChar(ArrayExpression): def __init__(self, ins): super(AGetChar, self).__init__(ins) Util.log('AGetChar : %s' % self.ops, 'debug') # aget-short vAA, vBB, vCC ( 8b, 8b, 8b ) class AGetShort(ArrayExpression): def __init__(self, ins): super(AGetShort, self).__init__(ins) Util.log('AGetShort : %s' % self.ops, 'debug') # aput vAA, vBB, vCC class APut(ArrayInstruction): def __init__(self, ins): super(APut, self).__init__(ins) Util.log('APut : %s' % self.ops, 'debug') # aput-wide vAA, vBB, vCC ( 8b, 8b, 8b ) class APutWide(ArrayInstruction): def __init__(self, ins): super(APutWide, self).__init__(ins) Util.log('APutWide : %s' % self.ops, 'debug') # aput-object vAA, vBB, vCC ( 8b, 8b, 8b ) class APutObject(ArrayInstruction): def __init__(self, ins): super(APutObject, self).__init__(ins) Util.log('APutObject : %s' % self.ops, 'debug') # aput-boolean vAA, vBB, vCC ( 8b, 8b, 8b ) class APutBoolean(ArrayInstruction): def __init__(self, ins): super(APutBoolean, self).__init__(ins) Util.log('APutBoolean : %s' % self.ops, 'debug') # aput-byte vAA, vBB, vCC ( 8b, 8b, 8b ) class APutByte(ArrayInstruction): def __init__(self, ins): super(APutByte, self).__init__(ins) Util.log('APutByte : %s' % self.ops, 'debug') # aput-char vAA, vBB, vCC ( 8b, 8b, 8b ) class APutChar(ArrayInstruction): def __init__(self, ins): super(APutChar, self).__init__(ins) Util.log('APutChar : %s' % self.ops, 'debug') # aput-short vAA, vBB, vCC ( 8b, 8b, 8b ) class APutShort(ArrayInstruction): def __init__(self, ins): super(APutShort, self).__init__(ins) Util.log('APutShort : %s' % self.ops, 'debug') # iget vA, vB ( 4b, 4b ) class IGet(InstanceExpression): def __init__(self, ins): super(IGet, self).__init__(ins) Util.log('IGet : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-wide vA, vB ( 4b, 4b ) class IGetWide(InstanceExpression): def __init__(self, ins): super(IGetWide, self).__init__(ins) Util.log('IGetWide : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-object vA, vB ( 4b, 4b ) class IGetObject(InstanceExpression): def __init__(self, ins): super(IGetObject, self).__init__(ins) Util.log('IGetObject : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-boolean vA, vB ( 4b, 4b ) class IGetBoolean(InstanceExpression): def __init__(self, ins): super(IGetBoolean, self).__init__(ins) Util.log('IGetBoolean : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-byte vA, vB ( 4b, 4b ) class IGetByte(InstanceExpression): def __init__(self, ins): super(IGetByte, self).__init__(ins) Util.log('IGetByte : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-char vA, vB ( 4b, 4b ) class IGetChar(InstanceExpression): def __init__(self, ins): super(IGetChar, self).__init__(ins) Util.log('IGetChar : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iget-short vA, vB ( 4b, 4b ) class IGetShort(InstanceExpression): def __init__(self, ins): super(IGetShort, self).__init__(ins) Util.log('IGetShort : %s' % self.ops, 'debug') def __str__(self): return '( %s ) %s.%s' % (self.type, self.location, self.name) # iput vA, vB ( 4b, 4b ) class IPut(InstanceInstruction): def __init__(self, ins): super(IPut, self).__init__(ins) Util.log('IPut %s' % self.ops, 'debug') # iput-wide vA, vB ( 4b, 4b ) class IPutWide(InstanceInstruction): def __init__(self, ins): super(IPutWide, self).__init__(ins) Util.log('IPutWide %s' % self.ops, 'debug') # iput-object vA, vB ( 4b, 4b ) class IPutObject(InstanceInstruction): def __init__(self, ins): super(IPutObject, self).__init__(ins) Util.log('IPutObject %s' % self.ops, 'debug') # iput-boolean vA, vB ( 4b, 4b ) class IPutBoolean(InstanceInstruction): def __init__(self, ins): super(IPutBoolean, self).__init__(ins) Util.log('IPutBoolean %s' % self.ops, 'debug') # iput-byte vA, vB ( 4b, 4b ) class IPutByte(InstanceInstruction): def __init__(self, ins): super(IPutBoolean, self).__init__(ins) Util.log('IPutByte %s' % self.ops, 'debug') # iput-char vA, vB ( 4b, 4b ) class IPutChar(InstanceInstruction): def __init__(self, ins): super(IPutBoolean, self).__init__(ins) Util.log('IPutChar %s' % self.ops, 'debug') # iput-short vA, vB ( 4b, 4b ) class IPutShort(InstanceInstruction): def __init__(self, ins): super(IPutBoolean, self).__init__(ins) Util.log('IPutShort %s' % self.ops, 'debug') # sget vAA ( 8b ) class SGet(StaticExpression): def __init__(self, ins): super(SGet, self).__init__(ins) Util.log('SGet : %s' % self.ops, 'debug') def __str__(self): if self.location: return '(%s) %s.%s' % (self.type, self.location, self.name) return '(%s) %s' % (self.type, self.name) # sget-wide vAA ( 8b ) class SGetWide(StaticExpression): def __init__(self, ins): super(SGetWide, self).__init__(ins) Util.log('SGetWide : %s' % self.ops, 'debug') # sget-object vAA ( 8b ) class SGetObject(StaticExpression): def __init__(self, ins): super(SGetObject, self).__init__(ins) Util.log('SGetObject : %s' % self.ops, 'debug') def __str__(self): if self.location: return '(%s) %s.%s' % (self.type, self.location, self.name) return '(%s) %s' % (self.type, self.name) # sget-boolean vAA ( 8b ) class SGetBoolean(StaticExpression): def __init__(self, ins): super(SGetBoolean, self).__init__(ins) Util.log('SGetBoolean : %s' % self.ops, 'debug') # sget-byte vAA ( 8b ) class SGetByte(StaticExpression): def __init__(self, ins): super(SGetByte, self).__init__(ins) Util.log('SGetByte : %s' % self.ops, 'debug') # sget-char vAA ( 8b ) class SGetChar(StaticExpression): def __init__(self, ins): super(SGetChar, self).__init__(ins) Util.log('SGetChar : %s' % self.ops, 'debug') # sget-short vAA ( 8b ) class SGetShort(StaticExpression): def __init__(self, ins): super(SGetShort, self).__init__(ins) Util.log('SGetShort : %s' % self.ops, 'debug') # sput vAA ( 8b ) class SPut(StaticInstruction): def __init__(self, ins): super(SPut, self).__init__(ins) Util.log('SPut : %s' % self.ops, 'debug') def __str__(self): if self.loc: return '(%s) %s.%s' % (self.type, self.loc, self.name) return '(%s) %s' % (self.type, self.name) # sput-wide vAA ( 8b ) class SPutWide(StaticInstruction): def __init__(self, ins): super(SPutWide, self).__init__(ins) Util.log('SPutWide : %s' % self.ops, 'debug') # sput-object vAA ( 8b ) class SPutObject(StaticInstruction): def __init__(self, ins): super(SPutObject, self).__init__(ins) Util.log('SPutObject : %s' % self.ops, 'debug') def __str__(self): if self.loc: return '(%s) %s.%s' % (self.type, self.loc, self.name) return '(%s) %s' % (self.type, self.name) # sput-boolean vAA ( 8b ) class SPutBoolean(StaticInstruction): def __init__(self, ins): super(SPutBoolean, self).__init__(ins) Util.log('SPutBoolean : %s' % self.ops, 'debug') # sput-wide vAA ( 8b ) class SPutByte(StaticInstruction): def __init__(self, ins): super(SPutByte, self).__init__(ins) Util.log('SPutByte : %s' % self.ops, 'debug') # sput-char vAA ( 8b ) class SPutChar(StaticInstruction): def __init__(self, ins): super(SPutChar, self).__init__(ins) Util.log('SPutChar : %s' % self.ops, 'debug') # sput-short vAA ( 8b ) class SPutShort(StaticInstruction): def __init__(self, ins): super(SPutShort, self).__init__(ins) Util.log('SPutShort : %s' % self.ops, 'debug') # invoke-virtual {vD, vE, vF, vG, vA} ( 4b each ) class InvokeVirtual(InvokeInstruction): def __init__(self, ins): super(InvokeVirtual, self).__init__(ins) Util.log('InvokeVirtual : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] Util.log('Parameters = %s' % self.params, 'debug') def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.base = memory[self.register] self.params = get_invoke_params(self.params, self.paramsType, memory) if self.base.value() == 'this': self.op = '%s(%s)' else: self.op = '%s.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): for param in self.params: param.used = 1 if self.base.value() == 'this': return self.op % (self.methCalled, ', '.join([str( param.value()) for param in self.params])) return self.op % (self.base.value(), self.methCalled, ', '.join([ str(param.value()) for param in self.params])) def get_reg(self): Util.log('InvokeVirtual has no dest register.', 'debug') def __str__(self): return 'InvokeVirtual (%s) %s (%s ; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # invoke-super {vD, vE, vF, vG, vA} ( 4b each ) class InvokeSuper(InvokeInstruction): def __init__(self, ins): super(InvokeSuper, self).__init__(ins) Util.log('InvokeSuper : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = 'super.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): return self.op % (self.methCalled, ', '.join( [str(param.value()) for param in self.params])) def get_reg(self): Util.log('InvokeSuper has no dest register.', 'debug') def __str__(self): return 'InvokeSuper (%s) %s (%s ; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # invoke-direct {vD, vE, vF, vG, vA} ( 4b each ) class InvokeDirect(InvokeInstruction): def __init__(self, ins): super(InvokeDirect, self).__init__(ins) Util.log('InvokeDirect : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.base = memory[self.register] if self.base.value() == 'this': self.op = None else: self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = '%s %s(%s)' def value(self): if self.op is None: return self.base.value() return self.op % (self.base.value(), self.type, ', '.join( [str(param.value()) for param in self.params])) def __str__(self): return 'InvokeDirect (%s) %s (%s)' % (self.returnType, self.methCalled, str(self.params)) # invoke-static {vD, vE, vF, vG, vA} ( 4b each ) class InvokeStatic(InvokeInstruction): def __init__(self, ins): super(InvokeStatic, self).__init__(ins) Util.log('InvokeStatic : %s' % self.ops, 'debug') if len(self.ops) > 1: self.params = [int(i[1]) for i in self.ops[0:-1]] else: self.params = [] Util.log('Parameters = %s' % self.params, 'debug') def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = '%s.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): return self.op % (self.type, self.methCalled, ', '.join([ str(param.value()) for param in self.params])) def get_reg(self): Util.log('InvokeStatic has no dest register.', 'debug') def __str__(self): return 'InvokeStatic (%s) %s (%s ; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # invoke-interface {vD, vE, vF, vG, vA} ( 4b each ) class InvokeInterface(InvokeInstruction): def __init__(self, ins): super(InvokeInterface, self).__init__(ins) Util.log('InvokeInterface : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.base = memory[self.register] if self.base.value() == 'this': self.op = None else: self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = '%s %s(%s)' def value(self): if self.op is None: return self.base.value() return self.op % (self.base.value(), self.type, ', '.join( [str(param.value()) for param in self.params])) def __str__(self): return 'InvokeInterface (%s) %s (%s)' % (self.returnType, self.methCalled, str(self.params)) # invoke-virtual/range {vCCCC..vNNNN} ( 16b each ) class InvokeVirtualRange(InvokeInstruction): def __init__(self, ins): super(InvokeVirtualRange, self).__init__(ins) Util.log('InvokeVirtualRange : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] Util.log('Parameters = %s' % self.params, 'debug') self.type = self.ops[-1][2] self.paramsType = Util.get_params_type(self.ops[-1][3]) self.returnType = self.ops[-1][4] self.methCalled = self.ops[-1][-1] def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.base = memory[self.register] self.params = get_invoke_params(self.params, self.paramsType, memory) if self.base.value() == 'this': self.op = '%s(%s)' else: self.op = '%s.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): if self.base.value() == 'this': return self.op % (self.methCalled, ', '.join( [str(param.value()) for param in self.params])) return self.op % (self.base.value(), self.methCalled, ', '.join( [str(param.value()) for param in self.params])) def get_type(self): return self.returnType def get_reg(self): Util.log('InvokeVirtualRange has no dest register.', 'debug') def __str__(self): return 'InvokeVirtualRange (%s) %s (%s; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # invoke-super/range {vCCCC..vNNNN} ( 16b each ) class InvokeSuperRange(InvokeInstruction): pass # invoke-direct/range {vCCCC..vNNNN} ( 16b each ) class InvokeDirectRange(InvokeInstruction): def __init__(self, ins): super(InvokeDirectRange, self).__init__(ins) Util.log('InvokeDirectRange : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] self.paramsType = Util.get_params_type(self.ops[-1][3]) self.returnType = self.ops[-1][4] self.methCalled = self.ops[-1][-1] def symbolic_process(self, memory, tabsymb, varsgen): self.base = memory[self.register] self.type = self.base.get_type() self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = '%s %s(%s)' def value(self): return self.op % (self.base.value(), self.type, ', '.join( [str(param.value()) for param in self.params])) def get_type(self): return self.type def __str__(self): return 'InvokeDirectRange (%s) %s (%s; %s)' % (self.returnType, self.methCalled, str(self.paramsType), str(self.params)) # invoke-static/range {vCCCC..vNNNN} ( 16b each ) class InvokeStaticRange(InvokeInstruction): def __init__(self, ins): super(InvokeStaticRange, self).__init__(ins) Util.log('InvokeStaticRange : %s' % self.ops, 'debug') if len(self.ops) > 1: self.params = [int(i[1]) for i in self.ops[0:-1]] else: self.params = [] Util.log('Parameters = %s' % self.params, 'debug') def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.params = get_invoke_params(self.params, self.paramsType, memory) self.op = '%s.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): return self.op % (self.type, self.methCalled, ', '.join([ str(param.value()) for param in self.params])) def get_reg(self): Util.log('InvokeStaticRange has no dest register.', 'debug') def __str__(self): return 'InvokeStaticRange (%s) %s (%s ; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # invoke-interface/range {vCCCC..vNNNN} ( 16b each ) class InvokeInterfaceRange(InvokeInstruction): def __init__(self, ins): super(InvokeInterfaceRange, self).__init__(ins) Util.log('InvokeInterfaceRange : %s' % self.ops, 'debug') self.params = [int(i[1]) for i in self.ops[1:-1]] Util.log('Parameters = %s' % self.params, 'debug') self.type = self.ops[-1][2] self.paramsType = Util.get_params_type(self.ops[-1][3]) self.returnType = self.ops[-1][4] self.methCalled = self.ops[-1][-1] def symbolic_process(self, memory, tabsymb, varsgen): memory['heap'] = True self.base = memory[self.register] self.params = get_invoke_params(self.params, self.paramsType, memory) if self.base.value() == 'this': self.op = '%s(%s)' else: self.op = '%s.%s(%s)' Util.log('Ins :: %s' % self.op, 'debug') def value(self): if self.base.value() == 'this': return self.op % (self.methCalled, ', '.join( [str(param.value()) for param in self.params])) return self.op % (self.base.value(), self.methCalled, ', '.join( [str(param.value()) for param in self.params])) def get_type(self): return self.returnType def get_reg(self): Util.log('InvokeInterfaceRange has no dest register.', 'debug') def __str__(self): return 'InvokeInterfaceRange (%s) %s (%s; %s)' % (self.returnType, self.methCalled, self.paramsType, str(self.params)) # neg-int vA, vB ( 4b, 4b ) class NegInt(UnaryExpression): def __init__(self, ins): super(NegInt, self).__init__(ins) Util.log('NegInt : %s' % self.ops, 'debug') self.op = '-' self.type = 'I' def __str__(self): return 'NegInt (%s)' % self.source # not-int vA, vB ( 4b, 4b ) class NotInt(UnaryExpression): def __init__(self, ins): super(NotInt, self).__init__(ins) Util.log('NotInt : %s' % self.ops, 'debug') self.op = '~' self.type = 'I' def __str__(self): return 'NotInt (%s)' % self.source # neg-long vA, vB ( 4b, 4b ) class NegLong(UnaryExpression): def __init__(self, ins): super(NegLong, self).__init__(ins) Util.log('NegLong : %s' % self.ops, 'debug') self.op = '-' self.type = 'J' def __str__(self): return 'NegLong (%s)' % self.source # not-long vA, vB ( 4b, 4b ) class NotLong(UnaryExpression): def __init__(self, ins): super(NotLong, self).__init__(ins) Util.log('NotLong : %s' % self.ops, 'debug') self.op = '~' self.type = 'J' def __str__(self): return 'NotLong (%s)' % self.source # neg-float vA, vB ( 4b, 4b ) class NegFloat(UnaryExpression): def __init__(self, ins): super(NegFloat, self).__init__(ins) Util.log('NegFloat : %s' % self.ops, 'debug') self.op = '-' self.type = 'F' def __str__(self): return 'NegFloat (%s)' % self.source # neg-double vA, vB ( 4b, 4b ) class NegDouble(UnaryExpression): def __init__(self, ins): super(NegDouble, self).__init__(ins) Util.log('NegDouble : %s' % self.ops, 'debug') self.op = '-' self.type = 'D' def __str__(self): return 'NegDouble (%s)' % self.source # int-to-long vA, vB ( 4b, 4b ) class IntToLong(UnaryExpression): def __init__(self, ins): super(IntToLong, self).__init__(ins) Util.log('IntToLong : %s' % self.ops, 'debug') self.op = '(long)' self.type = 'J' def __str__(self): return 'IntToLong (%s)' % self.source # int-to-float vA, vB ( 4b, 4b ) class IntToFloat(UnaryExpression): def __init__(self, ins): super(IntToFloat, self).__init__(ins) Util.log('IntToFloat : %s' % self.ops, 'debug') self.op = '(float)' self.type = 'F' def __str__(self): return 'IntToFloat (%s)' % self.source # int-to-double vA, vB ( 4b, 4b ) class IntToDouble(UnaryExpression): def __init__(self, ins): super(IntToDouble, self).__init__(ins) Util.log('IntToDouble : %s' % self.ops, 'debug') self.op = '(double)' self.type = 'D' def __str__(self): return 'IntToDouble (%s)' % self.source # long-to-int vA, vB ( 4b, 4b ) class LongToInt(UnaryExpression): def __init__(self, ins): super(LongToInt, self).__init__(ins) Util.log('LongToInt : %s' % self.ops, 'debug') self.op = '(int)' self.type = 'I' def __str__(self): return 'LongToInt (%s)' % self.source # long-to-float vA, vB ( 4b, 4b ) class LongToFloat(UnaryExpression): def __init__(self, ins): super(LongToFloat, self).__init__(ins) Util.log('LongToFloat : %s' % self.ops, 'debug') self.op = '(float)' self.type = 'F' def __str__(self): return 'LongToFloat (%s)' % self.source # long-to-double vA, vB ( 4b, 4b ) class LongToDouble(UnaryExpression): def __init__(self, ins): super(LongToDouble, self).__init__(ins) Util.log('LongToDouble : %s' % self.ops, 'debug') self.op = '(double)' self.type = 'D' def __str__(self): return 'LongToDouble (%s)' % self.source # float-to-int vA, vB ( 4b, 4b ) class FloatToInt(UnaryExpression): def __init__(self, ins): super(FloatToInt, self).__init__(ins) Util.log('FloatToInt : %s' % self.ops, 'debug') self.op = '(int)' self.type = 'I' def __str__(self): return 'FloatToInt (%s)' % self.source # float-to-long vA, vB ( 4b, 4b ) class FloatToLong(UnaryExpression): def __init__(self, ins): super(FloatToLong, self).__init__(ins) Util.log('FloatToLong : %s' % self.ops, 'debug') self.op = '(long)' self.type = 'J' def __str__(self): return 'FloatToLong (%s)' % self.source # float-to-double vA, vB ( 4b, 4b ) class FloatToDouble(UnaryExpression): def __init__(self, ins): super(FloatToDouble, self).__init__(ins) Util.log('FloatToDouble : %s' % self.ops, 'debug') self.op = '(double)' self.type = 'D' def __str__(self): return 'FloatToDouble (%s)' % self.source # double-to-int vA, vB ( 4b, 4b ) class DoubleToInt(UnaryExpression): def __init__(self, ins): super(DoubleToInt, self).__init__(ins) Util.log('DoubleToInt : %s' % self.ops, 'debug') self.op = '(int)' self.type = 'I' def __str__(self): return 'DoubleToInt (%s)' % self.source # double-to-long vA, vB ( 4b, 4b ) class DoubleToLong(UnaryExpression): def __init__(self, ins): super(DoubleToLong, self).__init__(ins) Util.log('DoubleToLong : %s' % self.ops, 'debug') self.op = '(long)' self.type = 'J' def __str__(self): return 'DoubleToLong (%s)' % self.source # double-to-float vA, vB ( 4b, 4b ) class DoubleToFloat(UnaryExpression): def __init__(self, ins): super(DoubleToFloat, self).__init__(ins) Util.log('DoubleToFloat : %s' % self.ops, 'debug') self.op = '(float)' self.type = 'F' def __str__(self): return 'DoubleToFloat (%s)' % self.source # int-to-byte vA, vB ( 4b, 4b ) class IntToByte(UnaryExpression): def __init__(self, ins): super(IntToByte, self).__init__(ins) Util.log('IntToByte : %s' % self.ops, 'debug') self.op = '(byte)' self.type = 'B' def __str__(self): return 'IntToByte (%s)' % self.source # int-to-char vA, vB ( 4b, 4b ) class IntToChar(UnaryExpression): def __init__(self, ins): super(IntToChar, self).__init__(ins) Util.log('IntToChar : %s' % self.ops, 'debug') self.op = '(char)' self.type = 'C' def __str__(self): return 'IntToChar (%s)' % self.source # int-to-short vA, vB ( 4b, 4b ) class IntToShort(UnaryExpression): def __init__(self, ins): super(IntToShort, self).__init__(ins) Util.log('IntToShort : %s' % self.ops, 'debug') self.op = '(short)' self.type = 'S' def __str__(self): return 'IntToShort (%s)' % self.source # add-int vAA, vBB, vCC ( 8b, 8b, 8b ) class AddInt(BinaryExpression): def __init__(self, ins): super(AddInt, self).__init__(ins) Util.log('AddInt : %s' % self.ops, 'debug') self.op = '+' self.type = 'I' def __str__(self): return 'AddInt (%s, %s)' % (self.lhs, self.rhs) # sub-int vAA, vBB, vCC ( 8b, 8b, 8b ) class SubInt(BinaryExpression): def __init__(self, ins): super(SubInt, self).__init__(ins) Util.log('SubInt : %s' % self.ops, 'debug') self.op = '-' self.type = 'I' def __str__(self): return 'AddInt (%s, %s)' % (self.lhs, self.rhs) # mul-int vAA, vBB, vCC ( 8b, 8b, 8b ) class MulInt(BinaryExpression): def __init__(self, ins): super(MulInt, self).__init__(ins) Util.log('MulInt : %s' % self.ops, 'debug') self.op = '*' self.type = 'I' def __str__(self): return 'MulInt (%s, %s)' % (self.lhs, self.rhs) # div-int vAA, vBB, vCC ( 8b, 8b, 8b ) class DivInt(BinaryExpression): def __init__(self, ins): super(DivInt, self).__init__(ins) Util.log('DivInt : %s' % self.ops, 'debug') self.op = '/' self.type = 'I' def __str__(self): return 'DivInt (%s, %s)' % (self.lhs, self.rhs) # rem-int vAA, vBB, vCC ( 8b, 8b, 8b ) class RemInt(BinaryExpression): def __init__(self, ins): super(RemInt, self).__init__(ins) Util.log('RemInt : %s' % self.ops, 'debug') self.op = '%%' self.type = 'I' def __str__(self): return 'RemInt (%s, %s)' % (self.lhs, self.rhs) # and-int vAA, vBB, vCC ( 8b, 8b, 8b ) class AndInt(BinaryExpression): def __init__(self, ins): super(AndInt, self).__init__(ins) Util.log('AndInt : %s' % self.ops, 'debug') self.op = '&' self.type = 'I' def __str__(self): return 'AndInt (%s, %s)' % (self.lhs, self.rhs) # or-int vAA, vBB, vCC ( 8b, 8b, 8b ) class OrInt(BinaryExpression): def __init__(self, ins): super(OrInt, self).__init__(ins) Util.log('OrInt : %s' % self.ops, 'debug') self.op = '|' self.type = 'I' def __str__(self): return 'OrInt (%s, %s)' % (self.lhs, self.rhs) # xor-int vAA, vBB, vCC ( 8b, 8b, 8b ) class XorInt(BinaryExpression): def __init__(self, ins): super(XorInt, self).__init__(ins) Util.log('XorInt : %s' % self.ops, 'debug') self.op = '^' self.type = 'I' def __str__(self): return 'XorInt (%s, %s)' % (self.lhs, self.rhs) # shl-int vAA, vBB, vCC ( 8b, 8b, 8b ) class ShlInt(BinaryExpression): def __init__(self, ins): super(ShlInt, self).__init__(ins) Util.log('ShlInt : %s' % self.ops, 'debug') self.op = '(%s << ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShlInt (%s, %s)' % (self.lhs, self.rhs) # shr-int vAA, vBB, vCC ( 8b, 8b, 8b ) class ShrInt(BinaryExpression): def __init__(self, ins): super(ShrInt, self).__init__(ins) Util.log('ShrInt : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShrInt (%s, %s)' % (self.lhs, self.rhs) # ushr-int vAA, vBB, vCC ( 8b, 8b, 8b ) class UShrInt(BinaryExpression): def __init__(self, ins): super(UShrInt, self).__init__(ins) Util.log('UShrInt : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'UShrInt (%s, %s)' % (self.lhs, self.rhs) # add-long vAA, vBB, vCC ( 8b, 8b, 8b ) class AddLong(BinaryExpression): def __init__(self, ins): super(AddLong, self).__init__(ins) Util.log('AddLong : %s' % self.ops, 'debug') self.op = '+' self.type = 'J' def __str__(self): return 'AddLong (%s, %s)' % (self.lhs, self.rhs) # sub-long vAA, vBB, vCC ( 8b, 8b, 8b ) class SubLong(BinaryExpression): def __init__(self, ins): super(SubLong, self).__init__(ins) Util.log('SubLong : %s' % self.ops, 'debug') self.op = '-' self.type = 'J' def __str__(self): return 'SubLong (%s, %s)' % (self.lhs, self.rhs) # mul-long vAA, vBB, vCC ( 8b, 8b, 8b ) class MulLong(BinaryExpression): def __init__(self, ins): super(MulLong, self).__init__(ins) Util.log('MulLong : %s' % self.ops, 'debug') self.op = '*' self.type = 'J' def __str__(self): return 'MulLong (%s, %s)' % (self.lhs, self.rhs) # div-long vAA, vBB, vCC ( 8b, 8b, 8b ) class DivLong(BinaryExpression): def __init__(self, ins): super(DivLong, self).__init__(ins) Util.log('DivLong : %s' % self.ops, 'debug') self.op = '/' self.type = 'J' def __str__(self): return 'DivLong (%s, %s)' % (self.lhs, self.rhs) # rem-long vAA, vBB, vCC ( 8b, 8b, 8b ) class RemLong(BinaryExpression): def __init__(self, ins): super(RemLong, self).__init__(ins) Util.log('RemLong : %s' % self.ops, 'debug') self.op = '%%' self.type = 'J' def __str__(self): return 'RemLong (%s, %s)' % (self.lhs, self.rhs) # and-long vAA, vBB, vCC ( 8b, 8b, 8b ) class AndLong(BinaryExpression): def __init__(self, ins): super(AndLong, self).__init__(ins) Util.log('AndLong : %s' % self.ops, 'debug') self.op = '&' self.type = 'J' def __str__(self): return 'AndLong (%s, %s)' % (self.lhs, self.rhs) # or-long vAA, vBB, vCC ( 8b, 8b, 8b ) class OrLong(BinaryExpression): def __init__(self, ins): super(OrLong, self).__init__(ins) Util.log('OrLong : %s' % self.ops, 'debug') self.op = '|' self.type = 'J' def __str__(self): return 'OrLong (%s, %s)' % (self.lhs, self.rhs) # xor-long vAA, vBB, vCC ( 8b, 8b, 8b ) class XorLong(BinaryExpression): def __init__(self, ins): super(XorLong, self).__init__(ins) Util.log('XorLong : %s' % self.ops, 'debug') self.op = '^' self.type = 'J' def __str__(self): return 'XorLong (%s, %s)' % (self.lhs, self.rhs) # shl-long vAA, vBB, vCC ( 8b, 8b, 8b ) class ShlLong(BinaryExpression): def __init__(self, ins): super(ShlLong, self).__init__(ins) Util.log('ShlLong : %s' % self.ops, 'debug') self.op = '(%s << ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShlLong (%s, %s)' % (self.lhs, self.rhs) # shr-long vAA, vBB, vCC ( 8b, 8b, 8b ) class ShrLong(BinaryExpression): def __init__(self, ins): super(ShrLong, self).__init__(ins) Util.log('ShrLong : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShrLong (%s, %s)' % (self.lhs, self.rhs) # ushr-long vAA, vBB, vCC ( 8b, 8b, 8b ) class UShrLong(BinaryExpression): def __init__(self, ins): super(UShrLong, self).__init__(ins) Util.log('UShrLong : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'UShrLong (%s, %s)' % (self.lhs, self.rhs) # add-float vAA, vBB, vCC ( 8b, 8b, 8b ) class AddFloat(BinaryExpression): def __init__(self, ins): super(AddFloat, self).__init__(ins) Util.log('AddFloat : %s' % self.ops, 'debug') self.op = '+' self.type = 'F' def __str__(self): return 'AddFloat (%s, %s)' % (self.lhs, self.rhs) # sub-float vAA, vBB, vCC ( 8b, 8b, 8b ) class SubFloat(BinaryExpression): def __init__(self, ins): super(SubFloat, self).__init__(ins) Util.log('SubFloat : %s' % self.ops, 'debug') self.op = '-' self.type = 'F' def __str__(self): return 'SubFloat (%s, %s)' % (self.lhs, self.rhs) # mul-float vAA, vBB, vCC ( 8b, 8b, 8b ) class MulFloat(BinaryExpression): def __init__(self, ins): super(MulFloat, self).__init__(ins) Util.log('MulFloat : %s' % self.ops, 'debug') self.op = '*' self.type = 'F' def __str__(self): return 'MulFloat (%s, %s)' % (self.lhs, self.rhs) # div-float vAA, vBB, vCC ( 8b, 8b, 8b ) class DivFloat(BinaryExpression): def __init__(self, ins): super(DivFloat, self).__init__(ins) Util.log('DivFloat : %s' % self.ops, 'debug') self.op = '/' self.type = 'F' def __str__(self): return 'DivFloat (%s, %s)' % (self.lhs, self.rhs) # rem-float vAA, vBB, vCC ( 8b, 8b, 8b ) class RemFloat(BinaryExpression): def __init__(self, ins): super(RemFloat, self).__init__(ins) Util.log('RemFloat : %s' % self.ops, 'debug') self.op = '%%' self.type = 'F' def __str__(self): return 'RemFloat (%s, %s)' % (self.lhs, self.rhs) # add-double vAA, vBB, vCC ( 8b, 8b, 8b ) class AddDouble(BinaryExpression): def __init__(self, ins): super(AddDouble, self).__init__(ins) Util.log('AddDouble : %s' % self.ops, 'debug') self.op = '+' self.type = 'D' def __str__(self): return 'AddDouble (%s, %s)' % (self.lhs, self.rhs) # sub-double vAA, vBB, vCC ( 8b, 8b, 8b ) class SubDouble(BinaryExpression): def __init__(self, ins): super(SubDouble, self).__init__(ins) Util.log('SubDouble : %s' % self.ops, 'debug') self.op = '-' self.type = 'D' def __str__(self): return 'SubDouble (%s, %s)' % (self.lhs, self.rhs) # mul-double vAA, vBB, vCC ( 8b, 8b, 8b ) class MulDouble(BinaryExpression): def __init__(self, ins): super(MulDouble, self).__init__(ins) Util.log('MulDouble : %s' % self.ops, 'debug') self.op = '*' self.type = 'D' def __str__(self): return 'MulDouble (%s, %s)' % (self.lhs, self.rhs) # div-double vAA, vBB, vCC ( 8b, 8b, 8b ) class DivDouble(BinaryExpression): def __init__(self, ins): super(DivDouble, self).__init__(ins) Util.log('DivDouble : %s' % self.ops, 'debug') self.op = '/' self.type = 'D' def __str__(self): return 'DivDouble (%s, %s)' % (self.lhs, self.rhs) # rem-double vAA, vBB, vCC ( 8b, 8b, 8b ) class RemDouble(BinaryExpression): def __init__(self, ins): super(RemDouble, self).__init__(ins) Util.log('RemDouble : %s' % self.ops, 'debug') self.op = '%%' self.type = 'D' def __str__(self): return 'DivDouble (%s, %s)' % (self.lhs, self.rhs) # add-int/2addr vA, vB ( 4b, 4b ) class AddInt2Addr(BinaryExpression): def __init__(self, ins): super(AddInt2Addr, self).__init__(ins) Util.log('AddInt2Addr : %s' % self.ops, 'debug') self.op = '+' self.type = 'I' def __str__(self): return 'AddInt2Addr (%s, %s)' % (self.lhs, self.rhs) # sub-int/2addr vA, vB ( 4b, 4b ) class SubInt2Addr(BinaryExpression): def __init__(self, ins): super(SubInt2Addr, self).__init__(ins) Util.log('SubInt2Addr : %s' % self.ops, 'debug') self.op = '-' self.type = 'I' def __str__(self): return 'SubInt2Addr (%s, %s)' % (self.lhs, self.rhs) # mul-int/2addr vA, vB ( 4b, 4b ) class MulInt2Addr(BinaryExpression): def __init__(self, ins): super(MulInt2Addr, self).__init__(ins) Util.log('MulInt2Addr : %s' % self.ops, 'debug') self.op = '*' self.type = 'I' def __str__(self): return 'MulInt2Addr (%s, %s)' % (self.lhs, self.rhs) # div-int/2addr vA, vB ( 4b, 4b ) class DivInt2Addr(BinaryExpression): def __init__(self, ins): super(DivInt2Addr, self).__init__(ins) Util.log('DivInt2Addr : %s' % self.ops, 'debug') self.op = '/' self.type = 'I' def __str__(self): return 'DivInt2Addr (%s, %s)' % (self.lhs, self.rhs) # rem-int/2addr vA, vB ( 4b, 4b ) class RemInt2Addr(BinaryExpression): def __init__(self, ins): super(RemInt2Addr, self).__init__(ins) Util.log('RemInt2Addr : %s' % self.ops, 'debug') self.op = '%%' self.type = 'I' def __str__(self): return 'RemInt2Addr (%s, %s)' % (self.lhs, self.rhs) # and-int/2addr vA, vB ( 4b, 4b ) class AndInt2Addr(BinaryExpression): def __init__(self, ins): super(AndInt2Addr, self).__init__(ins) Util.log('AndInt2Addr : %s' % self.ops, 'debug') self.op = '&' self.type = 'I' def __str__(self): return 'AndInt2Addr (%s, %s)' % (self.lhs, self.rhs) # or-int/2addr vA, vB ( 4b, 4b ) class OrInt2Addr(BinaryExpression): def __init__(self, ins): super(OrInt2Addr, self).__init__(ins) Util.log('OrInt2Addr : %s' % self.ops, 'debug') self.op = '|' self.type = 'I' def __str__(self): return 'OrInt2Addr (%s, %s)' % (self.lhs, self.rhs) # xor-int/2addr vA, vB ( 4b, 4b ) class XorInt2Addr(BinaryExpression): def __init__(self, ins): super(XorInt2Addr, self).__init__(ins) Util.log('XorInt2Addr : %s' % self.ops, 'debug') self.op = '^' self.type = 'I' def __str__(self): return 'XorInt2Addr (%s, %s)' % (self.lhs, self.rhs) # shl-int/2addr vA, vB ( 4b, 4b ) class ShlInt2Addr(BinaryExpression): def __init__(self, ins): super(ShlInt2Addr, self).__init__(ins) Util.log('ShlInt2Addr : %s' % self.ops, 'debug') self.op = '(%s << ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShlInt2Addr (%s, %s)' % (self.lhs, self.rhs) # shr-int/2addr vA, vB ( 4b, 4b ) class ShrInt2Addr(BinaryExpression): def __init__(self, ins): super(ShrInt2Addr, self).__init__(ins) Util.log('ShrInt2Addr : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'ShrInt2Addr (%s, %s)' % (self.lhs, self.rhs) # ushr-int/2addr vA, vB ( 4b, 4b ) class UShrInt2Addr(BinaryExpression): def __init__(self, ins): super(UShrInt2Addr, self).__init__(ins) Util.log('UShrInt2Addr : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.lhs.value(), self.rhs.value()) def __str__(self): return 'UShrInt2Addr (%s, %s)' % (self.lhs, self.rhs) # add-long/2addr vA, vB ( 4b, 4b ) class AddLong2Addr(BinaryExpression): def __init__(self, ins): super(AddLong2Addr, self).__init__(ins) Util.log('AddLong2Addr : %s' % self.ops, 'debug') self.op = '+' self.type = 'J' def __str__(self): return 'AddLong2Addr (%s, %s)' % (self.lhs, self.rhs) # sub-long/2addr vA, vB ( 4b, 4b ) class SubLong2Addr(BinaryExpression): def __init__(self, ins): super(SubLong2Addr, self).__init__(ins) Util.log('SubLong2Addr : %s' % self.ops, 'debug') self.op = '-' self.type = 'J' def __str__(self): return 'SubLong2Addr (%s, %s)' % (self.lhs, self.rhs) # mul-long/2addr vA, vB ( 4b, 4b ) class MulLong2Addr(BinaryExpression): def __init__(self, ins): super(MulLong2Addr, self).__init__(ins) Util.log('MulLong2Addr : %s' % self.ops, 'debug') self.op = '*' self.type = 'J' def __str__(self): return 'MulLong2Addr (%s, %s)' % (self.lhs, self.rhs) # div-long/2addr vA, vB ( 4b, 4b ) class DivLong2Addr(BinaryExpression): def __init__(self, ins): super(DivLong2Addr, self).__init__(ins) Util.log('DivLong2Addr : %s' % self.ops, 'debug') self.op = '/' self.type = 'J' def __str__(self): return 'DivLong2Addr (%s, %s)' % (self.lhs, self.rhs) # rem-long/2addr vA, vB ( 4b, 4b ) class RemLong2Addr(BinaryExpression): def __init__(self, ins): super(RemLong2Addr, self).__init__(ins) Util.log('RemLong2Addr : %s' % self.ops, 'debug') self.op = '%%' self.type = 'J' def __str__(self): return 'RemLong2Addr (%s, %s)' % (self.lhs, self.rhs) # and-long/2addr vA, vB ( 4b, 4b ) class AndLong2Addr(BinaryExpression): def __init__(self, ins): super(AndLong2Addr, self).__init__(ins) Util.log('AddLong2Addr : %s' % self.ops, 'debug') self.op = '&' self.type = 'J' def __str__(self): return 'AndLong2Addr (%s, %s)' % (self.lhs, self.rhs) # or-long/2addr vA, vB ( 4b, 4b ) class OrLong2Addr(BinaryExpression): def __init__(self, ins): super(OrLong2Addr, self).__init__(ins) Util.log('OrLong2Addr : %s' % self.ops, 'debug') self.op = '|' self.type = 'J' def __str__(self): return 'OrLong2Addr (%s, %s)' % (self.lhs, self.rhs) # xor-long/2addr vA, vB ( 4b, 4b ) class XorLong2Addr(BinaryExpression): def __init__(self, ins): super(XorLong2Addr, self).__init__(ins) Util.log('XorLong2Addr : %s' % self.ops, 'debug') self.op = '^' self.type = 'J' def __str__(self): return 'XorLong2Addr (%s, %s)' % (self.lhs, self.rhs) # shl-long/2addr vA, vB ( 4b, 4b ) class ShlLong2Addr(BinaryExpression): def __init__(self, ins): super(ShlLong2Addr, self).__init__(ins) Util.log('ShlLong2Addr : %s' % self.ops, 'debug') self.op = '(%s << ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.rhs.value(), self.lhs.value()) def __str__(self): return 'ShlLong2Addr (%s, %s)' % (self.lhs, self.rhs) # shr-long/2addr vA, vB ( 4b, 4b ) class ShrLong2Addr(BinaryExpression): def __init__(self, ins): super(ShrLong2Addr, self).__init__(ins) Util.log('ShrLong2Addr : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.rhs.value(), self.lhs.value()) def __str__(self): return 'ShrLong2Addr (%s, %s)' % (self.lhs, self.rhs) # ushr-long/2addr vA, vB ( 4b, 4b ) class UShrLong2Addr(BinaryExpression): def __init__(self, ins): super(UShrLong2Addr, self).__init__(ins) Util.log('UShrLong2Addr : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'J' def value(self): return self.op % (self.rhs.value(), self.lhs.value()) def __str__(self): return 'UShrLong2Addr (%s, %s)' % (self.lhs, self.rhs) # add-float/2addr vA, vB ( 4b, 4b ) class AddFloat2Addr(BinaryExpression): def __init__(self, ins): super(AddFloat2Addr, self).__init__(ins) Util.log('AddFloat2Addr : %s' % self.ops, 'debug') self.op = '+' self.type = 'F' def __str__(self): return 'AddFloat2Addr (%s, %s)' % (self.lhs, self.rhs) # sub-float/2addr vA, vB ( 4b, 4b ) class SubFloat2Addr(BinaryExpression): def __init__(self, ins): super(SubFloat2Addr, self).__init__(ins) Util.log('SubFloat2Addr : %s' % self.ops, 'debug') self.op = '-' self.type = 'F' def __str__(self): return 'SubFloat2Addr (%s, %s)' % (self.lhs, self.rhs) # mul-float/2addr vA, vB ( 4b, 4b ) class MulFloat2Addr(BinaryExpression): def __init__(self, ins): super(MulFloat2Addr, self).__init__(ins) Util.log('MulFloat2Addr : %s' % self.ops, 'debug') self.op = '*' self.type = 'F' def __str__(self): return 'MulFloat2Addr (%s, %s)' % (self.lhs, self.rhs) # div-float/2addr vA, vB ( 4b, 4b ) class DivFloat2Addr(BinaryExpression): def __init__(self, ins): super(DivFloat2Addr, self).__init__(ins) Util.log('DivFloat2Addr : %s' % self.ops, 'debug') self.op = '/' self.type = 'F' def __str__(self): return 'DivFloat2Addr (%s, %s)' % (self.lhs, self.rhs) # rem-float/2addr vA, vB ( 4b, 4b ) class RemFloat2Addr(BinaryExpression): def __init__(self, ins): super(RemFloat2Addr, self).__init__(ins) Util.log('RemFloat2Addr : %s' % self.ops, 'debug') self.op = '%%' self.type = 'F' def __str__(self): return 'RemFloat2Addr (%s, %s)' % (self.lhs, self.rhs) # add-double/2addr vA, vB ( 4b, 4b ) class AddDouble2Addr(BinaryExpression): def __init__(self, ins): super(AddDouble2Addr, self).__init__(ins) Util.log('AddDouble2Addr : %s' % self.ops, 'debug') self.op = '+' self.type = 'D' def __str__(self): return 'AddDouble2Addr (%s, %s)' % (self.lhs, self.rhs) # sub-double/2addr vA, vB ( 4b, 4b ) class SubDouble2Addr(BinaryExpression): def __init__(self, ins): super(SubDouble2Addr, self).__init__(ins) Util.log('subDouble2Addr : %s' % self.ops, 'debug') self.op = '-' self.type = 'D' def __str__(self): return 'SubDouble2Addr (%s, %s)' % (self.lhs, self.rhs) # mul-double/2addr vA, vB ( 4b, 4b ) class MulDouble2Addr(BinaryExpression): def __init__(self, ins): super(MulDouble2Addr, self).__init__(ins) Util.log('MulDouble2Addr : %s' % self.ops, 'debug') self.op = '*' self.type = 'D' def __str__(self): return 'MulDouble2Addr (%s, %s)' % (self.lhs, self.rhs) # div-double/2addr vA, vB ( 4b, 4b ) class DivDouble2Addr(BinaryExpression): def __init__(self, ins): super(DivDouble2Addr, self).__init__(ins) Util.log('DivDouble2Addr : %s' % self.ops, 'debug') self.op = '/' self.type = 'D' def __str__(self): return 'DivDouble2Addr (%s, %s)' % (self.lhs, self.rhs) # rem-double/2addr vA, vB ( 4b, 4b ) class RemDouble2Addr(BinaryExpression): def __init__(self, ins): super(RemDouble2Addr, self).__init__(ins) Util.log('RemDouble2Addr : %s' % self.ops, 'debug') self.op = '%%' self.type = 'D' def __str__(self): return 'RemDouble2Addr (%s, %s)' % (self.lhs, self.rhs) # add-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class AddIntLit16(BinaryExpressionLit): def __init__(self, ins): super(AddIntLit16, self).__init__(ins) Util.log('AddIntLit16 : %s' % self.ops, 'debug') self.op = '+' self.type = 'I' def __str__(self): return 'AddIntLit16 (%s, %s)' % (self.lhs, self.rhs) # rsub-int vA, vB, #+CCCC ( 4b, 4b, 16b ) class RSubInt(BinaryExpressionLit): pass #TODO inverse lhs & rhs # mul-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class MulIntLit16(BinaryExpressionLit): def __init__(self, ins): super(MulIntLit16, self).__init__(ins) Util.log('MulIntLit16 : %s' % self.ops, 'debug') self.op = '*' self.type = 'I' def __str__(self): return 'MulIntLit16 (%s, %s)' % (self.lhs, self.rhs) # div-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class DivIntLit16(BinaryExpressionLit): def __init__(self, ins): super(DivIntLit16, self).__init__(ins) Util.log('DivIntLit16 : %s' % self.ops, 'debug') self.op = '/' self.type = 'I' def __str__(self): return 'DivIntLit16 (%s, %s)' % (self.lhs, self.rhs) # rem-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class RemIntLit16(BinaryExpressionLit): def __init__(self, ins): super(RemIntLit16, self).__init__(ins) Util.log('RemIntLit16 : %s' % self.ops, 'debug') self.op = '%%' self.type = 'I' def __str__(self): return 'RemIntLit16 (%s, %s)' % (self.lhs, self.rhs) # and-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class AndIntLit16(BinaryExpressionLit): def __init__(self, ins): super(AndIntLit16, self).__init__(ins) Util.log('AndIntLit16 : %s' % self.ops, 'debug') self.op = 'a' self.type = 'I' def __str__(self): return 'AndIntLit16 (%s, %s)' % (self.lhs, self.rhs) # or-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class OrIntLit16(BinaryExpressionLit): def __init__(self, ins): super(OrIntLit16, self).__init__(ins) Util.log('OrIntLit16 : %s' % self.ops, 'debug') self.op = '|' self.type = 'I' def __str__(self): return 'OrIntLit16 (%s, %s)' % (self.lhs, self.rhs) # xor-int/lit16 vA, vB, #+CCCC ( 4b, 4b, 16b ) class XorIntLit16(BinaryExpressionLit): def __init__(self, ins): super(XorIntLit16, self).__init__(ins) Util.log('XorIntLit16 : %s' % self.ops, 'debug') self.op = '^' self.type = 'I' def __str__(self): return 'XorIntLit16 (%s, %s)' % (self.lhs, self.rhs) # add-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class AddIntLit8(BinaryExpressionLit): def __init__(self, ins): super(AddIntLit8, self).__init__(ins) Util.log('AddIntLit8 : %s' % self.ops, 'debug') self.op = '+' self.type = 'I' def __str__(self): return 'AddIntLit8 (%s, %s)' % (self.lhs, self.rhs) # rsub-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class RSubIntLit8(BinaryExpressionLit): def __init__(self, ins): super(RSubIntLit8, self).__init__(ins) Util.log('RSubIntLit8 : %s' % self.ops, 'debug') self.op = '-' self.type = 'I' def __str__(self): return 'AddIntLit8 (%s, %s)' % (self.lhs, self.rhs) # mul-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class MulIntLit8(BinaryExpressionLit): def __init__(self, ins): super(MulIntLit8, self).__init__(ins) Util.log('MulIntLit8 : %s' % self.ops, 'debug') self.op = '*' self.type = 'I' def __str__(self): return 'MulIntLit8 (%s, %s)' % (self.lhs, self.rhs) # div-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class DivIntLit8(BinaryExpressionLit): def __init__(self, ins): super(DivIntLit8, self).__init__(ins) Util.log('DivIntLit8 : %s' % self.ops, 'debug') self.op = '/' self.type = 'I' def __str__(self): return 'DivIntLit8 (%s, %s)' % (self.lhs, self.rhs) # rem-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class RemIntLit8(BinaryExpressionLit): def __init__(self, ins): super(RemIntLit8, self).__init__(ins) Util.log('RemIntLit8 : %s' % self.ops, 'debug') self.op = '%%' self.type = 'I' def __str__(self): return 'RemIntLit8 (%s, %s)' % (self.lhs, self.rhs) # and-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class AndIntLit8(BinaryExpressionLit): def __init__(self, ins): super(AddIntLit8, self).__init__(ins) Util.log('AddIntLit8 : %s' % self.ops, 'debug') self.op = '+' self.type = 'I' def __str__(self): return 'AddIntLit8 (%s, %s)' % (self.lhs, self.rhs) # or-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class OrIntLit8(BinaryExpressionLit): def __init__(self, ins): super(OrIntLit8, self).__init__(ins) Util.log('OrIntLit8 : %s' % self.ops, 'debug') self.op = '|' self.type = 'I' def __str__(self): return 'OrIntLit8 (%s, %s)' % (self.lhs, self.rhs) # xor-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class XorIntLit8(BinaryExpressionLit): def __init__(self, ins): super(XorIntLit8, self).__init__(ins) Util.log('XorIntLit8 : %s' % self.ops, 'debug') self.op = '^' self.type = 'I' def __str__(self): return 'XorIntLit8 (%s, %s)' % (self.lhs, self.rhs) # shl-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class ShlIntLit8(BinaryExpressionLit): def __init__(self, ins): super(ShlIntLit8, self).__init__(ins) Util.log('ShlIntLit8 : %s' % self.ops, 'debug') self.op = '(%s << ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.rhs.value(), self.lhs) def __str__(self): return 'ShlIntLit8 (%s, %s)' % (self.lhs, self.rhs) # shr-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class ShrIntLit8(BinaryExpressionLit): def __init__(self, ins): super(ShrIntLit8, self).__init__(ins) Util.log('ShrIntLit8 : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.rhs.value(), self.lhs) def __str__(self): return 'ShrIntLit8 (%s, %s)' % (self.lhs, self.rhs) # ushr-int/lit8 vAA, vBB, #+CC ( 8b, 8b, 8b ) class UShrIntLit8(BinaryExpressionLit): def __init__(self, ins): super(UShrIntLit8, self).__init__(ins) Util.log('UShrIntLit8 : %s' % self.ops, 'debug') self.op = '(%s >> ( %s & 0x1f ))' self.type = 'I' def value(self): return self.op % (self.rhs.value(), self.lhs) def __str__(self): return 'UShrIntLit8 (%s, %s)' % (self.lhs, self.rhs) INSTRUCTION_SET = { 'nop' : (EXPR, Nop), 'move' : (INST, Move), 'move/from16' : (INST, MoveFrom16), 'move/16' : (INST, Move16), 'move-wide' : (INST, MoveWide), 'move-wide/from16' : (INST, MoveWideFrom16), 'move-wide/16' : (INST, MoveWide16), 'move-object' : (INST, MoveObject), 'move-object/from16' : (INST, MoveObjectFrom16), 'move-object/16' : (INST, MoveObject16), 'move-result' : (INST, MoveResult), 'move-result-wide' : (INST, MoveResultWide), 'move-result-object' : (INST, MoveResultObject), 'move-exception' : (EXPR, MoveException), 'return-void' : (INST, ReturnVoid), 'return' : (INST, Return), 'return-wide' : (INST, ReturnWide), 'return-object' : (INST, ReturnObject), 'const/4' : (EXPR, Const4), 'const/16' : (EXPR, Const16), 'const' : (EXPR, Const), 'const/high16' : (EXPR, ConstHigh16), 'const-wide/16' : (EXPR, ConstWide16), 'const-wide/32' : (EXPR, ConstWide32), 'const-wide' : (EXPR, ConstWide), 'const-wide/high16' : (EXPR, ConstWideHigh16), 'const-string' : (EXPR, ConstString), 'const-string/jumbo' : (EXPR, ConstStringJumbo), 'const-class' : (EXPR, ConstClass), 'monitor-enter' : (EXPR, MonitorEnter), 'monitor-exit' : (EXPR, MonitorExit), 'check-cast' : (EXPR, CheckCast), 'instance-of' : (EXPR, InstanceOf), 'array-length' : (EXPR, ArrayLength), 'new-instance' : (EXPR, NewInstance), 'new-array' : (EXPR, NewArray), 'filled-new-array' : (EXPR, FilledNewArray), 'filled-new-array/range': (EXPR, FilledNewArrayRange), 'fill-array-data' : (EXPR, FillArrayData), 'throw' : (EXPR, Throw), 'goto' : (EXPR, Goto), 'goto/16' : (EXPR, Goto16), 'goto/32' : (EXPR, Goto32), 'packed-switch' : (INST, PackedSwitch), 'sparse-switch' : (EXPR, SparseSwitch), 'cmpl-float' : (EXPR, CmplFloat), 'cmpg-float' : (EXPR, CmpgFloat), 'cmpl-double' : (EXPR, CmplDouble), 'cmpg-double' : (EXPR, CmpgDouble), 'cmp-long' : (EXPR, CmpLong), 'if-eq' : (COND, IfEq), 'if-ne' : (COND, IfNe), 'if-lt' : (COND, IfLt), 'if-ge' : (COND, IfGe), 'if-gt' : (COND, IfGt), 'if-le' : (COND, IfLe), 'if-eqz' : (COND, IfEqz), 'if-nez' : (COND, IfNez), 'if-ltz' : (COND, IfLtz), 'if-gez' : (COND, IfGez), 'if-gtz' : (COND, IfGtz), 'if-lez' : (COND, IfLez), 'aget' : (EXPR, AGet), 'aget-wide' : (EXPR, AGetWide), 'aget-object' : (EXPR, AGetObject), 'aget-boolean' : (EXPR, AGetBoolean), 'aget-byte' : (EXPR, AGetByte), 'aget-char' : (EXPR, AGetChar), 'aget-short' : (EXPR, AGetShort), 'aput' : (INST, APut), 'aput-wide' : (INST, APutWide), 'aput-object' : (INST, APutObject), 'aput-boolean' : (INST, APutBoolean), 'aput-byte' : (INST, APutByte), 'aput-char' : (INST, APutChar), 'aput-short' : (INST, APutShort), 'iget' : (EXPR, IGet), 'iget-wide' : (EXPR, IGetWide), 'iget-object' : (EXPR, IGetObject), 'iget-boolean' : (EXPR, IGetBoolean), 'iget-byte' : (EXPR, IGetByte), 'iget-char' : (EXPR, IGetChar), 'iget-short' : (EXPR, IGetShort), 'iput' : (INST, IPut), 'iput-wide' : (INST, IPutWide), 'iput-object' : (INST, IPutObject), 'iput-boolean' : (INST, IPutBoolean), 'iput-byte' : (INST, IPutByte), 'iput-char' : (INST, IPutChar), 'iput-short' : (INST, IPutShort), 'sget' : (EXPR, SGet), 'sget-wide' : (EXPR, SGetWide), 'sget-object' : (EXPR, SGetObject), 'sget-boolean' : (EXPR, SGetBoolean), 'sget-byte' : (EXPR, SGetByte), 'sget-char' : (EXPR, SGetChar), 'sget-short' : (EXPR, SGetShort), 'sput' : (INST, SPut), 'sput-wide' : (INST, SPutWide), 'sput-object' : (INST, SPutObject), 'sput-boolean' : (INST, SPutBoolean), 'sput-byte' : (INST, SPutByte), 'sput-char' : (INST, SPutChar), 'sput-short' : (INST, SPutShort), 'invoke-virtual' : (INST, InvokeVirtual), 'invoke-super' : (INST, InvokeSuper), 'invoke-direct' : (INST, InvokeDirect), 'invoke-static' : (INST, InvokeStatic), 'invoke-interface' : (INST, InvokeInterface), 'invoke-virtual/range' : (INST, InvokeVirtualRange), 'invoke-super/range' : (INST, InvokeSuperRange), 'invoke-direct/range' : (INST, InvokeDirectRange), 'invoke-static/range' : (INST, InvokeStaticRange), 'invoke-interface/range': (INST, InvokeInterfaceRange), 'neg-int' : (EXPR, NegInt), 'not-int' : (EXPR, NotInt), 'neg-long' : (EXPR, NegLong), 'not-long' : (EXPR, NotLong), 'neg-float' : (EXPR, NegFloat), 'neg-double' : (EXPR, NegDouble), 'int-to-long' : (EXPR, IntToLong), 'int-to-float' : (EXPR, IntToFloat), 'int-to-double' : (EXPR, IntToDouble), 'long-to-int' : (EXPR, LongToInt), 'long-to-float' : (EXPR, LongToFloat), 'long-to-double' : (EXPR, LongToDouble), 'float-to-int' : (EXPR, FloatToInt), 'float-to-long' : (EXPR, FloatToLong), 'float-to-double' : (EXPR, FloatToDouble), 'double-to-int' : (EXPR, DoubleToInt), 'double-to-long' : (EXPR, DoubleToLong), 'double-to-float' : (EXPR, DoubleToFloat), 'int-to-byte' : (EXPR, IntToByte), 'int-to-char' : (EXPR, IntToChar), 'int-to-short' : (EXPR, IntToShort), 'add-int' : (EXPR, AddInt), 'sub-int' : (EXPR, SubInt), 'mul-int' : (EXPR, MulInt), 'div-int' : (EXPR, DivInt), 'rem-int' : (EXPR, RemInt), 'and-int' : (EXPR, AndInt), 'or-int' : (EXPR, OrInt), 'xor-int' : (EXPR, XorInt), 'shl-int' : (EXPR, ShlInt), 'shr-int' : (EXPR, ShrInt), 'ushr-int' : (EXPR, UShrInt), 'add-long' : (EXPR, AddLong), 'sub-long' : (EXPR, SubLong), 'mul-long' : (EXPR, MulLong), 'div-long' : (EXPR, DivLong), 'rem-long' : (EXPR, RemLong), 'and-long' : (EXPR, AndLong), 'or-long' : (EXPR, OrLong), 'xor-long' : (EXPR, XorLong), 'shl-long' : (EXPR, ShlLong), 'shr-long' : (EXPR, ShrLong), 'ushr-long' : (EXPR, UShrLong), 'add-float' : (EXPR, AddFloat), 'sub-float' : (EXPR, SubFloat), 'mul-float' : (EXPR, MulFloat), 'div-float' : (EXPR, DivFloat), 'rem-float' : (EXPR, RemFloat), 'add-double' : (EXPR, AddDouble), 'sub-double' : (EXPR, SubDouble), 'mul-double' : (EXPR, MulDouble), 'div-double' : (EXPR, DivDouble), 'rem-double' : (EXPR, RemDouble), 'add-int/2addr' : (EXPR, AddInt2Addr), 'sub-int/2addr' : (EXPR, SubInt2Addr), 'mul-int/2addr' : (EXPR, MulInt2Addr), 'div-int/2addr' : (EXPR, DivInt2Addr), 'rem-int/2addr' : (EXPR, RemInt2Addr), 'and-int/2addr' : (EXPR, AndInt2Addr), 'or-int/2addr' : (EXPR, OrInt2Addr), 'xor-int/2addr' : (EXPR, XorInt2Addr), 'shl-int/2addr' : (EXPR, ShlInt2Addr), 'shr-int/2addr' : (EXPR, ShrInt2Addr), 'ushr-int/2addr' : (EXPR, UShrInt2Addr), 'add-long/2addr' : (EXPR, AddLong2Addr), 'sub-long/2addr' : (EXPR, SubLong2Addr), 'mul-long/2addr' : (EXPR, MulLong2Addr), 'div-long/2addr' : (EXPR, DivLong2Addr), 'rem-long/2addr' : (EXPR, RemLong2Addr), 'and-long/2addr' : (EXPR, AndLong2Addr), 'or-long/2addr' : (EXPR, OrLong2Addr), 'xor-long/2addr' : (EXPR, XorLong2Addr), 'shl-long/2addr' : (EXPR, ShlLong2Addr), 'shr-long/2addr' : (EXPR, ShrLong2Addr), 'ushr-long/2addr' : (EXPR, UShrLong2Addr), 'add-float/2addr' : (EXPR, AddFloat2Addr), 'sub-float/2addr' : (EXPR, SubFloat2Addr), 'mul-float/2addr' : (EXPR, MulFloat2Addr), 'div-float/2addr' : (EXPR, DivFloat2Addr), 'rem-float/2addr' : (EXPR, RemFloat2Addr), 'add-double/2addr' : (EXPR, AddDouble2Addr), 'sub-double/2addr' : (EXPR, SubDouble2Addr), 'mul-double/2addr' : (EXPR, MulDouble2Addr), 'div-double/2addr' : (EXPR, DivDouble2Addr), 'rem-double/2addr' : (EXPR, RemDouble2Addr), 'add-int/lit16' : (EXPR, AddIntLit16), 'rsub-int' : (EXPR, RSubInt), 'mul-int/lit16' : (EXPR, MulIntLit16), 'div-int/lit16' : (EXPR, DivIntLit16), 'rem-int/lit16' : (EXPR, RemIntLit16), 'and-int/lit16' : (EXPR, AndIntLit16), 'or-int/lit16' : (EXPR, OrIntLit16), 'xor-int/lit16' : (EXPR, XorIntLit16), 'add-int/lit8' : (EXPR, AddIntLit8), 'rsub-int/lit8' : (EXPR, RSubIntLit8), 'mul-int/lit8' : (EXPR, MulIntLit8), 'div-int/lit8' : (EXPR, DivIntLit8), 'rem-int/lit8' : (EXPR, RemIntLit8), 'and-int/lit8' : (EXPR, AndIntLit8), 'or-int/lit8' : (EXPR, OrIntLit8), 'xor-int/lit8' : (EXPR, XorIntLit8), 'shl-int/lit8' : (EXPR, ShlIntLit8), 'shr-int/lit8' : (EXPR, ShrIntLit8), 'ushr-int/lit8' : (EXPR, UShrIntLit8) }
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import Instruction import Util import pydot LOOP_PRETEST = 0 LOOP_POSTTEST = 1 LOOP_ENDLESS = 2 NODE_IF = 0 NODE_SWITCH = 1 NODE_STMT = 2 NODE_RETURN = 3 def indent(ind): return ' ' * ind class Block(object): def __init__(self, node, block): self.block = block self.node = node self.next = None def get_next(self): return self.next def set_next(self, next): self.next = next def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): Util.log('Process not done : %s' % self, 'debug') class StatementBlock(Block): def __init__(self, node, block): super(StatementBlock, self).__init__(node, block) def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): res = process_block(self.block, memory, tabsymb, vars, ind) ins = '' for i in res: ins += '%s%s;\n' % (indent(ind), i.value()) if self.next is not None: if not self.next.traversed: ins += self.next.process(memory, tabsymb, vars, ind, ifollow, nfollow) return ins def __str__(self): return 'Statement(%s)' % self.block.name class WhileBlock(Block): def __init__(self, node, block): super(WhileBlock, self).__init__(node, block) self.true = None self.false = None def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): ins = '' if self.node.looptype == LOOP_PRETEST: lins, cond = self.block.get_cond(memory, tabsymb, vars, ind) for i in lins: ins += '%s%s;\n' % (indent(ind), i.value()) if self.false is self.next: ins += '%swhile(%s) {\n' % (indent(ind), cond.value()) else: cond.neg() ins += '%swhile(%s) {\n' % (indent(ind), cond.value()) elif self.node.looptype == LOOP_POSTTEST: ins += '%sdo {\n' % indent(ind) elif self.node.looptype == LOOP_ENDLESS: ins += '%swhile(true) {\n' % indent(ind) ins += self.block.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) else: Util.log('Error processing loop. No type.', 'error') if not self.node.end_loop(): if self.node.looptype == LOOP_PRETEST: suc = self.true if suc is self.next: suc = self.false else: suc = None ins += self.block.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) if suc: if not suc.traversed: ins += suc.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) else: print 'node :', self.node, self.block.end_loop() print 'suc :', suc print 'end ?', self.node.end_loop(), self.node.endloop, suc.endloop, suc.end_loop() Util.log('Error, goto needed for the loop.', 'error') if self.node.looptype == LOOP_PRETEST: #ins += process_block(self.block, memory, tabsymb, vars, # ind + 1) ins += self.block.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) ins += '%s}\n' % indent(ind) elif self.node.looptype == LOOP_POSTTEST: if not self.node.endloop: end = self.node.loopend.content lins, cond = end.get_cond(memory, tabsymb, vars, ind) self.node.loopend.traversed = True ins += self.block.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) else: end = self.block lins, cond = end.get_cond(memory, tabsymb, vars, ind) self.node.loopend.traversed = True for i in lins: ins += '%s%s;\n' % (indent(ind + 1), i.value()) ins += '%s} while (%s);\n' % (indent(ind), cond.value()) else: ins += '%s}\n' % indent(ind) if self.next and not self.next.traversed: ins += self.next.process(memory, tabsymb, vars, ind, ifollow, nfollow) return ins def __str__(self): if self.node.looptype == LOOP_PRETEST: return 'While(%s)' % self.block elif self.node.looptype == LOOP_POSTTEST: return 'DoWhile(%s)' % self.block else: return 'WhileTrue(%s)' % self.block class SwitchBlock(Block): def __init__(self, node, block): super(SwitchBlock, self).__init__(node, block) def get_switch(self, memory, tabsymb, vars, ind): lins = process_block(self.block, memory, tabsymb, vars, ind) cond = lins[-1] return (lins[:-1], cond) def compute_follow(self): def get_branch(node, l=None): if l is None: l = set() l.add(node) for child in node.succs: if not (child in l): l.add(child) get_branch(child, l) return l branches = [get_branch(br) for br in self.node.succs] join = reduce(set.intersection, branches) if join: self.follow = min(join, key=lambda x: x.num) def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): ins = '' self.compute_follow() lins, switchvalue = self.get_switch(memory, tabsymb, vars, ind) for i in lins: ins += '%s%s;\n' % (indent(ind), i.value()) values = self.block.get_special_ins(switchvalue.ins).get_operands() initval = values[0] # cases = {} # for v in values[1]: # cases[v] = initval # initval += 1 ins += '%sswitch(%s) {\n' % (indent(ind), switchvalue.value()) # print 'BLOCK :', self.block # print 'STARt :', hex(self.block.get_start()) # print 'CASES :', cases for s in self.node.succs: # print 'NEXT :', self.next, hex(self.next.content.block.get_start()) # print 'S :', s, hex(s.content.block.get_start()) if not s.traversed: ins += '%scase %s:\n' % (indent(ind + 1), initval) initval += 1 ins += s.process(memory, tabsymb, vars, ind + 2, ifollow, self.follow) ins += '%sbreak;\n' % indent(ind + 2) else: Util.log('Switch node %s already traversed.' % self, 'error') if self.next and not self.next.traversed: ins += self.next.process(memory, tabsymb, vars, ind, ifollow, nfollow) return ins def __str__(self): return 'Switch(%s)' % self.block.name class TryBlock(Block): def __init__(self, node, block): super(TryBlock, self).__init__(node, block) self.catch = [] def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): res = process_block(self.block, memory, tabsymb, vars, ind) res = ''.join([str(i.value()) for i in res]) return res def add_catch(self, node): self.catch.append(node) def __str__(self): return 'Try(%s)' % self.block.name class CatchBlock(Block): def __init__(self, node, block, type): super(CatchBlock, self).__init__(node, block) self.exceptionType = type def __str__(self): return 'Catch(%s)' % self.block.name class Condition( ): def __init__(self, cond1, cond2, isand, isnot): self.cond1 = cond1 self.cond2 = cond2 self.isand = isand self.isnot = isnot def neg(self): self.cond1.neg() self.cond2.neg() self.isand = not self.isand def get_cond(self, memory, tabsymb, vars, ind): lins1, cond1 = self.cond1.content.get_cond(memory, tabsymb, vars, ind) lins2, cond2 = self.cond2.content.get_cond(memory, tabsymb, vars, ind) if self.isnot: cond1.neg() self.cond = Condition(cond1, cond2, self.isand, self.isnot) lins1.extend(lins2) return lins1, self.cond def value(self): cond = ['||', '&&'][self.isand] return '(%s %s %s)' % (self.cond1.value(), cond, self.cond2.value()) def __str__(self): return '(%s %s %s)' % (self.cond1, ['||', '&&'][self.isand], self.cond2) class ShortCircuitBlock(Block): def __init__(self, newNode, cond): super(ShortCircuitBlock, self).__init__(newNode, None) self.cond = cond newNode.type = NODE_IF newNode.num = cond.cond1.num newNode.looptype = cond.cond1.looptype newNode.loophead = cond.cond1.loop_head() newNode.startloop = cond.cond1.start_loop() newNode.endloop = cond.cond1.end_loop() if cond.cond1.loopend is cond.cond1: newNode.loopend = self else: newNode.loopend = cond.cond1.loopend self.true = None self.false = None self.follow = None def update(self): interval = self.cond.cond1.interval interval.content.remove(self.cond.cond1) interval.content.remove(self.cond.cond2) interval.add(self.node) self.node.set_next(self.cond.cond1.get_next()) for pred in self.cond.cond1.preds: if pred.get_next() is self.cond.cond1: pred.set_next(self.node) pred.del_node(self.cond.cond1) pred.add_node(self.node) for suc in self.cond.cond1.succs: suc.preds.remove(self.cond.cond1) for suc in self.cond.cond2.succs: suc.preds.remove(self.cond.cond2) self.node.add_node(suc) def get_cond(self, memory, tabsymb, vars, ind): return self.cond.get_cond(memory, tabsymb, vars, ind) def compute_follow(self): def get_branch(node, l=None): if l is None: l = set() l.add(node) for child in node.succs: if not (child in l): l.add(child) get_branch(child, l) return l true = get_branch(self.true) false = get_branch(self.false) join = true & false if join: self.follow = min(join, key=lambda x: x.num) def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): ins = '' lins, cond = self.get_cond(memory, tabsymb, vars, ind) for i in lins: ins += '%s%s;\n' % (indent(ind), i.value()) self.compute_follow() if self.follow: if not self.true.traversed: if not (self.true is self.follow): ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.true.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) else: # no true clause ? cond.neg() ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) else: cond.neg() ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) if not self.false.traversed: if not (self.false is self.follow): ins += '%s} else {\n' % indent(ind) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) ins += '%s}\n' % indent(ind) if not self.follow.traversed: ins += self.follow.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) else: # if then else ins += '%sif(%s) {\n' % (indent(ind), cond.value()) ins += self.true.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) ins += '%s} else {\n' % indent(ind) ins += self.false.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) ins += '%s}\n' % indent(ind) return ins def __str__(self): r = 'SC(' r += str(self.cond) r += ')' return r class IfBlock(Block): def __init__(self, node, block): super(IfBlock, self).__init__(node, block) self.true = None self.false = None self.follow = None def get_cond(self, memory, tabsymb, vars, ind): lins = process_block(self.block, memory, tabsymb, vars, ind) cond = lins[-1] return (lins[:-1], cond) def compute_follow(self): def get_branch(node, l=None): if l is None: l = set() l.add(node) for child in node.succs: if not (child in l): l.add(child) get_branch(child, l) return l true = get_branch(self.true) false = get_branch(self.false) join = true & false if join: self.follow = min(join, key=lambda x: x.num) def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): ins = '' lins, cond = self.get_cond(memory, tabsymb, vars, ind) for i in lins: ins += '%s%s;\n' % (indent(ind), i.value()) self.compute_follow() if self.follow: if not self.true.traversed: if not (self.true is self.follow): ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.true.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) else: # no true clause ? cond.neg() ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) else: cond.neg() ins += '%sif (%s) {\n' % (indent(ind), cond.value()) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) if not self.false.traversed: if not (self.false is self.follow): ins += '%s} else {\n' % indent(ind) ins += self.false.process(memory, tabsymb, vars, ind + 1, self.follow, nfollow) ins += '%s}\n' % indent(ind) if not self.follow.traversed: ins += self.follow.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) else: # if then else ins += '%sif(%s) {\n' % (indent(ind), cond.value()) ins += self.true.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) ins += '%s} else {\n' % indent(ind) ins += self.false.process(memory, tabsymb, vars, ind + 1, ifollow, nfollow) ins += '%s}\n' % indent(ind) return ins def __str__(self): return 'If(%s)' % self.block.name class Node(object): def __init__(self): self.succs = [] self.preds = [] self.type = None self.content = None self.interval = None self.next = None self.num = 0 self.looptype = None self.loophead = None self.loopend = None self.startloop = False self.endloop = False self.traversed = False def __contains__(self, item): if item == self: return True return False def add_node(self, node): if self.type == NODE_IF: if self.content.false is None: self.content.false = node elif self.content.true is None: self.content.true = node elif self.type == NODE_STMT: self.content.next = node if node not in self.succs: self.succs.append(node) if self not in node.preds: node.preds.append(self) def del_node(self, node): if self.type == NODE_IF: if self.content.false is None: self.content.false = None elif self.content.true is node: self.content.true = None self.succs.remove(node) def set_content(self, content): self.content = content def set_loophead(self, head): if self.loophead is None: self.loophead = head def set_loopend(self, end): if self.loopend is None: self.loopend = end def loop_head(self): return self.loophead def get_head(self): return self def get_end(self): return self def set_loop_type(self, type): self.looptype = type def set_startloop(self): self.startloop = True def set_endloop(self): self.endloop = True def start_loop(self): return self.startloop def end_loop(self): return self.endloop def process(self, memory, tabsymb, vars, ind, ifollow, nfollow): print 'PROCESSING %s' % self.content if self in (ifollow, nfollow) or self.traversed: print '\tOr not.' return '' self.traversed = True # vars.startBlock() / endBlock ? return self.content.process(memory, tabsymb, vars, ind, ifollow, nfollow) def get_next(self): return self.content.get_next() def set_next(self, next): self.content.set_next(next) def __repr__(self): return '%d-%s' % (self.num, str(self.content)) class Graph( ): def __init__(self, nodes, tradBlock): self.nodes = nodes self.tradBlock = tradBlock for node in self.nodes: if node.type is None: node.type = node.head.get_head().type def remove_jumps(self): for node in self.nodes: if len(node.content.block.ins) == 0: for suc in node.succs: suc.preds.remove(node) for pred in node.preds: pred.succs.remove(node) pred.add_node(suc) self.nodes.remove(node) def get_nodes_reversed(self): return sorted(self.nodes, key=lambda x: x.num, reverse=True) def first_node(self): return sorted(self.nodes, key=lambda x: x.num)[0] def __repr__(self): r = 'GRAPHNODE :\n' for node in self.nodes: r += '\tNODE :\t' + str(node) + '\n' for child in node.succs: r += '\t\t\tCHILD : ' + str(child) + '\n' return r def draw(self, dname, name): if len(self.nodes) < 3: return digraph = 'Digraph %s {\n' % dname digraph += 'graph [bgcolor=white];\n' digraph += 'node [color=lightgray, style=filled shape=box '\ 'fontname=\"Courier\" fontsize=\"8\"];\n' slabel = '' for node in self.nodes: val = 'green' lenSuc = len(node.succs) if lenSuc > 1: val = 'red' elif lenSuc == 1: val = 'blue' for child in node.succs: digraph += '"%s" -> "%s" [color="%s"];\n' % (node, child, val) if val == 'red': val = 'green' slabel += '"%s" [ label = "%s" ];\n' % (node, str(node)) dir = 'graphs2' digraph += slabel + '}' pydot.graph_from_dot_data(digraph).write_png('%s/%s.png' % (dir, name)) class AST( ): def __init__(self, root, doms): self.succs = [root] # else: # self.root = root # self.childs = root.succs # print 'Root :', root, # if root.looptype: # print ['LOOP_PRETEST', 'LOOP_POSTTEST', 'LOOP_ENDLESS'][root.looptype] # else: # print 'not loop' # print 'childs :', self.childs self.build(root, doms) # print 'childs after build :', self.childs # self.childs = [AST(child, False) for child in self.childs] def build(self, node, doms): if node.type == NODE_RETURN: child = None else: child = node.get_next() # if child is None and len(node.succs) > 0: # self.childs = node.succs # return # node.set_next(None) if child is not None: for pred in child.preds: if child in pred.succs: pred.succs.remove(child) child.preds = [] self.succs.append(child) self.build(child, doms) def draw(self, dname, name): if len(self.succs) < 2: return def slabel(node, done): done.add(node) val = 'green' lenSuc = len(node.succs) if lenSuc > 1: val = 'red' elif lenSuc == 1: val = 'blue' label = '' for child in node.succs: label += '"%s" -> "%s" [color="%s"];\n' % (node, child, val) if val == 'red': val = 'green' if not (child in done): label += slabel(child, done) label += '"%s" [ label = "%s" ];\n' % (node, str(node)) return label digraph = 'Digraph %s {\n' % dname digraph += 'graph [bgcolor=white];\n' digraph += 'node [color=lightgray, style=filled shape=box '\ 'fontname=\"Courier\" fontsize=\"8\"];\n' done = set() label = slabel(self, done) dir = 'graphs2/ast' digraph += label + '}' pydot.graph_from_dot_data(digraph).write_png('%s/%s.png' % (dir, name)) class Interval(Node): def __init__(self, head, nodes, num): super(Interval, self).__init__() self.content = nodes self.head = head self.end = None self.internum = num for node in nodes: node.interval = self def __contains__(self, item): for n in self.content: if item in n: return True return False def add(self, node): self.content.append(node) node.interval = self def compute_end(self): for node in self.content: for suc in node.succs: if suc not in self.content: self.end = node def get_end(self): return self.end.get_end() def type(self): return self.get_head().type def set_next(self, next): self.head.set_next(next.get_head()) def set_loop_type(self, type): self.looptype = type self.get_head().set_loop_type(type) def set_loophead(self, head): self.loophead = head for n in self.content: n.set_loophead(head) def set_loopend(self, end): self.loopend = end self.get_head().set_loopend(end) def set_startloop(self): self.head.set_startloop() def get_head(self): return self.head.get_head() def loop_head(self): return self.head.loop_head() def __repr__(self): return 'Interval(%d)=%s' % (self.internum, self.head.get_head()) def Construct(node, block): # if block.exception_analysis: # currentblock = TryBlock(node, block) # else: last_ins = block.ins[-1].op_name if last_ins.startswith('return'): node.type = NODE_RETURN currentblock = StatementBlock(node, block) elif last_ins.endswith('switch'): node.type = NODE_SWITCH currentblock = SwitchBlock(node, block) elif last_ins.startswith('if'): node.type = NODE_IF currentblock = IfBlock(node, block) else: if last_ins.startswith('goto'): block.ins = block.ins[:-1] node.type = NODE_STMT currentblock = StatementBlock(node, block) return currentblock def process_block(block, memory, tabsymb, vars, ind): lins = [] memory['heap'] = None for ins in block.get_ins(): Util.log('Name : %s, Operands : %s' % (ins.get_name(), ins.get_operands()), 'debug') _ins = Instruction.INSTRUCTION_SET.get(ins.get_name().lower()) if _ins is None: Util.log('Unknown instruction : %s.' % _ins.get_name().lower(), 'error') else: newIns = _ins[1] newIns = newIns(ins) newIns.symbolic_process(memory, tabsymb, vars) #if _ins[0] in (Instruction.INST, Instruction.COND): lins.append(newIns) if memory['heap'] is True: memory['heap'] = newIns Util.log('---> newIns : %s. varName : %s.\n' % (ins.get_name(), newIns), 'debug') return lins def BFS(start): from Queue import Queue Q = Queue() Q.put(start) nodes = [] nodes.append(start) while not Q.empty(): node = Q.get() for child in node.childs: if child[-1] not in nodes: nodes.append(child[-1]) Q.put(child[-1]) return nodes def NumberGraph(v, interval, num, visited = None): if visited is None: visited = set() v.num = num visited.add(v) for suc in v.succs: if suc not in visited: if suc in interval: toVisit = True for pred in suc.preds: if pred not in visited and \ pred.interval.internum < suc.interval.internum: toVisit = False if toVisit: num = NumberGraph(suc, interval, num + 1, visited) else: toVisit = True for pred in suc.preds: if pred not in visited: toVisit = False if toVisit: num = NumberGraph(suc, interval, num + 1, visited) return num def Intervals(num, G): I = [] H = [G.nodes[0]] L = {} processed = dict([(i, -1) for i in G.nodes]) while H: n = H.pop(0) if processed[n] == -1: processed[n] = 1 L[n] = Interval(n, [n], num) num += 1 change = True while change: change = False for m in G.nodes: add = True if len(m.preds) > 0: for p in m.preds: if p not in L[n].content: add = False if add and m not in L[n].content: L[n].add(m) change = True for m in G.nodes: add = False if m not in H and m not in L[n].content: for p in m.preds: if p in L[n].content: add = True if add: H.append(m) L[n].compute_end() I.append(L[n]) return I, L, num def DerivedSequence(G): I, L, nInterv = Intervals(1, G) NumberGraph(G.nodes[0], L, 1) derivSeq = [] derivInterv = [] different = True while different: derivSeq.append(G) derivInterv.append(L) for interval in I: for pred in interval.head.preds: if interval is not pred.interval: pred.interval.add_node(interval) for node in interval.content: for suc in node.succs: if interval is not suc.interval: interval.add_node(suc.interval) G = Graph(I, None) I, L, nInterv = Intervals(nInterv, G) NumberGraph(G.nodes[0], L, 1) if len(I) == 1 and len(I[0].content) == 1: derivSeq.append(G) derivInterv.append(L) different = False return derivSeq, derivInterv def InLoop(node, nodesInLoop): for n in nodesInLoop: if node in n: return True return False def MarkLoop(G, root, end, L): print 'MARKLOOP :', root, 'END :', end def MarkLoopRec(end): if not InLoop(end, nodesInLoop): nodesInLoop.append(end) end.set_loophead(headnode) for node in end.preds: if node.num > headnode.num and node.num <= end.num: if InLoop(node, L[root].content): MarkLoopRec(node) headnode = root.get_head() endnode = end.get_end() nodesInLoop = [headnode] root.set_loophead(headnode) root.set_loopend(endnode) root.set_startloop() for pred in root.get_head().preds: if pred.num > headnode.num: pred.set_endloop() endnode.set_endloop() MarkLoopRec(endnode) return nodesInLoop def LoopType(G, root, end, nodesInLoop): for pred in root.get_head().preds: if pred.interval is end: end = pred if end.type == NODE_IF: if root.type == NODE_IF: succs = root.succs if len(succs) == 1 and InLoop(succs[0].get_head(), nodesInLoop): root.set_loop_type(LOOP_POSTTEST) elif InLoop(succs[0], nodesInLoop) and InLoop(succs[1], nodesInLoop): root.set_loop_type(LOOP_POSTTEST) else: root.set_loop_type(LOOP_PRETEST) else: root.set_loop_type(LOOP_POSTTEST) else: if root.type == NODE_IF: succs = root.succs if len(succs) == 1 and InLoop(succs[0].get_head(), nodesInLoop): root.set_loop_type(LOOP_PRETEST) elif InLoop(succs[0], nodesInLoop) and InLoop(succs[1], nodesInLoop): root.set_loop_type(LOOP_ENDLESS) else: root.set_loop_type(LOOP_PRETEST) else: root.set_loop_type(LOOP_ENDLESS) def LoopFollow(G, root, end, nodesInLoop): for pred in root.get_head().preds: if pred.interval is end: end = pred if root.looptype == LOOP_PRETEST: succ = root.get_head() if InLoop(succ.succs[0], nodesInLoop): root.set_next(succ.succs[1]) else: root.set_next(succ.succs[0]) elif root.looptype == LOOP_POSTTEST: succ = end.get_end() if InLoop(succ.succs[0], nodesInLoop): root.set_next(succ.succs[1]) else: root.set_next(succ.succs[0]) else: numNext = 10**10 #FIXME? for node in nodesInLoop: if node.type == NODE_IF: succs = node.succs if not InLoop(succs[0], nodesInLoop) and succs[0].num < numNext: next = succs[0] numNext = next.num elif not InLoop(succs[1], nodesInLoop) \ and succs[1].num < numNext: next = succs[1] numNext = next.num if numNext != 10**10: root.set_next(next) def LoopStruct(G, Gi, Li): if len(Li) < 0: return for i, G in enumerate(Gi): loops = set() L = Li[i] for head in sorted(L.keys(), key=lambda x: x.num): for node in head.preds: if node.interval == head.interval: loops.update(MarkLoop(G, head, node, L)) LoopType(G, head, node, loops) LoopFollow(G, head, node, loops) def IfStruct(G, immDom): unresolved = set() for node in G.get_nodes_reversed(): if node.type == NODE_IF and not (node.start_loop() or node.end_loop()): ldominates = [] for n, dom in immDom.iteritems(): if node is dom and len(n.preds) > 1: ldominates.append(n) if len(ldominates) > 0: n = max(ldominates, key=lambda x: x.num) node.set_next(n) for x in unresolved: x.set_next(n) unresolved = set() else: unresolved.add(node) def SwitchStruct(G, immDom): unresolved = set() for node in G.get_nodes_reversed(): if node.type == NODE_SWITCH: for suc in node.succs: if immDom[suc] is not node: n = commonImmedDom(node.succs, immDom) #TODO else: n = node ldominates = [] for n, dom in immDom.iteritems(): if node is dom and len(n.preds) >= 2: ldominates.append(n) if len(ldominates) > 0: j = max(ldominates, key=lambda x: len(x.preds)) node.set_next(j) for x in unresolved: x.set_next(j) unresolved = set() else: unresolved.add(node) def ShortCircuitStruct(G): def MergeNodes(node1, node2, isAnd, isNot): G.nodes.remove(node1) G.nodes.remove(node2) done.add(node2) newNode = Node() block = ShortCircuitBlock(newNode, Condition(node1, node2, isAnd, isNot)) newNode.set_content(block) block.update() G.nodes.append(newNode) change = True while change: G.nodes = sorted(G.nodes, key=lambda x: x.num) change = False done = set() for node in G.nodes[:]: # work on copy if node.type == NODE_IF and node not in done and \ not node.end_loop():#(node.start_loop() or node.end_loop()): then = node.succs[1] els = node.succs[0] if then.type is NODE_IF and len(then.preds) == 1 and \ not then.end_loop(): if then.succs[0] is els: # !node && t MergeNodes(node, then, True, True) change = True elif then.succs[1] is els: # node || t MergeNodes(node, then, False, False) change = True elif els.type is NODE_IF and len(els.preds) == 1 and \ not els.end_loop(): if els.succs[0] is then: # !node && e MergeNodes(node, els, True, True) change = True elif els.succs[1] is then: # node || e MergeNodes(node, els, False, False) change = True done.add(node) def WhileBlockStruct(G): for node in G.nodes: if node.start_loop(): cnt = node.content block = WhileBlock(node, cnt) block.next = cnt.next if node.type == NODE_IF: print 'NODE :', node print 'CNT :', cnt print 'TRUE :', cnt.true print 'FALSE :', cnt.false block.true = node.content.true block.false = node.content.false node.set_content(block) def Dominators(G): dom = {} dom[G.nodes[0]] = set([G.nodes[0]]) for n in G.nodes[1:]: dom[n] = set(G.nodes) changes = True while changes: changes = False for n in G.nodes[1:]: old = len(dom[n]) for p in n.preds: dom[n].intersection_update(dom[p]) dom[n] = dom[n].union([n]) if old != len(dom[n]): changes = True return dom def BuildImmediateDominator_old(G): immDom = {} dominators = Dominators(G) for dom in dominators: dom_set = dominators[dom] - set([dom]) if dom_set: immDom[dom] = max(dom_set, key=lambda x: x.num) else: immDom[dom] = None return immDom def BuildImmediateDominator(G): def commonDom(cur, pred): if not cur: return pred if not pred: return cur while cur and pred and cur is not pred: if cur.num < pred.num: pred = immDom[pred] else: cur = immDom[cur] return cur immDom = dict([(n, None) for n in G.nodes]) for node in sorted(G.nodes, key=lambda x: x.num): for pred in node.preds: if pred.num < node.num: immDom[node] = commonDom(immDom[node], pred) return immDom def ConstructAST(basicblocks, exceptions): def build_node_from_bblock(bblock): node = Node() nodeBlock = Construct(node, bblock) bblockToNode[bblock] = node node.set_content(nodeBlock) nodegraph.append(node) # if bblock.exception_analysis: # Util.log("BBLOCK == %s" % bblock.name, 'debug') # build_exception(node, bblock) return node def build_exception(node, bblock): Util.log('Exceptions :', 'debug') for exception in bblock.exception_analysis.exceptions: Util.log(' => %s' % exception, 'debug') catchNode = bblockToNode.get(exception[-1]) if catchNode is None: catchNode = Node() catchBlock = CatchBlock(catchNode, exception[-1], exception[0]) bblockToNode[exception[-1]] = catchNode catchNode.set_content(catchBlock) nodegraph.append(catchNode) catchNode.num += 1 node.content.add_catch(catchNode) node.add_node(catchNode) # Native methods,... no blocks. if len(basicblocks) < 1: return graph = BFS(basicblocks[0]) # Needed for now because of exceptions nodegraph = [] # Construction of a mapping of basic blocks into Nodes bblockToNode = {} for bblock in graph: node = bblockToNode.get(bblock) if node is None: node = build_node_from_bblock(bblock) for child in bblock.childs: #[::-1] for rev post order right to left childNode = bblockToNode.get(child[-1]) if childNode is None: childNode = build_node_from_bblock(child[-1]) node.add_node(childNode) G = Graph(nodegraph, bblockToNode) G.remove_jumps() Gi, Li = DerivedSequence(G) immdoms = BuildImmediateDominator(G) SwitchStruct(G, immdoms) LoopStruct(G, Gi, Li) IfStruct(G, immdoms) ShortCircuitStruct(G) WhileBlockStruct(G) if False: #if True: import string mmeth = basicblocks[0].get_method() dname = filter(lambda x: x in string.letters + string.digits, mmeth.get_name()) mname = mmeth.get_class_name().split('/')[-1][:-1] + '#' + dname for i, g in enumerate(Gi, 1): name = mname + '-%d' % i g.draw(dname, name) for node in G.nodes: for pred in node.preds: if node in pred.succs and node.num <= pred.num: pred.succs.remove(node) #ast = AST(G.first_node(), None)#invdoms) #if False: ##if True: # import string # mmeth = basicblocks[0].get_method() # dname = filter(lambda x: x in string.letters + string.digits, # mmeth.get_name()) # mname = mmeth.get_class_name().split('/')[-1][:-1] + '#' + dname # ast.draw(dname, mname) #return ast return G
Python
# This file is part of Androguard. # # Copyright (C) 2011, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from subprocess import Popen, PIPE, STDOUT import tempfile, os from androguard.core.androconf import rrmdir from pygments.filter import Filter from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter, TerminalFormatter from pygments.token import Token, Text, STANDARD_TYPES class DecompilerDex2Jad : def __init__(self, vm, path_dex2jar = "./decompiler/dex2jar/", bin_dex2jar = "dex2jar.sh", path_jad="./decompiler/jad/", bin_jad="jad") : self.classes = {} self.classes_failed = [] pathtmp = os.getcwd() + "/tmp/" if not os.path.exists(pathtmp) : os.makedirs( pathtmp ) fd, fdname = tempfile.mkstemp( dir=pathtmp ) fd = os.fdopen(fd, "w+b") fd.write( vm.get_buff() ) fd.flush() fd.close() compile = Popen([ path_dex2jar + bin_dex2jar, fdname ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink( fdname ) pathclasses = fdname + "dex2jar/" compile = Popen([ "unzip", fdname + "_dex2jar.jar", "-d", pathclasses ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink( fdname + "_dex2jar.jar" ) for root, dirs, files in os.walk( pathclasses, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f compile = Popen([ path_jad + bin_jad, "-o", "-d", root, real_filename ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() for i in vm.get_classes() : fname = pathclasses + "/" + i.get_name()[1:-1] + ".jad" if os.path.isfile(fname) == True : fd = open(fname, "r") self.classes[ i.get_name() ] = fd.read() fd.close() else : self.classes_failed.append( i.get_name() ) rrmdir( pathclasses ) def get_source(self, class_name, method_name) : if class_name not in self.classes : return "" lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def display_source(self, class_name, method_name, method_descriptor) : print self.get_source( class_name, method_name ) def get_all(self, class_name) : if class_name not in self.classes : return "" lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def display_all(self, class_name) : print self.get_all( class_name ) class DecompilerDed : def __init__(self, vm, path="./decompiler/ded/", bin_ded = "ded.sh") : self.classes = {} self.classes_failed = [] pathtmp = os.getcwd() + "/tmp/" if not os.path.exists(pathtmp) : os.makedirs( pathtmp ) fd, fdname = tempfile.mkstemp( dir=pathtmp ) fd = os.fdopen(fd, "w+b") fd.write( vm.get_buff() ) fd.flush() fd.close() dirname = tempfile.mkdtemp(prefix=fdname + "-src") compile = Popen([ path + bin_ded, "-c", "-o", "-d", dirname, fdname ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink( fdname ) findsrc = None for root, dirs, files in os.walk( dirname + "/optimized-decompiled/" ) : if dirs != [] : for f in dirs : if f == "src" : findsrc = root if findsrc[-1] != "/" : findsrc += "/" findsrc += f break if findsrc != None : break for i in vm.get_classes() : fname = findsrc + "/" + i.get_name()[1:-1] + ".java" #print fname if os.path.isfile(fname) == True : fd = open(fname, "r") self.classes[ i.get_name() ] = fd.read() fd.close() else : self.classes_failed.append( i.get_name() ) rrmdir( dirname ) def get_source(self, class_name, method_name) : if class_name not in self.classes : return "" lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def display_source(self, class_name, method_name, method_descriptor) : print self.get_source( class_name, method_name ) def get_all(self, class_name) : if class_name not in self.classes : return "" lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def display_all(self, class_name) : print self.get_all( class_name ) class MethodFilter(Filter): def __init__(self, **options): Filter.__init__(self, **options) self.method_name = options["method_name"] #self.descriptor = options["descriptor"] self.present = False self.get_desc = True #False def filter(self, lexer, stream) : a = [] l = [] rep = [] for ttype, value in stream: if self.method_name == value and (ttype is Token.Name.Function or ttype is Token.Name) : #print ttype, value item_decl = -1 for i in range(len(a)-1, 0, -1) : if a[i][0] is Token.Keyword.Declaration : if a[i][1] != "class" : item_decl = i break if item_decl != -1 : self.present = True l.extend( a[item_decl:] ) if self.present and ttype is Token.Keyword.Declaration : item_end = -1 for i in range(len(l)-1, 0, -1) : if l[i][0] is Token.Operator and l[i][1] == "}" : item_end = i break if item_end != -1 : rep.extend( l[:item_end+1] ) l = [] self.present = False if self.present : # if self.get_desc == False : # if ttype is Token.Operator and value == ")" : # self.get_desc = True # # item_desc = -1 # for i in range(len(l)-1, 0, -1) : # if l[i][1] == "(" : # item_desc = i # break # desc = ''.join(i[1] for i in l[item_desc+1:-1] ) # desc = desc.split() # print "DESC", desc, # equivalent = True # if len(self.descriptor) != len(desc) : # equivalent = False # else : # for i in range(0, len(self.descriptor)) : # if self.descriptor[i] != desc[i] : # equivalent = False # break # print equivalent # if equivalent == False : # self.get_desc = False # self.present = False # l = [] #print "ADD", (ttype, value) l.append( (ttype, value) ) a.append( (ttype, value) ) if self.present : nb = 0 item_end = -1 for i in range(len(l)-1, 0, -1) : if l[i][0] is Token.Operator and l[i][1] == "}" : nb += 1 if nb == 2 : item_end = i break rep.extend( l[:item_end+1] ) #return l[:item_end+1] return rep class DecompilerDAD : def __init__(self, vm, vmx) : self.vm = vm self.vmx = vmx def display_source(self, class_name, method_name, method_descriptor) : m = self.vm.get_method_descriptor( class_name, method_name, method_descriptor ) mx = self.vmx.get_method( m ) from dad import start z = start.DvMethod( mx, start.This ) z.process() lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(z.debug(), lexer, formatter) print result def get_all(self, class_name) : pass
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from struct import pack, unpack, calcsize from collections import namedtuple import re, zipfile, StringIO, os from androguard.core import bytecode from androguard.core.bytecode import SV, SVs ######################################################## JAR FORMAT ######################################################## class JAR : def __init__(self, filename, raw=False) : self.filename = filename if raw == True : self.__raw = filename else : fd = open( filename, "rb" ) self.__raw = fd.read() fd.close() self.zip = zipfile.ZipFile( StringIO.StringIO( self.__raw ) ) def get_classes(self) : l = [] for i in self.zip.namelist() : if ".class" in i : l.append( (i, self.zip.read(i)) ) return l def show(self) : print self.zip.namelist() ######################################################## CLASS FORMAT ######################################################## # Special functions to manage more easily special arguments of bytecode def special_F0(x) : return [ i for i in x ] def special_F0R(x) : return [ x ] def special_F1(x) : return (x[0] << 8) | x[1] def special_F1R(x) : return [ (x & 0xFF00) >> 8, x & 0x00FF ] def special_F2(x) : v = ((x[0] << 8) | x[1]) if v > 0x7FFF : v = (0x7FFF & v) - 0x8000 return v def special_F2R(x) : val = x & 0xFFFF return [ (val & 0xFF00) >> 8, val & 0x00FF ] def special_F3(x) : val = (x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3] if val > 0x7fffffff : val = (0x7fffffff & val) - 0x80000000 return val def special_F3R(x) : val = x & 0xFFFFFFFF return [ (val & 0xFF000000) >> 24, (val & 0x00FF0000) >> 16, (val & 0x0000FF00) >> 8, val & 0x000000FF ] def special_F4(x) : return [ (x[0] << 8) | x[1], x[2] ] def special_F4R(x) : pass def specialSwitch(x) : return x FD = { "B" : "byte", "C" : "char", "D" : "double", "F" : "float", "I" : "int", "J" : "long", "S" : "short", "Z" : "boolean", "V" : "void", } def formatFD(v) : #print v, "--->", l = [] i = 0 while i < len(v) : if v[i] == "L" : base_object = "" i = i + 1 while v[i] != ";" : base_object += v[i] i = i + 1 l.append( os.path.basename( base_object ) ) elif v[i] == "[" : z = [] while v[i] == "[" : z.append( "[]" ) i = i + 1 l.append( [ FD[ v[i] ], z ] ) else : l.append( FD[ v[i] ] ) i = i + 1 #print l return l def TableSwitch(idx, raw_format) : r_buff = [] r_format = ">" idx = idx + 1 n = 0 if idx % 4 : n = 4 - (idx % 4) for i in range(0, n) : r_buff.append( "bytepad%d" % i ) r_format += "B" r_buff.extend( [ "default", "low", "high" ] ) r_format += "LLL" idx = 1 + n + 4 low = unpack('>L', raw_format[ idx : idx + 4 ])[0] idx = idx + 4 high = unpack('>L', raw_format[ idx : idx + 4 ])[0] for i in range(0, high - low + 1) : r_buff.append( "offset%d" % i ) r_format += "L" return specialSwitch, specialSwitch, r_buff, r_format, None def LookupSwitch(idx, raw_format) : r_buff = [] r_format = ">" idx = idx + 1 n = 0 if idx % 4 : n = 4 - (idx % 4) for i in range(0, n) : r_buff.append( "bytepad%d" % i ) r_format += "B" r_buff.extend( [ "default", "npairs" ] ) r_format += "LL" idx = 1 + n + 4 for i in range(0, unpack('>L', raw_format[ idx : idx + 4 ])[0]) : r_buff.extend( [ "match%d" % i, "offset%d" % i ] ) r_format += "LL" return specialSwitch, specialSwitch, r_buff, r_format, None # The list of java bytecodes, with their value, name, and special functions ! JAVA_OPCODES = { 0x32 : [ "aaload" ], 0x53 : [ "aastore" ], 0x1 : [ "aconst_null" ], 0x19 : [ "aload", "index:B", special_F0, special_F0, None ], 0x2a : [ "aload_0" ], 0x2b : [ "aload_1" ], 0x2c : [ "aload_2" ], 0x2d : [ "aload_3" ], 0xbd : [ "anewarray", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_class" ], 0xb0 : [ "areturn" ], 0xbe : [ "arraylength" ], 0x3a : [ "astore", "index:B", special_F0, special_F0, None ], 0x4b : [ "astore_0" ], 0x4c : [ "astore_1" ], 0x4d : [ "astore_2" ], 0x4e : [ "astore_3" ], 0xbf : [ "athrow" ], 0x33 : [ "baload" ], 0x54 : [ "bastore" ], 0x10 : [ "bipush", "byte:B", special_F0, special_F0R, None ], 0x34 : [ "caload" ], 0x55 : [ "castore" ], 0xc0 : [ "checkcast", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, None ], 0x90 : [ "d2f" ], 0x8e : [ "d2i" ], 0x8f : [ "d2l" ], 0x63 : [ "dadd" ], 0x31 : [ "daload" ], 0x52 : [ "dastore" ], 0x98 : [ "dcmpg" ], 0x97 : [ "dcmpl" ], 0xe : [ "dconst_0" ], 0xf : [ "dconst_1" ], 0x6f : [ "ddiv" ], 0x18 : [ "dload", "index:B", special_F0, special_F0, None ], 0x26 : [ "dload_0" ], 0x27 : [ "dload_1" ], 0x28 : [ "dload_2" ], 0x29 : [ "dload_3" ], 0x6b : [ "dmul" ], 0x77 : [ "dneg" ], 0x73 : [ "drem" ], 0xaf : [ "dreturn" ], 0x39 : [ "dstore", "index:B", special_F0, special_F0, None ], 0x47 : [ "dstore_0" ], 0x48 : [ "dstore_1" ], 0x49 : [ "dstore_2" ], 0x4a : [ "dstore_3" ], 0x67 : [ "dsub" ], 0x59 : [ "dup" ], 0x5a : [ "dup_x1" ], 0x5b : [ "dup_x2" ], 0x5c : [ "dup2" ], 0x5d : [ "dup2_x1" ], 0x5e : [ "dup2_x2" ], 0x8d : [ "f2d" ], 0x8b : [ "f2i" ], 0x8c : [ "f2l" ], 0x62 : [ "fadd" ], 0x30 : [ "faload" ], 0x51 : [ "fastore" ], 0x96 : [ "fcmpg" ], 0x95 : [ "fcmpl" ], 0xb : [ "fconst_0" ], 0xc : [ "fconst_1" ], 0xd : [ "fconst_2" ], 0x6e : [ "fdiv" ], 0x17 : [ "fload", "index:B", special_F0, special_F0, None ], 0x22 : [ "fload_0" ], 0x23 : [ "fload_1" ], 0x24 : [ "fload_2" ], 0x25 : [ "fload_3" ], 0x6a : [ "fmul" ], 0x76 : [ "fneg" ], 0x72 : [ "frem" ], 0xae : [ "freturn" ], 0x38 : [ "fstore", "index:B", special_F0, special_F0, None ], 0x43 : [ "fstore_0" ], 0x44 : [ "fstore_1" ], 0x45 : [ "fstore_2" ], 0x46 : [ "fstore_3" ], 0x66 : [ "fsub" ], 0xb4 : [ "getfield", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_field" ], 0xb2 : [ "getstatic", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_field", "get_field_index" ], 0xa7 : [ "goto", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xc8 : [ "goto_w", "branchbyte1:B branchbyte2:B branchbyte3:B branchbyte4:B", special_F3, special_F3R, None ], 0x91 : [ "i2b" ], 0x92 : [ "i2c" ], 0x87 : [ "i2d" ], 0x86 : [ "i2f" ], 0x85 : [ "i2l" ], 0x93 : [ "i2s" ], 0x60 : [ "iadd" ], 0x2e : [ "iaload" ], 0x7e : [ "iand" ], 0x4f : [ "iastore" ], 0x2 : [ "iconst_m1" ], 0x3 : [ "iconst_0" ], 0x4 : [ "iconst_1" ], 0x5 : [ "iconst_2" ], 0x6 : [ "iconst_3" ], 0x7 : [ "iconst_4" ], 0x8 : [ "iconst_5" ], 0x6c : [ "idiv" ], 0xa5 : [ "if_acmpeq", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa6 : [ "if_acmpne", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9f : [ "if_icmpeq", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa0 : [ "if_icmpne", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa1 : [ "if_icmplt", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa2 : [ "if_icmpge", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa3 : [ "if_icmpgt", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xa4 : [ "if_icmple", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x99 : [ "ifeq", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9a : [ "ifne", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9b : [ "iflt", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9c : [ "ifge", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9d : [ "ifgt", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x9e : [ "ifle", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xc7 : [ "ifnonnull", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xc6 : [ "ifnull", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0x84 : [ "iinc", "index:B const:B", special_F0, special_F0, None ], 0x15 : [ "iload", "index:B", special_F0, special_F0, None ], 0x1a : [ "iload_0" ], 0x1b : [ "iload_1" ], 0x1c : [ "iload_2" ], 0x1d : [ "iload_3" ], 0x68 : [ "imul" ], 0x74 : [ "ineg" ], 0xc1 : [ "instanceof", "indexbyte1:B indexbyte2:B", special_F2, special_F2R, None ], 0xb9 : [ "invokeinterface", "indexbyte1:B indexbyte2:B count:B null:B", special_F1, special_F1R, "get_interface", "get_interface_index" ], 0xb7 : [ "invokespecial", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_method", "get_method_index" ], 0xb8 : [ "invokestatic", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_method", "get_method_index" ], 0xb6 : [ "invokevirtual", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_method", "get_method_index" ], 0x80 : [ "ior" ], 0x70 : [ "irem" ], 0xac : [ "ireturn" ], 0x78 : [ "ishl" ], 0x7a : [ "ishr" ], 0x36 : [ "istore", "index:B", special_F0, special_F0, None ], 0x3b : [ "istore_0" ], 0x3c : [ "istore_1" ], 0x3d : [ "istore_2" ], 0x3e : [ "istore_3" ], 0x64 : [ "isub" ], 0x7c : [ "iushr" ], 0x82 : [ "ixor" ], 0xa8 : [ "jsr", "branchbyte1:B branchbyte2:B", special_F2, special_F2R, None ], 0xc9 : [ "jsr_w", "branchbyte1:B branchbyte2:B branchbyte3:B branchbyte4:B", special_F3, special_F3R, None ], 0x8a : [ "l2d" ], 0x89 : [ "l2f" ], 0x88 : [ "l2i" ], 0x61 : [ "ladd" ], 0x2f : [ "laload" ], 0x7f : [ "land" ], 0x50 : [ "lastore" ], 0x94 : [ "lcmp" ], 0x9 : [ "lconst_0" ], 0xa : [ "lconst_1" ], 0x12 : [ "ldc", "index:B", special_F0, special_F0R, "get_value" ], 0x13 : [ "ldc_w", "indexbyte1:B indexbyte2:B", special_F2, special_F2R, None ], 0x14 : [ "ldc2_w", "indexbyte1:B indexbyte2:B", special_F2, special_F2R, None ], 0x6d : [ "ldiv" ], 0x16 : [ "lload", "index:B", special_F0, special_F0, None ], 0x1e : [ "lload_0" ], 0x1f : [ "lload_1" ], 0x20 : [ "lload_2" ], 0x21 : [ "lload_3" ], 0x69 : [ "lmul" ], 0x75 : [ "lneg" ], 0xab : [ "lookupswitch", LookupSwitch ], 0x81 : [ "lor" ], 0x71 : [ "lrem" ], 0xad : [ "lreturn" ], 0x79 : [ "lshl" ], 0x7b : [ "lshr" ], 0x37 : [ "lstore", "index:B", special_F0, special_F0, None ], 0x3f : [ "lstore_0" ], 0x40 : [ "lstore_1" ], 0x41 : [ "lstore_2" ], 0x42 : [ "lstore_3" ], 0x65 : [ "lsub" ], 0x7d : [ "lushr" ], 0x83 : [ "lxor" ], 0xc2 : [ "monitorenter" ], 0xc3 : [ "monitorexit" ], 0xc5 : [ "multianewarray", "indexbyte1:B indexbyte2:B dimensions:B", special_F4, special_F4R, None ], 0xbb : [ "new", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_class", "get_class_index2" ], 0xbc : [ "newarray", "atype:B", special_F0, special_F0, "get_array_type" ], 0x0 : [ "nop" ], 0x57 : [ "pop" ], 0x58 : [ "pop2" ], 0xb5 : [ "putfield", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_field", "get_field_index" ], 0xb3 : [ "putstatic", "indexbyte1:B indexbyte2:B", special_F1, special_F1R, "get_field", "get_field_index" ], 0xa9 : [ "ret", "index:B", special_F0, special_F0, None ], 0xb1 : [ "return" ], 0x35 : [ "saload" ], 0x56 : [ "sastore" ], 0x11 : [ "sipush", "byte1:B byte2:B", special_F1, special_F1R, None ], 0x5f : [ "swap" ], 0xaa : [ "tableswitch", TableSwitch ], 0xc4 : [ "wide" ], # FIXME } # Invert the value and the name of the bytecode INVERT_JAVA_OPCODES = dict([( JAVA_OPCODES[k][0], k ) for k in JAVA_OPCODES]) # List of java bytecodes which can modify the control flow BRANCH_JVM_OPCODES = [ "goto", "goto_w", "if_acmpeq", "if_icmpeq", "if_icmpne", "if_icmplt", "if_icmpge", "if_icmpgt", "if_icmple", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "ifnonnull", "ifnull", "jsr", "jsr_w" ] BRANCH2_JVM_OPCODES = [ "goto", "goto.", "jsr", "jsr.", "if.", "return", ".return", "tableswitch", "lookupswitch" ] MATH_JVM_OPCODES = { ".and" : '&', ".add" : '+', ".sub" : '-', ".mul" : '*', ".div" : '/', ".shl" : '<<', ".shr" : '>>', ".xor" : '^', ".or" : '|', } MATH_JVM_RE = [] for i in MATH_JVM_OPCODES : MATH_JVM_RE.append( (re.compile( i ), MATH_JVM_OPCODES[i]) ) INVOKE_JVM_OPCODES = [ "invoke." ] FIELD_READ_JVM_OPCODES = [ "get." ] FIELD_WRITE_JVM_OPCODES = [ "put." ] BREAK_JVM_OPCODES = [ "invoke.", "put.", ".store", "iinc", "pop", ".return", "if." ] INTEGER_INSTRUCTIONS = [ "bipush", "sipush" ] def EXTRACT_INFORMATION_SIMPLE(op_value) : """Extract information (special functions) about a bytecode""" r_function = JAVA_OPCODES[ op_value ][2] v_function = JAVA_OPCODES[ op_value ][3] f_function = JAVA_OPCODES[ op_value ][4] r_format = ">" r_buff = [] format = JAVA_OPCODES[ op_value ][1] l = format.split(" ") for j in l : operands = j.split(":") name = operands[0] + " " val = operands[1] r_buff.append( name.replace(' ', '') ) r_format += val return ( r_function, v_function, r_buff, r_format, f_function ) def EXTRACT_INFORMATION_VARIABLE(idx, op_value, raw_format) : r_function, v_function, r_buff, r_format, f_function = JAVA_OPCODES[ op_value ][1]( idx, raw_format ) return ( r_function, v_function, r_buff, r_format, f_function ) def determineNext(i, end, m) : #if "invoke" in i.get_name() : # self.childs.append( self.end, -1, ExternalMethod( i.get_operands()[0], i.get_operands()[1], i.get_operands()[2] ) ) # self.childs.append( self.end, self.end, self.__context.get_basic_block( self.end + 1 ) ) if "return" in i.get_name() : return [ -1 ] elif "goto" in i.get_name() : return [ i.get_operands() + end ] elif "jsr" in i.get_name() : return [ i.get_operands() + end ] elif "if" in i.get_name() : return [ end + i.get_length(), i.get_operands() + end ] elif "tableswitch" in i.get_name() : x = [] x.append( i.get_operands().default + end ) for idx in range(0, (i.get_operands().high - i.get_operands().low) + 1) : off = getattr(i.get_operands(), "offset%d" % idx) x.append( off + end ) return x elif "lookupswitch" in i.get_name() : x = [] x.append( i.get_operands().default + end ) for idx in range(0, i.get_operands().npairs) : off = getattr(i.get_operands(), "offset%d" % idx) x.append( off + end ) return x return [] def determineException(vm, m) : return [] def classToJclass(x) : return "L%s;" % x METHOD_INFO = [ '>HHHH', namedtuple("MethodInfo", "access_flags name_index descriptor_index attributes_count") ] ATTRIBUTE_INFO = [ '>HL', namedtuple("AttributeInfo", "attribute_name_index attribute_length") ] FIELD_INFO = [ '>HHHH', namedtuple("FieldInfo", "access_flags name_index descriptor_index attributes_count") ] LINE_NUMBER_TABLE = [ '>HH', namedtuple("LineNumberTable", "start_pc line_number") ] EXCEPTION_TABLE = [ '>HHHH', namedtuple("ExceptionTable", "start_pc end_pc handler_pc catch_type") ] LOCAL_VARIABLE_TABLE = [ '>HHHHH', namedtuple("LocalVariableTable", "start_pc length name_index descriptor_index index") ] LOCAL_VARIABLE_TYPE_TABLE = [ '>HHHHH', namedtuple("LocalVariableTypeTable", "start_pc length name_index signature_index index") ] CODE_LOW_STRUCT = [ '>HHL', namedtuple( "LOW", "max_stack max_locals code_length" ) ] ARRAY_TYPE = { 4 : "T_BOOLEAN", 5 : "T_CHAR", 6 : "T_FLOAT", 7 : "T_DOUBLE", 8 : "T_BYTE", 9 : "T_SHORT", 10 : "T_INT", 11 : "T_LONG", } INVERT_ARRAY_TYPE = dict([( ARRAY_TYPE[k][0], k ) for k in ARRAY_TYPE]) ACC_CLASS_FLAGS = { 0x0001 : [ "ACC_PUBLIC", "Declared public; may be accessed from outside its package." ], 0x0010 : [ "ACC_FINAL", "Declared final; no subclasses allowed." ], 0x0020 : [ "ACC_SUPER", "Treat superclass methods specially when invoked by the invokespecial instruction." ], 0x0200 : [ "ACC_INTERFACE", "Is an interface, not a class." ], 0x0400 : [ "ACC_ABSTRACT", "Declared abstract; may not be instantiated." ], } INVERT_ACC_CLASS_FLAGS = dict([( ACC_CLASS_FLAGS[k][0], k ) for k in ACC_CLASS_FLAGS]) ACC_FIELD_FLAGS = { 0x0001 : [ "ACC_PUBLIC", "Declared public; may be accessed from outside its package." ], 0x0002 : [ "ACC_PRIVATE", "Declared private; usable only within the defining class." ], 0x0004 : [ "ACC_PROTECTED", "Declared protected; may be accessed within subclasses." ], 0x0008 : [ "ACC_STATIC", "Declared static." ], 0x0010 : [ "ACC_FINAL", "Declared final; no further assignment after initialization." ], 0x0040 : [ "ACC_VOLATILE", "Declared volatile; cannot be cached." ], 0x0080 : [ "ACC_TRANSIENT", "Declared transient; not written or read by a persistent object manager." ], } INVERT_ACC_FIELD_FLAGS = dict([( ACC_FIELD_FLAGS[k][0], k ) for k in ACC_FIELD_FLAGS]) ACC_METHOD_FLAGS = { 0x0001 : [ "ACC_PUBLIC", "Declared public; may be accessed from outside its package." ], 0x0002 : [ "ACC_PRIVATE", "Declared private; accessible only within the defining class." ], 0x0004 : [ "ACC_PROTECTED", "Declared protected; may be accessed within subclasses." ], 0x0008 : [ "ACC_STATIC", "Declared static." ], 0x0010 : [ "ACC_FINAL", "Declared final; may not be overridden." ], 0x0020 : [ "ACC_SYNCHRONIZED", "Declared synchronized; invocation is wrapped in a monitor lock." ], 0x0100 : [ "ACC_NATIVE", "Declared native; implemented in a language other than Java." ], 0x0400 : [ "ACC_ABSTRACT", "Declared abstract; no implementation is provided." ], 0x0800 : [ "ACC_STRICT", "Declared strictfp; floating-point mode is FP-strict" ] } INVERT_ACC_METHOD_FLAGS = dict([( ACC_METHOD_FLAGS[k][0], k ) for k in ACC_METHOD_FLAGS]) class CpInfo(object) : """Generic class to manage constant info object""" def __init__(self, buff) : self.__tag = SV( '>B', buff.read_b(1) ) self.__bytes = None self.__extra = 0 tag_value = self.__tag.get_value() format = CONSTANT_INFO[ tag_value ][1] self.__name = CONSTANT_INFO[ tag_value ][0] self.format = SVs( format, CONSTANT_INFO[ tag_value ][2], buff.read( calcsize( format ) ) ) # Utf8 value ? if tag_value == 1 : self.__extra = self.format.get_value().length self.__bytes = SVs( ">%ss" % self.format.get_value().length, namedtuple( CONSTANT_INFO[ tag_value ][0] + "_next", "bytes" ), buff.read( self.format.get_value().length ) ) def get_format(self) : return self.format def get_name(self) : return self.__name def get_bytes(self) : return self.__bytes.get_value().bytes def set_bytes(self, name) : self.format.set_value( { "length" : len(name) } ) self.__extra = self.format.get_value().length self.__bytes = SVs( ">%ss" % self.format.get_value().length, namedtuple( CONSTANT_INFO[ self.__tag.get_value() ][0] + "_next", "bytes" ), name ) def get_length(self) : return self.__extra + calcsize( CONSTANT_INFO[ self.__tag.get_value() ][1] ) def get_raw(self) : if self.__bytes != None : return self.format.get_value_buff() + self.__bytes.get_value_buff() return self.format.get_value_buff() def show(self) : if self.__bytes != None : print self.format.get_value(), self.__bytes.get_value() else : print self.format.get_value() class MethodRef(CpInfo) : def __init__(self, class_manager, buff) : super(MethodRef, self).__init__( buff ) def get_class_index(self) : return self.format.get_value().class_index def get_name_and_type_index(self) : return self.format.get_value().name_and_type_index class InterfaceMethodRef(CpInfo) : def __init__(self, class_manager, buff) : super(InterfaceMethodRef, self).__init__( buff ) def get_class_index(self) : return self.format.get_value().class_index def get_name_and_type_index(self) : return self.format.get_value().name_and_type_index class FieldRef(CpInfo) : def __init__(self, class_manager, buff) : super(FieldRef, self).__init__( buff ) def get_class_index(self) : return self.format.get_value().class_index def get_name_and_type_index(self) : return self.format.get_value().name_and_type_index class Class(CpInfo) : def __init__(self, class_manager, buff) : super(Class, self).__init__( buff ) def get_name_index(self) : return self.format.get_value().name_index class Utf8(CpInfo) : def __init__(self, class_manager, buff) : super(Utf8, self).__init__( buff ) class String(CpInfo) : def __init__(self, class_manager, buff) : super(String, self).__init__( buff ) class Integer(CpInfo) : def __init__(self, class_manager, buff) : super(Integer, self).__init__( buff ) class Float(CpInfo) : def __init__(self, class_manager, buff) : super(Float, self).__init__( buff ) class Long(CpInfo) : def __init__(self, class_manager, buff) : super(Long, self).__init__( buff ) class Double(CpInfo) : def __init__(self, class_manager, buff) : super(Double, self).__init__( buff ) class NameAndType(CpInfo) : def __init__(self, class_manager, buff) : super(NameAndType, self).__init__( buff ) def get_get_name_index(self) : return self.format.get_value().get_name_index def get_name_index(self) : return self.format.get_value().name_index def get_descriptor_index(self) : return self.format.get_value().descriptor_index class EmptyConstant : def __init__(self) : pass def get_name(self) : return "" def get_raw(self) : return "" def get_length(self) : return 0 def show(self) : pass CONSTANT_INFO = { 7 : [ "CONSTANT_Class", '>BH', namedtuple( "CONSTANT_Class_info", "tag name_index" ), Class ], 9 : [ "CONSTANT_Fieldref", '>BHH', namedtuple( "CONSTANT_Fieldref_info", "tag class_index name_and_type_index" ), FieldRef ], 10 : [ "CONSTANT_Methodref", '>BHH', namedtuple( "CONSTANT_Methodref_info", "tag class_index name_and_type_index" ), MethodRef ], 11 : [ "CONSTANT_InterfaceMethodref", '>BHH', namedtuple( "CONSTANT_InterfaceMethodref_info", "tag class_index name_and_type_index" ), InterfaceMethodRef ], 8 : [ "CONSTANT_String", '>BH', namedtuple( "CONSTANT_String_info", "tag string_index" ), String ], 3 : [ "CONSTANT_Integer", '>BL', namedtuple( "CONSTANT_Integer_info", "tag bytes" ), Integer ], 4 : [ "CONSTANT_Float", '>BL', namedtuple( "CONSTANT_Float_info", "tag bytes" ), Float ], 5 : [ "CONSTANT_Long", '>BLL', namedtuple( "CONSTANT_Long_info", "tag high_bytes low_bytes" ), Long ], 6 : [ "CONSTANT_Double", '>BLL', namedtuple( "CONSTANT_Long_info", "tag high_bytes low_bytes" ), Double ], 12 : [ "CONSTANT_NameAndType", '>BHH', namedtuple( "CONSTANT_NameAndType_info", "tag name_index descriptor_index" ), NameAndType ], 1 : [ "CONSTANT_Utf8", '>BH', namedtuple( "CONSTANT_Utf8_info", "tag length" ), Utf8 ] } INVERT_CONSTANT_INFO = dict([( CONSTANT_INFO[k][0], k ) for k in CONSTANT_INFO]) ITEM_Top = 0 ITEM_Integer = 1 ITEM_Float = 2 ITEM_Long = 4 ITEM_Double = 3 ITEM_Null = 5 ITEM_UninitializedThis = 6 ITEM_Object = 7 ITEM_Uninitialized = 8 VERIFICATION_TYPE_INFO = { ITEM_Top : [ "Top_variable_info", '>B', namedtuple( "Top_variable_info", "tag" ) ], ITEM_Integer : [ "Integer_variable_info", '>B', namedtuple( "Integer_variable_info", "tag" ) ], ITEM_Float : [ "Float_variable_info", '>B', namedtuple( "Float_variable_info", "tag" ) ], ITEM_Long : [ "Long_variable_info", '>B', namedtuple( "Long_variable_info", "tag" ) ], ITEM_Double : [ "Double_variable_info", '>B', namedtuple( "Double_variable_info", "tag" ) ], ITEM_Null : [ "Null_variable_info", '>B', namedtuple( "Null_variable_info", "tag" ) ], ITEM_UninitializedThis : [ "UninitializedThis_variable_info", '>B', namedtuple( "UninitializedThis_variable_info", "tag" ) ], ITEM_Object : [ "Object_variable_info", '>BH', namedtuple( "Object_variable_info", "tag cpool_index" ), [ ("cpool_index", "get_class") ] ], ITEM_Uninitialized : [ "Uninitialized_variable_info", '>BH', namedtuple( "Uninitialized_variable_info", "tag offset" ) ], } class FieldInfo : """An object which represents a Field""" def __init__(self, class_manager, buff) : self.__raw_buff = buff.read( calcsize( FIELD_INFO[0] ) ) self.format = SVs( FIELD_INFO[0], FIELD_INFO[1], self.__raw_buff ) self.__CM = class_manager self.__attributes = [] for i in range(0, self.format.get_value().attributes_count) : ai = AttributeInfo( self.__CM, buff ) self.__attributes.append( ai ) def get_raw(self) : return self.__raw_buff + ''.join(x.get_raw() for x in self.__attributes) def get_length(self) : val = 0 for i in self.__attributes : val += i.length return val + calcsize( FIELD_INFO[0] ) def get_access(self) : try : return ACC_FIELD_FLAGS[ self.format.get_value().access_flags ][0] except KeyError : ok = True access = "" for i in ACC_FIELD_FLAGS : if (i & self.format.get_value().access_flags) == i : access += ACC_FIELD_FLAGS[ i ][0] + " " ok = False if ok == False : return access[:-1] return "ACC_PRIVATE" def set_access(self, value) : self.format.set_value( { "access_flags" : value } ) def get_class_name(self) : return self.__CM.get_this_class_name() def get_name(self) : return self.__CM.get_string( self.format.get_value().name_index ) def set_name(self, name) : return self.__CM.set_string( self.format.get_value().name_index, name ) def get_descriptor(self) : return self.__CM.get_string( self.format.get_value().descriptor_index ) def set_descriptor(self, name) : return self.__CM.set_string( self.format.get_value().descriptor_index, name ) def get_attributes(self) : return self.__attributes def get_name_index(self) : return self.format.get_value().name_index def get_descriptor_index(self) : return self.format.get_value().descriptor_index def show(self) : print self.format.get_value(), self.get_name(), self.get_descriptor() for i in self.__attributes : i.show() class MethodInfo : """An object which represents a Method""" def __init__(self, class_manager, buff) : self.format = SVs( METHOD_INFO[0], METHOD_INFO[1], buff.read( calcsize( METHOD_INFO[0] ) ) ) self.__CM = class_manager self.__code = None self.__attributes = [] for i in range(0, self.format.get_value().attributes_count) : ai = AttributeInfo( self.__CM, buff ) self.__attributes.append( ai ) if ai.get_name() == "Code" : self.__code = ai def get_raw(self) : return self.format.get_value_buff() + ''.join(x.get_raw() for x in self.__attributes) def get_length(self) : val = 0 for i in self.__attributes : val += i.length return val + calcsize( METHOD_INFO[0] ) def get_attributes(self) : return self.__attributes def get_access(self) : return ACC_METHOD_FLAGS[ self.format.get_value().access_flags ][0] def set_access(self, value) : self.format.set_value( { "access_flags" : value } ) def get_name(self) : return self.__CM.get_string( self.format.get_value().name_index ) def set_name(self, name) : return self.__CM.set_string( self.format.get_value().name_index, name ) def get_descriptor(self) : return self.__CM.get_string( self.format.get_value().descriptor_index ) def set_descriptor(self, name) : return self.__CM.set_string( self.format.get_value().name_descriptor, name ) def get_name_index(self) : return self.format.get_value().name_index def get_descriptor_index(self) : return self.format.get_value().descriptor_index def get_local_variables(self) : return self.get_code().get_local_variables() def get_code(self) : if self.__code == None : return None return self.__code.get_item() def set_name_index(self, name_index) : self.format.set_value( { "name_index" : name_index } ) def set_descriptor_index(self, descriptor_index) : self.format.set_value( { "descriptor_index" : descriptor_index } ) def get_class_name(self) : return self.__CM.get_this_class_name() def set_cm(self, cm) : self.__CM = cm for i in self.__attributes : i.set_cm( cm ) def with_descriptor(self, descriptor) : return descriptor == self.__CM.get_string( self.format.get_value().descriptor_index ) def _patch_bytecodes(self) : return self.get_code()._patch_bytecodes() def show(self) : print "*" * 80 print self.format.get_value(), self.get_class_name(), self.get_name(), self.get_descriptor() for i in self.__attributes : i.show() print "*" * 80 def pretty_show(self, vm_a) : print "*" * 80 print self.format.get_value(), self.get_class_name(), self.get_name(), self.get_descriptor() for i in self.__attributes : i.pretty_show(vm_a.hmethods[ self ]) print "*" * 80 class CreateString : """Create a specific String constant by given the name index""" def __init__(self, class_manager, bytes) : self.__string_index = class_manager.add_string( bytes ) def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_String" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__string_index ) return buff class CreateInteger : """Create a specific Integer constant by given the name index""" def __init__(self, byte) : self.__byte = byte def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_Integer" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__byte ) return buff class CreateClass : """Create a specific Class constant by given the name index""" def __init__(self, class_manager, name_index) : self.__CM = class_manager self.__name_index = name_index def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_Class" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__name_index ) return buff class CreateNameAndType : """Create a specific NameAndType constant by given the name and the descriptor index""" def __init__(self, class_manager, name_index, descriptor_index) : self.__CM = class_manager self.__name_index = name_index self.__descriptor_index = descriptor_index def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_NameAndType" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__name_index, self.__descriptor_index ) return buff class CreateFieldRef : """Create a specific FieldRef constant by given the class and the NameAndType index""" def __init__(self, class_manager, class_index, name_and_type_index) : self.__CM = class_manager self.__class_index = class_index self.__name_and_type_index = name_and_type_index def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_Fieldref" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__class_index, self.__name_and_type_index ) return buff class CreateMethodRef : """Create a specific MethodRef constant by given the class and the NameAndType index""" def __init__(self, class_manager, class_index, name_and_type_index) : self.__CM = class_manager self.__class_index = class_index self.__name_and_type_index = name_and_type_index def get_raw(self) : tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_Methodref" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, self.__class_index, self.__name_and_type_index ) return buff class CreateCodeAttributeInfo : """Create a specific CodeAttributeInfo by given bytecodes (into an human readable format)""" def __init__(self, class_manager, codes) : self.__CM = class_manager #ATTRIBUTE_INFO = [ '>HL', namedtuple("AttributeInfo", "attribute_name_index attribute_length") ] self.__attribute_name_index = self.__CM.get_string_index( "Code" ) self.__attribute_length = 0 ######## # CODE_LOW_STRUCT = [ '>HHL', namedtuple( "LOW", "max_stack max_locals code_length" ) ] self.__max_stack = 1 self.__max_locals = 2 self.__code_length = 0 ######## # CODE raw_buff = "" for i in codes : op_name = i[0] op_value = INVERT_JAVA_OPCODES[ op_name ] raw_buff += pack( '>B', op_value ) if len( JAVA_OPCODES[ op_value ] ) > 1 : r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) raw_buff += pack(r_format, *v_function( *i[1:] ) ) self.__code = JavaCode( self.__CM, raw_buff ) self.__code_length = len( raw_buff ) ######## # EXCEPTION # u2 exception_table_length; self.__exception_table_length = 0 # { u2 start_pc; # u2 end_pc; # u2 handler_pc; # u2 catch_type; # } exception_table[exception_table_length]; self.__exception_table = [] ######## # ATTRIBUTES # u2 attributes_count; self.__attributes_count = 0 # attribute_info attributes[attributes_count]; self.__attributes = [] ######## # FIXME : remove calcsize self.__attribute_length = calcsize( ATTRIBUTE_INFO[0] ) + \ calcsize( CODE_LOW_STRUCT[0] ) + \ self.__code_length + \ calcsize('>H') + \ calcsize('>H') def get_raw(self) : return pack( ATTRIBUTE_INFO[0], self.__attribute_name_index, self.__attribute_length ) + \ pack( CODE_LOW_STRUCT[0], self.__max_stack, self.__max_locals, self.__code_length ) + \ self.__code.get_raw() + \ pack( '>H', self.__exception_table_length ) + \ ''.join( i.get_raw() for i in self.__exception_table ) + \ pack( '>H', self.__attributes_count ) + \ ''.join( i.get_raw() for i in self.__attributes ) # FIELD_INFO = [ '>HHHH', namedtuple("FieldInfo", "access_flags name_index descriptor_index attributes_count") ] class CreateFieldInfo : """Create a specific FieldInfo by given the name, the prototype of the "new" field""" def __init__(self, class_manager, name, proto) : self.__CM = class_manager access_flags_value = proto[0] type_value = proto[1] self.__access_flags = INVERT_ACC_FIELD_FLAGS[ access_flags_value ] self.__name_index = self.__CM.get_string_index( name ) if self.__name_index == -1 : self.__name_index = self.__CM.add_string( name ) else : bytecode.Exit("field %s is already present ...." % name) self.__descriptor_index = self.__CM.add_string( type_value ) self.__attributes = [] def get_raw(self) : buff = pack( FIELD_INFO[0], self.__access_flags, self.__name_index, self.__descriptor_index, len(self.__attributes) ) for i in self.__attributes : buff += i.get_raw() return buff # METHOD_INFO = [ '>HHHH', namedtuple("MethodInfo", "access_flags name_index descriptor_index attributes_count") ] class CreateMethodInfo : """Create a specific MethodInfo by given the name, the prototype and the code (into an human readable format) of the "new" method""" def __init__(self, class_manager, name, proto, codes) : self.__CM = class_manager access_flags_value = proto[0] return_value = proto[1] arguments_value = proto[2] self.__access_flags = INVERT_ACC_METHOD_FLAGS[ access_flags_value ] self.__name_index = self.__CM.get_string_index( name ) if self.__name_index == -1 : self.__name_index = self.__CM.add_string( name ) proto_final = "(" + arguments_value + ")" + return_value self.__descriptor_index = self.__CM.add_string( proto_final ) self.__attributes = [] self.__attributes.append( CreateCodeAttributeInfo( self.__CM, codes ) ) def get_raw(self) : buff = pack( METHOD_INFO[0], self.__access_flags, self.__name_index, self.__descriptor_index, len(self.__attributes) ) for i in self.__attributes : buff += i.get_raw() return buff class JBC : """JBC manages each bytecode with the value, name, raw buffer and special functions""" # special --> ( r_function, v_function, r_buff, r_format, f_function ) def __init__(self, class_manager, op_name, raw_buff, special=None) : self.__CM = class_manager self.__op_name = op_name self.__raw_buff = raw_buff self.__special = special self.__special_value = None self._load() def _load(self) : if self.__special != None : ntuple = namedtuple( self.__op_name, self.__special[2] ) x = ntuple._make( unpack( self.__special[3], self.__raw_buff[1:] ) ) if self.__special[4] == None : self.__special_value = self.__special[0]( x ) else : self.__special_value = getattr(self.__CM, self.__special[4])( self.__special[0]( x ) ) def reload(self, raw_buff) : """Reload the bytecode with a new raw buffer""" self.__raw_buff = raw_buff self._load() def set_cm(self, cm) : self.__CM = cm def get_length(self) : """Return the length of the bytecode""" return len( self.__raw_buff ) def get_raw(self) : """Return the current raw buffer of the bytecode""" return self.__raw_buff def get_name(self) : """Return the name of the bytecode""" return self.__op_name def get_operands(self) : """Return the operands of the bytecode""" if isinstance( self.__special_value, list ): if len(self.__special_value) == 1 : return self.__special_value[0] return self.__special_value def get_formatted_operands(self) : return [] def adjust_r(self, pos, pos_modif, len_modif) : """Adjust the bytecode (if necessary (in this cas the bytecode is a branch bytecode)) when a bytecode has been removed""" # print self.__op_name, pos, pos_modif, len_modif, self.__special_value, type(pos), type(pos_modif), type(len_modif), type(self.__special_value) if pos > pos_modif : if (self.__special_value + pos) < (pos_modif) : # print "MODIF +", self.__special_value, len_modif, self.__special_value += len_modif # print self.__special_value self.__raw_buff = pack( '>B', INVERT_JAVA_OPCODES[ self.__op_name ] ) + pack(self.__special[3], *self.__special[1]( self.__special_value ) ) elif pos < pos_modif : if (self.__special_value + pos) > (pos_modif) : # print "MODIF -", self.__special_value, len_modif, self.__special_value -= len_modif # print self.__special_value self.__raw_buff = pack( '>B', INVERT_JAVA_OPCODES[ self.__op_name ] ) + pack(self.__special[3], *self.__special[1]( self.__special_value ) ) def adjust_i(self, pos, pos_modif, len_modif) : """Adjust the bytecode (if necessary (in this cas the bytecode is a branch bytecode)) when a bytecode has been inserted""" #print self.__op_name, pos, pos_modif, len_modif, self.__special_value, type(pos), type(pos_modif), type(len_modif), type(self.__special_value) if pos > pos_modif : if (self.__special_value + pos) < (pos_modif) : # print "MODIF +", self.__special_value, len_modif, self.__special_value -= len_modif # print self.__special_value self.__raw_buff = pack( '>B', INVERT_JAVA_OPCODES[ self.__op_name ] ) + pack(self.__special[3], *self.__special[1]( self.__special_value ) ) elif pos < pos_modif : if (self.__special_value + pos) > (pos_modif) : # print "MODIF -", self.__special_value, len_modif, self.__special_value += len_modif # print self.__special_value self.__raw_buff = pack( '>B', INVERT_JAVA_OPCODES[ self.__op_name ] ) + pack(self.__special[3], *self.__special[1]( self.__special_value ) ) def show_buff(self, pos) : buff = "" if self.__special_value == None : buff += self.__op_name else : if self.__op_name in BRANCH_JVM_OPCODES : buff += "%s %s %s" % (self.__op_name, self.__special_value, self.__special_value + pos) else : buff += "%s %s" % (self.__op_name, self.__special_value) return buff def show(self, pos) : """Show the bytecode at a specific position pos - the position into the bytecodes (integer) """ print self.show_buff( pos ), class JavaCode : """JavaCode manages a list of bytecode to a specific method, by decoding a raw buffer and transform each bytecode into a JBC object""" def __init__(self, class_manager, buff) : self.__CM = class_manager self.__raw_buff = buff self.__bytecodes = [] self.__maps = [] self.__branches = [] i = 0 while i < len(self.__raw_buff) : op_value = unpack( '>B', self.__raw_buff[i])[0] if op_value in JAVA_OPCODES : if len( JAVA_OPCODES[ op_value ] ) >= 2 : # it's a fixed length opcode if isinstance(JAVA_OPCODES[ op_value ][1], str) == True : r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) # it's a variable length opcode else : r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_VARIABLE( i, op_value, self.__raw_buff[ i : ] ) len_format = calcsize(r_format) raw_buff = self.__raw_buff[ i : i + 1 + len_format ] jbc = JBC( class_manager, JAVA_OPCODES[ op_value ][0], raw_buff, ( r_function, v_function, r_buff, r_format, f_function ) ) self.__bytecodes.append( jbc ) i += len_format else : self.__bytecodes.append( JBC( class_manager, JAVA_OPCODES[ op_value ][0], self.__raw_buff[ i ] ) ) else : bytecode.Exit( "op_value 0x%x is unknown" % op_value ) i += 1 # Create branch bytecodes list idx = 0 nb = 0 for i in self.__bytecodes : self.__maps.append( idx ) if i.get_name() in BRANCH_JVM_OPCODES : self.__branches.append( nb ) idx += i.get_length() nb += 1 def _patch_bytecodes(self) : methods = [] for i in self.__bytecodes : if "invoke" in i.get_name() : operands = i.get_operands() methods.append( operands ) op_value = INVERT_JAVA_OPCODES[ i.get_name() ] raw_buff = pack( '>B', op_value ) r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) new_class_index = self.__CM.create_class( operands[0] ) new_name_and_type_index = self.__CM.create_name_and_type( operands[1], operands[2] ) self.__CM.create_method_ref( new_class_index, new_name_and_type_index ) value = getattr( self.__CM, JAVA_OPCODES[ op_value ][5] )( *operands[0:] ) if value == -1 : bytecode.Exit( "Unable to found method " + str(operands) ) raw_buff += pack(r_format, *v_function( value ) ) i.reload( raw_buff ) elif "anewarray" in i.get_name() : operands = i.get_operands() op_value = INVERT_JAVA_OPCODES[ i.get_name() ] raw_buff = pack( '>B', op_value ) r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) new_class_index = self.__CM.create_class( operands ) raw_buff += pack(r_format, *v_function( new_class_index ) ) i.reload( raw_buff ) elif "getstatic" == i.get_name() : operands = i.get_operands() op_value = INVERT_JAVA_OPCODES[ i.get_name() ] raw_buff = pack( '>B', op_value ) r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) new_class_index = self.__CM.create_class( operands[0] ) new_name_and_type_index = self.__CM.create_name_and_type( operands[1], operands[2] ) self.__CM.create_field_ref( new_class_index, new_name_and_type_index ) value = getattr( self.__CM, JAVA_OPCODES[ op_value ][5] )( *operands[1:] ) if value == -1 : bytecode.Exit( "Unable to found method " + str(operands) ) raw_buff += pack(r_format, *v_function( value ) ) i.reload( raw_buff ) elif "ldc" == i.get_name() : operands = i.get_operands() op_value = INVERT_JAVA_OPCODES[ i.get_name() ] raw_buff = pack( '>B', op_value ) r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) if operands[0] != "CONSTANT_Integer" and operands[0] != "CONSTANT_String" : bytecode.Exit( "...." ) if operands[0] == "CONSTANT_Integer" : new_int_index = self.__CM.create_integer( operands[1] ) raw_buff += pack(r_format, *v_function( new_int_index ) ) elif operands[0] == "CONSTANT_String" : new_string_index = self.__CM.create_string( operands[1] ) raw_buff += pack(r_format, *v_function( new_string_index ) ) i.reload( raw_buff ) elif "new" == i.get_name() : operands = i.get_operands() op_value = INVERT_JAVA_OPCODES[ i.get_name() ] raw_buff = pack( '>B', op_value ) r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) new_class_index = self.__CM.create_class( operands ) raw_buff += pack(r_format, *v_function( new_class_index ) ) i.reload( raw_buff ) return methods def get(self) : """ Return all bytecodes @rtype : L{list} """ return self.__bytecodes def get_raw(self) : return ''.join(x.get_raw() for x in self.__bytecodes) def show(self) : """ Display the code like a disassembler """ nb = 0 for i in self.__bytecodes : print nb, self.__maps[nb], i.show( self.__maps[nb] ) print nb += 1 def pretty_show(self, m_a) : """ Display the code like a disassembler but with instructions' links """ bytecode.PrettyShow( m_a.basic_blocks.gets() ) bytecode.PrettyShowEx( m_a.exceptions.gets() ) def get_relative_idx(self, idx) : """ Return the relative idx by given an offset in the code @param idx : an offset in the code @rtype : the relative index in the code, it's the position in the list of a bytecode """ n = 0 x = 0 for i in self.__bytecodes : #print n, idx if n == idx : return x n += i.get_length() x += 1 return -1 def get_at(self, idx) : """ Return a specific bytecode at an index @param : the index of a bytecode @rtype : L{JBC} """ return self.__bytecodes[ idx ] def remove_at(self, idx) : """ Remove bytecode at a specific index @param idx : the index to remove the bytecode @rtype : the length of the removed bytecode """ val = self.__bytecodes[idx] val_m = self.__maps[idx] # Remove the index if it's in our branch list if idx in self.__branches : self.__branches.remove( idx ) # Adjust each branch for i in self.__branches : self.__bytecodes[i].adjust_r( self.__maps[i], val_m, val.get_length() ) # Remove it ! self.__maps.pop(idx) self.__bytecodes.pop(idx) # Adjust branch and map list self._adjust_maps( val_m, val.get_length() * -1 ) self._adjust_branches( idx, -1 ) return val.get_length() def _adjust_maps(self, val, size) : nb = 0 for i in self.__maps : if i > val : self.__maps[ nb ] = i + size nb = nb + 1 def _adjust_maps_i(self, val, size) : nb = 0 x = 0 for i in self.__maps : if i == val : x+=1 if x == 2 : self.__maps[ nb ] = i + size if i > val : self.__maps[ nb ] = i + size nb = nb + 1 def _adjust_branches(self, val, size) : nb = 0 for i in self.__branches : if i > val : self.__branches[ nb ] = i + size nb += 1 def insert_at(self, idx, byte_code) : """ Insert bytecode at a specific index @param idx : the index to insert the bytecode @param bytecode : a list which represent the bytecode @rtype : the length of the inserted bytecode """ # Get the op_value and add it to the raw_buff op_name = byte_code[0] op_value = INVERT_JAVA_OPCODES[ op_name ] raw_buff = pack( '>B', op_value ) new_jbc = None # If it's an op_value with args, we must handle that ! if len( JAVA_OPCODES[ op_value ] ) > 1 : # Find information about the op_value r_function, v_function, r_buff, r_format, f_function = EXTRACT_INFORMATION_SIMPLE( op_value ) # Special values for this op_value (advanced bytecode) if len( JAVA_OPCODES[ op_value ] ) == 6 : value = getattr( self.__CM, JAVA_OPCODES[ op_value ][5] )( *byte_code[1:] ) if value == -1 : bytecode.Exit( "Unable to found " + str(byte_code[1:]) ) raw_buff += pack(r_format, *v_function( value ) ) else : raw_buff += pack(r_format, *v_function( *byte_code[1:] ) ) new_jbc = JBC(self.__CM, op_name, raw_buff, ( r_function, v_function, r_buff, r_format, f_function ) ) else : new_jbc = JBC(self.__CM, op_name, raw_buff) # Adjust each branch with the new insertion val_m = self.__maps[ idx ] for i in self.__branches : self.__bytecodes[i].adjust_i( self.__maps[i], val_m, new_jbc.get_length() ) # Insert the new bytecode at the correct index # Adjust maps + branches self.__bytecodes.insert( idx, new_jbc ) self.__maps.insert( idx, val_m ) self._adjust_maps_i( val_m, new_jbc.get_length() ) self._adjust_branches( idx, 1 ) # Add it to the branches if it's a correct op_value if new_jbc.get_name() in BRANCH_JVM_OPCODES : self.__branches.append( idx ) # FIXME # modify the exception table # modify tableswitch and lookupswitch instructions # return the length of the raw_buff return len(raw_buff) def remplace_at(self, idx, bytecode) : """ Remplace bytecode at a specific index by another bytecode (remplace = remove + insert) @param idx : the index to insert the bytecode @param bytecode : a list which represent the bytecode @rtype : the length of the inserted bytecode """ self.remove_at(idx) * (-1) size = self.insert_at(idx, bytecode) return size def set_cm(self, cm) : self.__CM = cm for i in self.__bytecodes : i.set_cm( cm ) class BasicAttribute(object) : def __init__(self) : self.__attributes = [] def get_attributes(self) : return self.__attributes def set_cm(self, cm) : self.__CM = cm class CodeAttribute(BasicAttribute) : def __init__(self, class_manager, buff) : self.__CM = class_manager super(CodeAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 max_stack; # u2 max_locals; # u4 code_length; # u1 code[code_length]; self.low_struct = SVs( CODE_LOW_STRUCT[0], CODE_LOW_STRUCT[1], buff.read( calcsize(CODE_LOW_STRUCT[0]) ) ) self.__code = JavaCode( class_manager, buff.read( self.low_struct.get_value().code_length ) ) # u2 exception_table_length; self.exception_table_length = SV( '>H', buff.read(2) ) # { u2 start_pc; # u2 end_pc; # u2 handler_pc; # u2 catch_type; # } exception_table[exception_table_length]; self.__exception_table = [] for i in range(0, self.exception_table_length.get_value()) : et = SVs( EXCEPTION_TABLE[0], EXCEPTION_TABLE[1], buff.read( calcsize(EXCEPTION_TABLE[0]) ) ) self.__exception_table.append( et ) # u2 attributes_count; self.attributes_count = SV( '>H', buff.read(2) ) # attribute_info attributes[attributes_count]; self.__attributes = [] for i in range(0, self.attributes_count.get_value()) : ai = AttributeInfo( self.__CM, buff ) self.__attributes.append( ai ) def get_attributes(self) : return self.__attributes def get_exceptions(self) : return self.__exception_table def get_raw(self) : return self.low_struct.get_value_buff() + \ self.__code.get_raw() + \ self.exception_table_length.get_value_buff() + \ ''.join(x.get_value_buff() for x in self.__exception_table) + \ self.attributes_count.get_value_buff() + \ ''.join(x.get_raw() for x in self.__attributes) def get_length(self) : return self.low_struct.get_value().code_length def get_max_stack(self) : return self.low_struct.get_value().max_stack def get_max_locals(self) : return self.low_struct.get_value().max_locals def get_local_variables(self) : for i in self.__attributes : if i.get_name() == "StackMapTable" : return i.get_item().get_local_variables() return [] def get_bc(self) : return self.__code # FIXME : show* --> add exceptions def show_info(self) : print "!" * 70 print self.low_struct.get_value() bytecode._Print( "ATTRIBUTES_COUNT", self.attributes_count.get_value() ) for i in self.__attributes : i.show() print "!" * 70 def _begin_show(self) : print "!" * 70 print self.low_struct.get_value() def _end_show(self) : bytecode._Print( "ATTRIBUTES_COUNT", self.attributes_count.get_value() ) for i in self.__attributes : i.show() print "!" * 70 def show(self) : self._begin_show() self.__code.show() self._end_show() def pretty_show(self, m_a) : self._begin_show() self.__code.pretty_show(m_a) self._end_show() def _patch_bytecodes(self) : return self.__code._patch_bytecodes() def remplace_at(self, idx, bytecode) : size = self.__code.remplace_at(idx, bytecode) # Adjust the length of our bytecode self.low_struct.set_value( { "code_length" : self.low_struct.get_value().code_length + size } ) def remove_at(self, idx) : size = self.__code.remove_at(idx) # Adjust the length of our bytecode self.low_struct.set_value( { "code_length" : self.low_struct.get_value().code_length - size } ) def removes_at(self, l_idx) : i = 0 while i < len(l_idx) : self.remove_at( l_idx[i] ) j = i + 1 while j < len(l_idx) : if l_idx[j] > l_idx[i] : l_idx[j] -= 1 j += 1 i += 1 def inserts_at(self, idx, l_bc) : # self.low_struct.set_value( { "max_stack" : self.low_struct.get_value().max_stack + 2 } ) # print self.low_struct.get_value() total_size = 0 for i in l_bc : size = self.insert_at( idx, i ) idx += 1 total_size += size return total_size def insert_at(self, idx, bytecode) : size = self.__code.insert_at(idx, bytecode) # Adjust the length of our bytecode self.low_struct.set_value( { "code_length" : self.low_struct.get_value().code_length + size } ) return size def get_relative_idx(self, idx) : return self.__code.get_relative_idx(idx) def get_at(self, idx) : return self.__code.get_at(idx) def gets_at(self, l_idx) : return [ self.__code.get_at(i) for i in l_idx ] def set_cm(self, cm) : self.__CM = cm for i in self.__attributes : i.set_cm( cm ) self.__code.set_cm( cm ) def _fix_attributes(self, new_cm) : for i in self.__attributes : i._fix_attributes( new_cm ) class SourceFileAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(SourceFileAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 sourcefile_index; self.sourcefile_index = SV( '>H', buff.read(2) ) def get_raw(self) : return self.sourcefile_index.get_value_buff() def show(self) : print self.sourcefile_index class LineNumberTableAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(LineNumberTableAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 line_number_table_length; # { u2 start_pc; # u2 line_number; # } line_number_table[line_number_table_length]; self.line_number_table_length = SV( '>H', buff.read( 2 ) ) self.__line_number_table = [] for i in range(0, self.line_number_table_length.get_value()) : lnt = SVs( LINE_NUMBER_TABLE[0], LINE_NUMBER_TABLE[1], buff.read( 4 ) ) self.__line_number_table.append( lnt ) def get_raw(self) : return self.line_number_table_length.get_value_buff() + \ ''.join(x.get_value_buff() for x in self.__line_number_table) def get_line_number_table(self) : return self.__line_number_table def show(self) : bytecode._Print("LINE_NUMBER_TABLE_LENGTH", self.line_number_table_length.get_value()) for x in self.__line_number_table : print "\t", x.get_value() def _fix_attributes(self, new_cm) : pass class LocalVariableTableAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(LocalVariableTableAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 local_variable_table_length; # { u2 start_pc; # u2 length; # u2 name_index; # u2 descriptor_index; # u2 index; # } local_variable_table[local_variable_table_length]; self.local_variable_table_length = SV( '>H', buff.read(2) ) self.local_variable_table = [] for i in range(0, self.local_variable_table_length.get_value()) : lvt = SVs( LOCAL_VARIABLE_TABLE[0], LOCAL_VARIABLE_TABLE[1], buff.read( calcsize(LOCAL_VARIABLE_TABLE[0]) ) ) self.local_variable_table.append( lvt ) def get_raw(self) : return self.local_variable_table_length.get_value_buff() + \ ''.join(x.get_value_buff() for x in self.local_variable_table) def show(self) : print "LocalVariableTable", self.local_variable_table_length.get_value() for x in self.local_variable_table : print x.get_value() class LocalVariableTypeTableAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(LocalVariableTypeTableAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 local_variable_type_table_length; # { u2 start_pc; # u2 length; # u2 name_index; # u2 signature_index; # u2 index; # } local_variable_type_table[local_variable_type_table_length]; self.local_variable_type_table_length = SV( '>H', buff.read(2) ) self.local_variable_type_table = [] for i in range(0, self.local_variable_type_table_length.get_value()) : lvtt = SVs( LOCAL_VARIABLE_TYPE_TABLE[0], LOCAL_VARIABLE_TYPE_TABLE[1], buff.read( calcsize(LOCAL_VARIABLE_TYPE_TABLE[0]) ) ) self.local_variable_type_table.append( lvtt ) def get_raw(self) : return self.local_variable_type_table_length.get_value_buff() + \ ''.join(x.get_value_buff() for x in self.local_variable_type_table) def show(self) : print "LocalVariableTypeTable", self.local_variable_type_table_length.get_value() for x in self.local_variable_type_table : print x.get_value() class SourceDebugExtensionAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(SourceDebugExtensionAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u1 debug_extension[attribute_length]; self.debug_extension = buff.read( self.attribute_length ) def get_raw(self) : return self.debug_extension def show(self) : print "SourceDebugExtension", self.debug_extension.get_value() class DeprecatedAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(DeprecatedAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; def get_raw(self) : return '' def show(self) : print "Deprecated" class SyntheticAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(SyntheticAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; def get_raw(self) : return '' def show(self) : print "Synthetic" class SignatureAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(SignatureAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 signature_index; self.signature_index = SV( '>H', buff.read(2) ) def get_raw(self) : return self.signature_index.get_value_buff() def show(self) : print "Signature", self.signature_index.get_value() class RuntimeVisibleAnnotationsAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(RuntimeVisibleAnnotationsAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 num_annotations; # annotation annotations[num_annotations]; self.num_annotations = SV( '>H', buff.read(2) ) self.annotations = [] for i in range(0, self.num_annotations.get_value()) : self.annotations.append( Annotation(cm, buff) ) def get_raw(self) : return self.num_annotations.get_value_buff() + \ ''.join(x.get_raw() for x in self.annotations) def show(self) : print "RuntimeVisibleAnnotations", self.num_annotations.get_value() for i in self.annotations : i.show() class RuntimeInvisibleAnnotationsAttribute(RuntimeVisibleAnnotationsAttribute) : def show(self) : print "RuntimeInvisibleAnnotations", self.num_annotations.get_value() for i in self.annotations : i.show() class RuntimeVisibleParameterAnnotationsAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(RuntimeVisibleParameterAnnotationsAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u1 num_parameters; #{ # u2 num_annotations; # annotation annotations[num_annotations]; #} parameter_annotations[num_parameters]; self.num_parameters = SV( '>H', buff.read(2) ) self.parameter_annotations = [] for i in range(0, self.num_parameters.get_value()) : self.parameter_annotations.append( ParameterAnnotation( cm, buff ) ) def get_raw(self) : return self.num_parameters.get_value_buff() + \ ''.join(x.get_raw() for x in self.parameter_annotations) def show(self) : print "RuntimeVisibleParameterAnnotations", self.num_parameters.get_value() for i in self.parameter_annotations : i.show() class RuntimeInvisibleParameterAnnotationsAttribute(RuntimeVisibleParameterAnnotationsAttribute) : def show(self) : print "RuntimeVisibleParameterAnnotations", self.num_annotations.get_value() for i in self.parameter_annotations : i.show() class ParameterAnnotation : def __init__(self, cm, buff) : # u2 num_annotations; # annotation annotations[num_annotations]; self.num_annotations = SV( '>H', buff.read(2) ) self.annotations = [] for i in range(0, self.num_annotations.get_value()) : self.annotations = Annotation( cm, buff ) def get_raw(self) : return self.num_annotations.get_value_buff() + \ ''.join(x.get_raw() for x in self.annotations) def show(self) : print "ParameterAnnotation", self.num_annotations.get_value() for i in self.annotations : i.show() class AnnotationDefaultAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(AnnotationDefaultAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # element_value default_value; self.default_value = ElementValue( cm, buff ) def get_raw(self) : return self.default_value.get_raw() def show(self) : print "AnnotationDefault" self.default_value.show() class Annotation : def __init__(self, cm, buff) : # u2 type_index; # u2 num_element_value_pairs; # { u2 element_name_index; # element_value value; # } element_value_pairs[num_element_value_pairs] self.type_index = SV( '>H', buff.read(2) ) self.num_element_value_pairs = SV( '>H', buff.read(2) ) self.element_value_pairs = [] for i in range(0, self.num_element_value_pairs.get_value()) : self.element_value_pairs.append( ElementValuePair(cm, buff) ) def get_raw(self) : return self.type_index.get_value_buff() + self.num_element_value_pairs.get_value_buff() + \ ''.join(x.get_raw() for x in self.element_value_pairs) def show(self) : print "Annotation", self.type_index.get_value(), self.num_element_value_pairs.get_value() for i in self.element_value_pairs : i.show() class ElementValuePair : def __init__(self, cm, buff) : # u2 element_name_index; # element_value value; self.element_name_index = SV( '>H', buff.read(2) ) self.value = ElementValue(cm, buff) def get_raw(self) : return self.element_name_index.get_value_buff() + \ self.value.get_raw() def show(self) : print "ElementValuePair", self.element_name_index.get_value() self.value.show() ENUM_CONST_VALUE = [ '>HH', namedtuple("EnumConstValue", "type_name_index const_name_index") ] class ElementValue : def __init__(self, cm, buff) : # u1 tag; # union { # u2 const_value_index; # { # u2 type_name_index; # u2 const_name_index; # } enum_const_value; # u2 class_info_index; # annotation annotation_value; # { # u2 num_values; # element_value values[num_values]; # } array_value; # } value; self.tag = SV( '>B', buff.read(1) ) tag = chr( self.tag.get_value() ) if tag == 'B' or tag == 'C' or tag == 'D' or tag == 'F' or tag == 'I' or tag == 'J' or tag == 'S' or tag == 'Z' or tag == 's' : self.value = SV( '>H', buff.read(2) ) elif tag == 'e' : self.value = SVs( ENUM_CONST_VALUE[0], ENUM_CONST_VALUE[1], buff.read( calcsize(ENUM_CONST_VALUE[0]) ) ) elif tag == 'c' : self.value = SV( '>H', buff.read(2) ) elif tag == '@' : self.value = Annotation( cm, buff ) elif tag == '[' : self.value = ArrayValue( cm, buff ) else : bytecode.Exit( "tag %c not in VERIFICATION_TYPE_INFO" % self.tag.get_value() ) def get_raw(self) : if isinstance(self.value, SV) or isinstance(self.value, SVs) : return self.tag.get_value_buff() + self.value.get_value_buff() return self.tag.get_value_buff() + self.value.get_raw() def show(self) : print "ElementValue", self.tag.get_value() if isinstance(self.value, SV) or isinstance(self.value, SVs) : print self.value.get_value() else : self.value.show() class ArrayValue : def __init__(self, cm, buff) : # u2 num_values; # element_value values[num_values]; self.num_values = SV( '>H', buff.read(2) ) self.values = [] for i in range(0, self.num_values.get_value()) : self.values.append( ElementValue(cm, buff) ) def get_raw(self) : return self.num_values.get_value_buff() + \ ''.join(x.get_raw() for x in self.values) def show(self) : print "ArrayValue", self.num_values.get_value() for i in self.values : i.show() class ExceptionsAttribute(BasicAttribute) : def __init__(self, cm, buff) : super(ExceptionsAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 number_of_exceptions; # u2 exception_index_table[number_of_exceptions]; self.number_of_exceptions = SV( '>H', buff.read(2) ) self.__exception_index_table = [] for i in range(0, self.number_of_exceptions.get_value()) : self.__exception_index_table.append( SV( '>H', buff.read(2) ) ) def get_raw(self) : return self.number_of_exceptions.get_value_buff() + ''.join(x.get_value_buff() for x in self.__exception_index_table) def get_exception_index_table(self) : return self.__exception_index_table def show(self) : print "Exceptions", self.number_of_exceptions.get_value() for i in self.__exception_index_table : print "\t", i class VerificationTypeInfo : def __init__(self, class_manager, buff) : self.__CM = class_manager tag = SV( '>B', buff.read_b(1) ).get_value() if tag not in VERIFICATION_TYPE_INFO : bytecode.Exit( "tag not in VERIFICATION_TYPE_INFO" ) format = VERIFICATION_TYPE_INFO[ tag ][1] self.format = SVs( format, VERIFICATION_TYPE_INFO[ tag ][2], buff.read( calcsize( format ) ) ) def get_raw(self) : return self.format.get_value_buff() def show(self) : general_format = self.format.get_value() if len( VERIFICATION_TYPE_INFO[ general_format.tag ] ) > 3 : print general_format, for (i,j) in VERIFICATION_TYPE_INFO[ general_format.tag ][3] : print getattr(self.__CM, j)( getattr(general_format, i) ) else : print general_format def _fix_attributes(self, new_cm) : general_format = self.format.get_value() if len( VERIFICATION_TYPE_INFO[ general_format.tag ] ) > 3 : for (i,j) in VERIFICATION_TYPE_INFO[ general_format.tag ][3] : # Fix the first object which is the current class if getattr(self.__CM, j)( getattr(general_format, i) )[0] == self.__CM.get_this_class_name() : self.format.set_value( { "cpool_index" : new_cm.get_this_class() } ) # Fix other objects else : new_class_index = new_cm.create_class( getattr(self.__CM, j)( getattr(general_format, i) )[0] ) self.format.set_value( { "cpool_index" : new_class_index } ) def set_cm(self, cm) : self.__CM = cm class FullFrame : def __init__(self, class_manager, buff) : self.__CM = class_manager # u1 frame_type = FULL_FRAME; /* 255 */ # u2 offset_delta; # u2 number_of_locals; self.frame_type = SV( '>B', buff.read(1) ) self.offset_delta = SV( '>H', buff.read(2) ) self.number_of_locals = SV( '>H', buff.read(2) ) # verification_type_info locals[number_of_locals]; self.__locals = [] for i in range(0, self.number_of_locals.get_value()) : self.__locals.append( VerificationTypeInfo( self.__CM, buff ) ) # u2 number_of_stack_items; self.number_of_stack_items = SV( '>H', buff.read(2) ) # verification_type_info stack[number_of_stack_items]; self.__stack = [] for i in range(0, self.number_of_stack_items.get_value()) : self.__stack.append( VerificationTypeInfo( self.__CM, buff ) ) def get_locals(self) : return self.__locals def get_raw(self) : return self.frame_type.get_value_buff() + \ self.offset_delta.get_value_buff() + \ self.number_of_locals.get_value_buff() + \ ''.join(x.get_raw() for x in self.__locals) + \ self.number_of_stack_items.get_value_buff() + \ ''.join(x.get_raw() for x in self.__stack) def show(self) : print "#" * 60 bytecode._Print("\tFULL_FRAME", self.frame_type.get_value()) bytecode._Print("\tOFFSET_DELTA", self.offset_delta.get_value()) bytecode._Print("\tNUMBER_OF_LOCALS", self.number_of_locals.get_value()) for i in self.__locals : i.show() bytecode._Print("\tNUMBER_OF_STACK_ITEMS", self.number_of_stack_items.get_value()) for i in self.__stack : i.show() print "#" * 60 def _fix_attributes(self, new_cm) : for i in self.__locals : i._fix_attributes( new_cm ) def set_cm(self, cm) : self.__CM = cm for i in self.__locals : i.set_cm( cm ) class ChopFrame : def __init__(self, buff) : # u1 frame_type=CHOP; /* 248-250 */ # u2 offset_delta; self.frame_type = SV( '>B', buff.read(1) ) self.offset_delta = SV( '>H', buff.read(2) ) def get_raw(self) : return self.frame_type.get_value_buff() + self.offset_delta.get_value_buff() def show(self) : print "#" * 60 bytecode._Print("\tCHOP_FRAME", self.frame_type.get_value()) bytecode._Print("\tOFFSET_DELTA", self.offset_delta.get_value()) print "#" * 60 def _fix_attributes(self, cm) : pass def set_cm(self, cm) : pass class SameFrame : def __init__(self, buff) : # u1 frame_type = SAME;/* 0-63 */ self.frame_type = SV( '>B', buff.read(1) ) def get_raw(self) : return self.frame_type.get_value_buff() def show(self) : print "#" * 60 bytecode._Print("\tSAME_FRAME", self.frame_type.get_value()) print "#" * 60 def _fix_attributes(self, new_cm) : pass def set_cm(self, cm) : pass class SameLocals1StackItemFrame : def __init__(self, class_manager, buff) : self.__CM = class_manager # u1 frame_type = SAME_LOCALS_1_STACK_ITEM;/* 64-127 */ # verification_type_info stack[1]; self.frame_type = SV( '>B', buff.read(1) ) self.stack = VerificationTypeInfo( self.__CM, buff ) def show(self) : print "#" * 60 bytecode._Print("\tSAME_LOCALS_1_STACK_ITEM_FRAME", self.frame_type.get_value()) self.stack.show() print "#" * 60 def get_raw(self) : return self.frame_type.get_value_buff() + self.stack.get_raw() def _fix_attributes(self, new_cm) : pass def set_cm(self, cm) : self.__CM = cm class SameLocals1StackItemFrameExtended : def __init__(self, class_manager, buff) : self.__CM = class_manager # u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */ # u2 offset_delta; # verification_type_info stack[1]; self.frame_type = SV( '>B', buff.read(1) ) self.offset_delta = SV( '>H', buff.read(2) ) self.stack = VerificationTypeInfo( self.__CM, buff ) def get_raw(self) : return self.frame_type.get_value_buff() + self.offset_delta.get_value_buff() + self.stack.get_value_buff() def _fix_attributes(self, new_cm) : pass def set_cm(self, cm) : self.__CM = cm def show(self) : print "#" * 60 bytecode._Print("\tSAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED", self.frame_type.get_value()) bytecode._Print("\tOFFSET_DELTA", self.offset_delta.get_value()) self.stack.show() print "#" * 60 class SameFrameExtended : def __init__(self, buff) : # u1 frame_type = SAME_FRAME_EXTENDED;/* 251*/ # u2 offset_delta; self.frame_type = SV( '>B', buff.read(1) ) self.offset_delta = SV( '>H', buff.read(2) ) def get_raw(self) : return self.frame_type.get_value_buff() + self.offset_delta.get_value_buff() def _fix_attributes(self, cm) : pass def set_cm(self, cm) : pass def show(self) : print "#" * 60 bytecode._Print("\tSAME_FRAME_EXTENDED", self.frame_type.get_value()) bytecode._Print("\tOFFSET_DELTA", self.offset_delta.get_value()) print "#" * 60 class AppendFrame : def __init__(self, class_manager, buff) : self.__CM = class_manager # u1 frame_type = APPEND; /* 252-254 */ # u2 offset_delta; self.frame_type = SV( '>B', buff.read(1) ) self.offset_delta = SV( '>H', buff.read(2) ) # verification_type_info locals[frame_type -251]; self.__locals = [] k = self.frame_type.get_value() - 251 for i in range(0, k) : self.__locals.append( VerificationTypeInfo( self.__CM, buff ) ) def get_locals(self) : return self.__locals def show(self) : print "#" * 60 bytecode._Print("\tAPPEND_FRAME", self.frame_type.get_value()) bytecode._Print("\tOFFSET_DELTA", self.offset_delta.get_value()) for i in self.__locals : i.show() print "#" * 60 def get_raw(self) : return self.frame_type.get_value_buff() + \ self.offset_delta.get_value_buff() + \ ''.join(x.get_raw() for x in self.__locals) def _fix_attributes(self, new_cm) : for i in self.__locals : i._fix_attributes( new_cm ) def set_cm(self, cm) : self.__CM = cm for i in self.__locals : i.set_cm( cm ) class StackMapTableAttribute(BasicAttribute) : def __init__(self, class_manager, buff) : self.__CM = class_manager super(StackMapTableAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length # u2 number_of_entries; self.number_of_entries = SV( '>H', buff.read(2) ) # stack_map_frame entries[number_of_entries]; self.__entries = [] for i in range(0, self.number_of_entries.get_value()) : frame_type = SV( '>B', buff.read_b(1) ).get_value() if frame_type >= 0 and frame_type <= 63 : self.__entries.append( SameFrame( buff ) ) elif frame_type >= 64 and frame_type <= 127 : self.__entries.append( SameLocals1StackItemFrame( self.__CM, buff ) ) elif frame_type == 247 : self.__entries.append( SameLocals1StackItemFrameExtended( self.__CM, buff ) ) elif frame_type >= 248 and frame_type <= 250 : self.__entries.append( ChopFrame( buff ) ) elif frame_type == 251 : self.__entries.append( SameFrameExtended( buff ) ) elif frame_type >= 252 and frame_type <= 254 : self.__entries.append( AppendFrame( self.__CM, buff ) ) elif frame_type == 255 : self.__entries.append( FullFrame( self.__CM, buff ) ) else : bytecode.Exit( "Frame type %d is unknown" % frame_type ) def get_entries(self) : return self.__entries def get_local_variables(self) : for i in self.__entries : if isinstance(i, FullFrame) : return i.get_local_variables() return [] def get_raw(self) : return self.number_of_entries.get_value_buff() + \ ''.join(x.get_raw() for x in self.__entries ) def show(self) : bytecode._Print("NUMBER_OF_ENTRIES", self.number_of_entries.get_value()) for i in self.__entries : i.show() def _fix_attributes(self, new_cm) : for i in self.__entries : i._fix_attributes( new_cm ) def set_cm(self, cm) : self.__CM = cm for i in self.__entries : i.set_cm( cm ) class InnerClassesDesc : def __init__(self, class_manager, buff) : INNER_CLASSES_FORMAT = [ ">HHHH", "inner_class_info_index outer_class_info_index inner_name_index inner_class_access_flags" ] self.__CM = class_manager self.__raw_buff = buff.read( calcsize( INNER_CLASSES_FORMAT[0] ) ) self.format = SVs( INNER_CLASSES_FORMAT[0], namedtuple( "InnerClassesFormat", INNER_CLASSES_FORMAT[1] ), self.__raw_buff ) def show(self) : print self.format def get_raw(self) : return self.format.get_value_buff() def set_cm(self, cm) : self.__CM = cm class InnerClassesAttribute(BasicAttribute) : def __init__(self, class_manager, buff) : self.__CM = class_manager super(InnerClassesAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length # u2 number_of_classes; self.number_of_classes = SV( '>H', buff.read(2) ) # { u2 inner_class_info_index; # u2 outer_class_info_index; # u2 inner_name_index; # u2 inner_class_access_flags; # } classes[number_of_classes]; self.__classes = [] for i in range(0, self.number_of_classes.get_value()) : self.__classes.append( InnerClassesDesc( self.__CM, buff ) ) def get_classes(self) : return self.__classes def show(self) : print self.number_of_classes for i in self.__classes : i.show() def set_cm(self, cm) : self.__CM = cm for i in self.__classes : i.set_cm( cm ) def get_raw(self) : return self.number_of_classes.get_value_buff() + \ ''.join(x.get_raw() for x in self.__classes) class ConstantValueAttribute(BasicAttribute) : def __init__(self, class_manager, buff) : self.__CM = class_manager super(ConstantValueAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 constantvalue_index; self.constantvalue_index = SV( '>H', buff.read(2) ) def show(self) : print self.constantvalue_index def set_cm(self, cm) : self.__CM = cm def get_raw(self) : return self.constantvalue_index.get_value_buff() class EnclosingMethodAttribute(BasicAttribute) : def __init__(self, class_manager, buff) : ENCLOSING_METHOD_FORMAT = [ '>HH', "class_index method_index" ] self.__CM = class_manager super(EnclosingMethodAttribute, self).__init__() # u2 attribute_name_index; # u4 attribute_length; # u2 class_index # u2 method_index; self.__raw_buff = buff.read( calcsize( ENCLOSING_METHOD_FORMAT[0] ) ) self.format = SVs( ENCLOSING_METHOD_FORMAT[0], namedtuple( "EnclosingMethodFormat", ENCLOSING_METHOD_FORMAT[1] ), self.__raw_buff ) def show(self) : print self.format def set_cm(self, cm) : self.__CM = cm def get_raw(self) : return self.format.get_value_buff() ATTRIBUTE_INFO_DESCR = { "Code" : CodeAttribute, "Deprecated" : DeprecatedAttribute, "SourceFile" : SourceFileAttribute, "Exceptions" : ExceptionsAttribute, "LineNumberTable" : LineNumberTableAttribute, "LocalVariableTable" : LocalVariableTableAttribute, "LocalVariableTypeTable" : LocalVariableTypeTableAttribute, "StackMapTable" : StackMapTableAttribute, "InnerClasses" : InnerClassesAttribute, "ConstantValue" : ConstantValueAttribute, "EnclosingMethod" : EnclosingMethodAttribute, "Signature" : SignatureAttribute, "Synthetic" : SyntheticAttribute, "SourceDebugExtension" : SourceDebugExtensionAttribute, "RuntimeVisibleAnnotations" : RuntimeVisibleAnnotationsAttribute, "RuntimeInvisibleAnnotations" : RuntimeInvisibleAnnotationsAttribute, "RuntimeVisibleParameterAnnotations" : RuntimeVisibleParameterAnnotationsAttribute, "RuntimeInvisibleParameterAnnotations" : RuntimeInvisibleParameterAnnotationsAttribute, "AnnotationDefault" : AnnotationDefaultAttribute, } class AttributeInfo : """AttributeInfo manages each attribute info (Code, SourceFile ....)""" def __init__(self, class_manager, buff) : self.__CM = class_manager self.__raw_buff = buff.read( calcsize( ATTRIBUTE_INFO[0] ) ) self.format = SVs( ATTRIBUTE_INFO[0], ATTRIBUTE_INFO[1], self.__raw_buff ) self.__name = self.__CM.get_string( self.format.get_value().attribute_name_index ) try : self._info = ATTRIBUTE_INFO_DESCR[ self.__name ](self.__CM, buff) except KeyError, ke : bytecode.Exit( "AttributeInfo %s doesn't exit" % self.__name ) def get_item(self) : """Return the specific attribute info""" return self._info def get_name(self) : """Return the name of the attribute""" return self.__name def get_raw(self) : v1 = self.format.get_value().attribute_length v2 = len(self._info.get_raw()) if v1 != v2 : self.set_attribute_length( v2 ) return self.format.get_value_buff() + self._info.get_raw() def get_attribute_name_index(self) : return self.format.get_value().attribute_name_index def set_attribute_name_index(self, value) : self.format.set_value( { "attribute_name_index" : value } ) def set_attribute_length(self, value) : self.format.set_value( { "attribute_length" : value } ) def get_attributes(self) : return self.format def _fix_attributes(self, new_cm) : self._info._fix_attributes( new_cm ) def set_cm(self, cm) : self.__CM = cm self._info.set_cm( cm ) def show(self) : print self.format, self.__name if self._info != None : self._info.show() def pretty_show(self, m_a) : print self.format, self.__name if self._info != None : if isinstance(self._info, CodeAttribute) : self._info.pretty_show(m_a) else : self._info.show() class ClassManager : """ClassManager can be used by all classes to get more information""" def __init__(self, constant_pool, constant_pool_count) : self.constant_pool = constant_pool self.constant_pool_count = constant_pool_count self.__this_class = None def get_value(self, idx) : name = self.get_item(idx[0]).get_name() if name == "CONSTANT_Integer" : return [ name, self.get_item(idx[0]).get_format().get_value().bytes ] elif name == "CONSTANT_String" : return [ name, self.get_string( self.get_item(idx[0]).get_format().get_value().string_index ) ] elif name == "CONSTANT_Class" : return [ name, self.get_class( idx[0] ) ] elif name == "CONSTANT_Fieldref" : return [ name, self.get_field( idx[0] ) ] elif name == "CONSTANT_Float" : return [ name, self.get_item(idx[0]).get_format().get_value().bytes ] bytecode.Exit( "get_value not yet implemented for %s" % name ) def get_item(self, idx) : return self.constant_pool[ idx - 1] def get_interface(self, idx) : if self.get_item(idx).get_name() != "CONSTANT_InterfaceMethodref" : return [] class_idx = self.get_item(idx).get_class_index() name_and_type_idx = self.get_item(idx).get_name_and_type_index() return [ self.get_string( self.get_item(class_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_descriptor_index() ) ] def get_interface_index(self, class_name, name, descriptor) : raise("ooo") def get_method(self, idx) : if self.get_item(idx).get_name() != "CONSTANT_Methodref" : return [] class_idx = self.get_item(idx).get_class_index() name_and_type_idx = self.get_item(idx).get_name_and_type_index() return [ self.get_string( self.get_item(class_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_descriptor_index() ) ] def get_method_index(self, class_name, name, descriptor) : idx = 1 for i in self.constant_pool : res = self.get_method( idx ) if res != [] : m_class_name, m_name, m_descriptor = res if m_class_name == class_name and m_name == name and m_descriptor == descriptor : return idx idx += 1 return -1 def get_field(self, idx) : if self.get_item(idx).get_name() != "CONSTANT_Fieldref" : return [] class_idx = self.get_item(idx).get_class_index() name_and_type_idx = self.get_item(idx).get_name_and_type_index() return [ self.get_string( self.get_item(class_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_name_index() ), self.get_string( self.get_item(name_and_type_idx).get_descriptor_index() ) ] def get_field_index(self, name, descriptor) : idx = 1 for i in self.constant_pool : res = self.get_field( idx ) if res != [] : _, m_name, m_descriptor = res if m_name == name and m_descriptor == descriptor : return idx idx += 1 def get_class(self, idx) : if self.get_item(idx).get_name() != "CONSTANT_Class" : return [] return [ self.get_string( self.get_item(idx).get_name_index() ) ] def get_array_type(self, idx) : return ARRAY_TYPE[ idx[0] ] def get_string_index(self, name) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_Utf8" : if i.get_bytes() == name : return idx idx += 1 return -1 def get_integer_index(self, value) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_Integer" : if i.get_format().get_value().bytes == value : return idx idx += 1 return -1 def get_cstring_index(self, value) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_String" : if self.get_string( i.get_format().get_value().string_index ) == value : return idx idx += 1 return -1 def get_name_and_type_index(self, name_method_index, descriptor_method_index) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_NameAndType" : value = i.get_format().get_value() if value.name_index == name_method_index and value.descriptor_index == descriptor_method_index : return idx idx += 1 return -1 def get_class_by_index(self, name_index) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_Class" : value = i.get_format().get_value() if value.name_index == name_index : return idx idx += 1 return -1 def get_method_ref_index(self, new_class_index, new_name_and_type_index) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_Methodref" : value = i.get_format().get_value() if value.class_index == new_class_index and value.name_and_type_index == new_name_and_type_index : return idx idx += 1 return -1 def get_field_ref_index(self, new_class_index, new_name_and_type_index) : idx = 1 for i in self.constant_pool : if i.get_name() == "CONSTANT_Fieldref" : value = i.get_format().get_value() if value.class_index == new_class_index and value.name_and_type_index == new_name_and_type_index : return idx idx += 1 return -1 def get_class_index(self, method_name) : idx = 1 for i in self.constant_pool : res = self.get_method( idx ) if res != [] : _, name, _ = res if name == method_name : return i.get_class_index() idx += 1 return -1 def get_class_index2(self, class_name) : idx = 1 for i in self.constant_pool : res = self.get_class( idx ) if res != [] : name = res[0] if name == class_name : return idx idx += 1 return -1 def get_used_fields(self) : l = [] for i in self.constant_pool : if i.get_name() == "CONSTANT_Fieldref" : l.append( i ) return l def get_used_methods(self) : l = [] for i in self.constant_pool : if i.get_name() == "CONSTANT_Methodref" : l.append( i ) return l def get_string(self, idx) : if self.constant_pool[idx - 1].get_name() == "CONSTANT_Utf8" : return self.constant_pool[idx - 1].get_bytes() return None def set_string(self, idx, name) : if self.constant_pool[idx - 1].get_name() == "CONSTANT_Utf8" : self.constant_pool[idx - 1].set_bytes( name ) else : bytecode.Exit( "invalid index %d to set string %s" % (idx, name) ) def add_string(self, name) : name_index = self.get_string_index(name) if name_index != -1 : return name_index tag_value = INVERT_CONSTANT_INFO[ "CONSTANT_Utf8" ] buff = pack( CONSTANT_INFO[ tag_value ][1], tag_value, len(name) ) + pack( ">%ss" % len(name), name ) ci = CONSTANT_INFO[ tag_value ][-1]( self, bytecode.BuffHandle( buff ) ) self.constant_pool.append( ci ) self.constant_pool_count.set_value( self.constant_pool_count.get_value() + 1 ) return self.constant_pool_count.get_value() - 1 def set_this_class(self, this_class) : self.__this_class = this_class def get_this_class(self) : return self.__this_class.get_value() def get_this_class_name(self) : return self.get_class( self.__this_class.get_value() )[0] def add_constant_pool(self, elem) : self.constant_pool.append( elem ) self.constant_pool_count.set_value( self.constant_pool_count.get_value() + 1 ) def get_constant_pool_count(self) : return self.constant_pool_count.get_value() def create_class(self, name) : class_name_index = self.add_string( name ) return self._create_class( class_name_index ) def _create_class(self, class_name_index) : class_index = self.get_class_by_index( class_name_index ) if class_index == -1 : new_class = CreateClass( self, class_name_index ) self.add_constant_pool( Class( self, bytecode.BuffHandle( new_class.get_raw() ) ) ) class_index = self.get_constant_pool_count() - 1 return class_index def create_name_and_type(self, name, desc) : name_index = self.add_string( name ) descriptor_index = self.add_string( desc ) return self._create_name_and_type( name_index, descriptor_index ) def create_name_and_type_by_index(self, name_method_index, descriptor_method_index) : return self._create_name_and_type( name_method_index, descriptor_method_index ) def _create_name_and_type(self, name_method_index, descriptor_method_index) : name_and_type_index = self.get_name_and_type_index( name_method_index, descriptor_method_index ) if name_and_type_index == -1 : new_nat = CreateNameAndType( self, name_method_index, descriptor_method_index ) self.add_constant_pool( NameAndType( self, bytecode.BuffHandle( new_nat.get_raw() ) ) ) name_and_type_index = self.get_constant_pool_count() - 1 return name_and_type_index def create_method_ref(self, new_class_index, new_name_and_type_index) : new_mr_index = self.get_method_ref_index( new_class_index, new_name_and_type_index ) if new_mr_index == -1 : new_mr = CreateMethodRef( self, new_class_index, new_name_and_type_index ) self.add_constant_pool( MethodRef( self, bytecode.BuffHandle( new_mr.get_raw() ) ) ) new_mr_index = self.get_constant_pool_count() - 1 return new_mr_index def create_field_ref(self, new_class_index, new_name_and_type_index) : new_fr_index = self.get_field_ref_index( new_class_index, new_name_and_type_index ) if new_fr_index == -1 : new_fr = CreateFieldRef( self, new_class_index, new_name_and_type_index ) self.add_constant_pool( FieldRef( self, bytecode.BuffHandle( new_fr.get_raw() ) ) ) new_fr_index = self.get_constant_pool_count() - 1 return new_fr_index def create_integer(self, value) : new_int_index = self.get_integer_index( value ) if new_int_index == -1 : new_int = CreateInteger( value ) self.add_constant_pool( Integer( self, bytecode.BuffHandle( new_int.get_raw() ) ) ) new_int_index = self.get_constant_pool_count() - 1 return new_int_index def create_string(self, value) : new_string_index = self.get_cstring_index( value ) if new_string_index == -1 : new_string = CreateString( self, value ) self.add_constant_pool( String( self, bytecode.BuffHandle( new_string.get_raw() ) ) ) new_string_index = self.get_constant_pool_count() - 1 return new_string_index class JVMFormat(bytecode._Bytecode) : """ An object which is the main class to handle properly a class file. Exported fields : magic, minor_version, major_version, constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, methods_count, attributes_count """ def __init__(self, buff) : """ @param buff : the buffer which represents the open file """ super(JVMFormat, self).__init__( buff ) self._load_class() def _load_class(self) : # u4 magic; # u2 minor_version; # u2 major_version; self.magic = SV( '>L', self.read( 4 ) ) self.minor_version = SV( '>H', self.read( 2 ) ) self.major_version = SV( '>H', self.read( 2 ) ) # u2 constant_pool_count; self.constant_pool_count = SV( '>H', self.read( 2 ) ) # cp_info constant_pool[constant_pool_count-1]; self.constant_pool = [] self.__CM = ClassManager( self.constant_pool, self.constant_pool_count ) i = 1 while(i < self.constant_pool_count.get_value()) : tag = SV( '>B', self.read_b( 1 ) ) if tag.get_value() not in CONSTANT_INFO : bytecode.Exit( "tag %d not in CONSTANT_INFO" % tag.get_value() ) ci = CONSTANT_INFO[ tag.get_value() ][-1]( self.__CM, self ) self.constant_pool.append( ci ) i = i + 1 # CONSTANT_Long or CONSTANT_Double # If a CONSTANT_Long_info or CONSTANT_Double_info structure is the item # in the constant_pool table at index n, then the next usable item in the pool is # located at index n + 2. The constant_pool index n + 1 must be valid but is # considered unusable. if tag.get_value() == 5 or tag.get_value() == 6 : self.constant_pool.append( EmptyConstant() ) i = i + 1 # u2 access_flags; # u2 this_class; # u2 super_class; self.access_flags = SV( '>H', self.read( 2 ) ) self.this_class = SV( '>H', self.read( 2 ) ) self.super_class = SV( '>H', self.read( 2 ) ) self.__CM.set_this_class( self.this_class ) # u2 interfaces_count; self.interfaces_count = SV( '>H', self.read( 2 ) ) # u2 interfaces[interfaces_count]; self.interfaces = [] for i in range(0, self.interfaces_count.get_value()) : tag = SV( '>H', self.read( 2 ) ) self.interfaces.append( tag ) # u2 fields_count; self.fields_count = SV( '>H', self.read( 2 ) ) # field_info fields[fields_count]; self.fields = [] for i in range(0, self.fields_count.get_value()) : fi = FieldInfo( self.__CM, self ) self.fields.append( fi ) # u2 methods_count; self.methods_count = SV( '>H', self.read( 2 ) ) # method_info methods[methods_count]; self.methods = [] for i in range(0, self.methods_count.get_value()) : mi = MethodInfo( self.__CM, self ) self.methods.append( mi ) # u2 attributes_count; self.attributes_count = SV( '>H', self.read( 2 ) ) # attribute_info attributes[attributes_count]; self.__attributes = [] for i in range(0, self.attributes_count.get_value()) : ai = AttributeInfo( self.__CM, self ) self.__attributes.append( ai ) def get_class(self, class_name) : """ Verify the name of the class @param class_name : the name of the class @rtype : True if the class name is valid, otherwise it's False """ x = self.__CM.get_this_class_name() == class_name if x == True : return x return self.__CM.get_this_class_name() == class_name.replace(".", "/") def get_classes_names(self) : """ Return the names of classes """ return [ self.__CM.get_this_class_name() ] def get_name(self) : """ """ return self.__CM.get_this_class_name() def get_classes(self) : """ """ return [ self ] def get_field(self, name) : """ Return into a list all fields which corresponds to the regexp @param name : the name of the field (a regexp) """ prog = re.compile( name ) fields = [] for i in self.fields : if prog.match( i.get_name() ) : fields.append( i ) return fields def get_method_descriptor(self, class_name, method_name, descriptor) : """ Return the specific method @param class_name : the class name of the method @param method_name : the name of the method @param descriptor : the descriptor of the method @rtype: L{MethodInfo} """ # FIXME : handle multiple class name ? if class_name != None : if class_name != self.__CM.get_this_class_name() : return None for i in self.methods : if method_name == i.get_name() and descriptor == i.get_descriptor() : return i return None def get_field_descriptor(self, class_name, field_name, descriptor) : """ Return the specific field @param class_name : the class name of the field @param field_name : the name of the field @param descriptor : the descriptor of the field @rtype: L{FieldInfo} """ # FIXME : handle multiple class name ? if class_name != None : if class_name != self.__CM.get_this_class_name() : return None for i in self.fields : if field_name == i.get_name() and descriptor == i.get_descriptor() : return i return None def get_method(self, name) : """Return into a list all methods which corresponds to the regexp @param name : the name of the method (a regexp) """ prog = re.compile( name ) methods = [] for i in self.methods : if prog.match( i.get_name() ) : methods.append( i ) return methods def get_all_fields(self) : return self.fields def get_fields(self) : """Return all objects fields""" return self.fields def get_methods(self) : """Return all objects methods""" return self.methods def get_constant_pool(self) : """Return the constant pool list""" return self.constant_pool def get_strings(self) : """Return all strings into the class""" l = [] for i in self.constant_pool : if i.get_name() == "CONSTANT_Utf8" : l.append( i.get_bytes() ) return l def get_class_manager(self) : """ Return directly the class manager @rtype : L{ClassManager} """ return self.__CM def set_used_field(self, old, new) : """ Change the description of a field @param old : a list of string which contained the original class name, the original field name and the original descriptor @param new : a list of string which contained the new class name, the new field name and the new descriptor """ used_fields = self.__CM.get_used_fields() for i in used_fields : class_idx = i.format.get_value().class_index name_and_type_idx = i.format.get_value().name_and_type_index class_name = self.__CM.get_string( self.__CM.get_item(class_idx).get_name_index() ) field_name = self.__CM.get_string( self.__CM.get_item(name_and_type_idx).get_name_index() ) descriptor = self.__CM.get_string( self.__CM.get_item(name_and_type_idx).get_descriptor_index() ) if old[0] == class_name and old[1] == field_name and old[2] == descriptor : # print "SET USED FIELD", class_name, method_name, descriptor self.__CM.set_string( self.__CM.get_item(class_idx).get_name_index(), new[0] ) self.__CM.set_string( self.__CM.get_item(name_and_type_idx).get_name_index(), new[1] ) self.__CM.set_string( self.__CM.get_item(name_and_type_idx).get_descriptor_index(), new[2] ) def set_used_method(self, old, new) : """ Change the description of a method @param old : a list of string which contained the original class name, the original method name and the original descriptor @param new : a list of string which contained the new class name, the new method name and the new descriptor """ used_methods = self.__CM.get_used_methods() for i in used_methods : class_idx = i.format.get_value().class_index name_and_type_idx = i.format.get_value().name_and_type_index class_name = self.__CM.get_string( self.__CM.get_item(class_idx).get_name_index() ) method_name = self.__CM.get_string( self.__CM.get_item(name_and_type_idx).get_name_index() ) descriptor = self.__CM.get_string( self.__CM.get_item(name_and_type_idx).get_descriptor_index() ) if old[0] == class_name and old[1] == method_name and old[2] == descriptor : # print "SET USED METHOD", class_name, method_name, descriptor self.__CM.set_string( self.__CM.get_item(class_idx).get_name_index(), new[0] ) self.__CM.set_string( self.__CM.get_item(name_and_type_idx).get_name_index(), new[1] ) self.__CM.set_string( self.__CM.get_item(name_and_type_idx).get_descriptor_index(), new[2] ) def show(self) : """ Show the .class format into a human readable format """ bytecode._Print( "MAGIC", self.magic.get_value() ) bytecode._Print( "MINOR VERSION", self.minor_version.get_value() ) bytecode._Print( "MAJOR VERSION", self.major_version.get_value() ) bytecode._Print( "CONSTANT POOL COUNT", self.constant_pool_count.get_value() ) nb = 0 for i in self.constant_pool : print nb, i.show() nb += 1 bytecode._Print( "ACCESS FLAGS", self.access_flags.get_value() ) bytecode._Print( "THIS CLASS", self.this_class.get_value() ) bytecode._Print( "SUPER CLASS", self.super_class.get_value() ) bytecode._Print( "INTERFACE COUNT", self.interfaces_count.get_value() ) nb = 0 for i in self.interfaces : print nb, print i bytecode._Print( "FIELDS COUNT", self.fields_count.get_value() ) nb = 0 for i in self.fields : print nb, i.show() nb += 1 bytecode._Print( "METHODS COUNT", self.methods_count.get_value() ) nb = 0 for i in self.methods : print nb, i.show() nb += 1 bytecode._Print( "ATTRIBUTES COUNT", self.attributes_count.get_value() ) nb = 0 for i in self.__attributes : print nb, i.show() nb += 1 def pretty_show(self, vm_a) : """ Show the .class format into a human readable format """ bytecode._Print( "MAGIC", self.magic.get_value() ) bytecode._Print( "MINOR VERSION", self.minor_version.get_value() ) bytecode._Print( "MAJOR VERSION", self.major_version.get_value() ) bytecode._Print( "CONSTANT POOL COUNT", self.constant_pool_count.get_value() ) nb = 0 for i in self.constant_pool : print nb, i.show() nb += 1 bytecode._Print( "ACCESS FLAGS", self.access_flags.get_value() ) bytecode._Print( "THIS CLASS", self.this_class.get_value() ) bytecode._Print( "SUPER CLASS", self.super_class.get_value() ) bytecode._Print( "INTERFACE COUNT", self.interfaces_count.get_value() ) nb = 0 for i in self.interfaces : print nb, i.show() bytecode._Print( "FIELDS COUNT", self.fields_count.get_value() ) nb = 0 for i in self.fields : print nb, i.show() nb += 1 bytecode._Print( "METHODS COUNT", self.methods_count.get_value() ) nb = 0 for i in self.methods : print nb, i.pretty_show(vm_a) nb += 1 bytecode._Print( "ATTRIBUTES COUNT", self.attributes_count.get_value() ) nb = 0 for i in self.__attributes : print nb, i.show() def insert_string(self, value) : """Insert a string into the constant pool list (Constant_Utf8) @param value : the new string """ self.__CM.add_string( value ) def insert_field(self, class_name, name, descriptor) : """ Insert a field into the class @param class_name : the class of the field @param name : the name of the field @param descriptor : a list with the access_flag and the descriptor ( [ "ACC_PUBLIC", "I" ] ) """ new_field = CreateFieldInfo( self.__CM, name, descriptor ) new_field = FieldInfo( self.__CM, bytecode.BuffHandle( new_field.get_raw() ) ) self.fields.append( new_field ) self.fields_count.set_value( self.fields_count.get_value() + 1 ) # Add a FieldRef and a NameAndType name_and_type_index = self.__CM.create_name_and_type_by_index( new_field.get_name_index(), new_field.get_descriptor_index() ) self.__CM.create_field_ref( self.__CM.get_this_class(), name_and_type_index ) def insert_craft_method(self, name, proto, codes) : """ Insert a craft method into the class @param name : the name of the new method @param proto : a list which describe the method ( [ ACCESS_FLAGS, RETURN_TYPE, ARGUMENTS ], ie : [ "ACC_PUBLIC", "[B", "[B" ] ) @param codes : a list which represents the code into a human readable format ( [ "aconst_null" ], [ "areturn" ] ] ) """ # Create new method new_method = CreateMethodInfo(self.__CM, name, proto, codes) # Insert the method by casting it directly into a MethodInfo with the raw buffer self._insert_basic_method( MethodInfo( self.__CM, bytecode.BuffHandle( new_method.get_raw() ) ) ) def insert_direct_method(self, name, ref_method) : """ Insert a direct method (MethodInfo object) into the class @param name : the name of the new method @param ref_method : the MethodInfo Object """ if ref_method == None : return # Change the name_index name_index = self.__CM.get_string_index( name ) if name_index != -1 : bytecode.Exit( "method %s already exits" % name ) name_index = self.__CM.add_string( name ) ref_method.set_name_index( name_index ) # Change the descriptor_index descriptor_index = self.__CM.get_string_index( ref_method.get_descriptor() ) if descriptor_index == -1 : descriptor_index = self.__CM.add_string( ref_method.get_descriptor() ) ref_method.set_descriptor_index( descriptor_index ) # Change attributes name index self._fix_attributes_external( ref_method ) # Change internal index self._fix_attributes_internal( ref_method ) # Insert the method self._insert_basic_method( ref_method ) def _fix_attributes_external(self, ref_method) : for i in ref_method.get_attributes() : attribute_name_index = self.__CM.add_string( i.get_name() ) i.set_attribute_name_index( attribute_name_index ) self._fix_attributes_external( i.get_item() ) def _fix_attributes_internal(self, ref_method) : for i in ref_method.get_attributes() : attribute_name_index = self.__CM.add_string( i.get_name() ) i._fix_attributes( self.__CM ) i.set_attribute_name_index( attribute_name_index ) def _insert_basic_method(self, ref_method) : # Add a MethodRef and a NameAndType name_and_type_index = self.__CM.create_name_and_type_by_index( ref_method.get_name_index(), ref_method.get_descriptor_index() ) self.__CM.create_method_ref( self.__CM.get_this_class(), name_and_type_index ) # Change the class manager ref_method.set_cm( self.__CM ) # Insert libraries/constants dependances methods = ref_method._patch_bytecodes() # FIXME : insert needed fields + methods prog = re.compile( "^java*" ) for i in methods : if prog.match( i[0] ) == None : bytecode.Exit( "ooooops" ) #ref_method.show() # Insert the method self.methods.append( ref_method ) self.methods_count.set_value( self.methods_count.get_value() + 1 ) def _get_raw(self) : # u4 magic; # u2 minor_version; # u2 major_version; buff = self.magic.get_value_buff() buff += self.minor_version.get_value_buff() buff += self.major_version.get_value_buff() # u2 constant_pool_count; buff += self.constant_pool_count.get_value_buff() # cp_info constant_pool[constant_pool_count-1]; for i in self.constant_pool : buff += i.get_raw() # u2 access_flags; # u2 this_class; # u2 super_class; buff += self.access_flags.get_value_buff() buff += self.this_class.get_value_buff() buff += self.super_class.get_value_buff() # u2 interfaces_count; buff += self.interfaces_count.get_value_buff() # u2 interfaces[interfaces_count]; for i in self.interfaces : buff += i.get_value_buff() # u2 fields_count; buff += self.fields_count.get_value_buff() # field_info fields[fields_count]; for i in self.fields : buff += i.get_raw() # u2 methods_count; buff += self.methods_count.get_value_buff() # method_info methods[methods_count]; for i in self.methods : buff += i.get_raw() # u2 attributes_count; buff += self.attributes_count.get_value_buff() # attribute_info attributes[attributes_count]; for i in self.__attributes : buff += i.get_raw() return buff def save(self) : """ Return the class (with the modifications) into raw format @rtype: string """ return self._get_raw() def set_vmanalysis(self, vmanalysis) : pass def get_generator(self) : import jvm_generate return jvm_generate.JVMGenerate def get_INTEGER_INSTRUCTIONS(self) : return INTEGER_INSTRUCTIONS def get_type(self) : return "JVM"
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. ########################################## PERMISSIONS ######################################################## DVM_PERMISSIONS = { "MANIFEST_PERMISSION" : { "SEND_SMS" : [ "dangerous" , "send SMS messages" , "Allows application to send SMS messages. Malicious applications may cost you money by sending messages without your confirmation." ], "CALL_PHONE" : [ "dangerous" , "directly call phone numbers" , "Allows the application to call phone numbers without your intervention. Malicious applications may cause unexpected calls on your phone bill. Note that this does not allow the application to call emergency numbers." ], "RECEIVE_SMS" : [ "dangerous" , "receive SMS" , "Allows application to receive and process SMS messages. Malicious applications may monitor your messages or delete them without showing them to you." ], "RECEIVE_MMS" : [ "dangerous" , "receive MMS" , "Allows application to receive and process MMS messages. Malicious applications may monitor your messages or delete them without showing them to you." ], "READ_SMS" : [ "dangerous" , "read SMS or MMS" , "Allows application to read SMS messages stored on your phone or SIM card. Malicious applications may read your confidential messages." ], "WRITE_SMS" : [ "dangerous" , "edit SMS or MMS" , "Allows application to write to SMS messages stored on your phone or SIM card. Malicious applications may delete your messages." ], "RECEIVE_WAP_PUSH" : [ "dangerous" , "receive WAP" , "Allows application to receive and process WAP messages. Malicious applications may monitor your messages or delete them without showing them to you." ], "READ_CONTACTS" : [ "dangerous" , "read contact data" , "Allows an application to read all of the contact (address) data stored on your phone. Malicious applications can use this to send your data to other people." ], "WRITE_CONTACTS" : [ "dangerous" , "write contact data" , "Allows an application to modify the contact (address) data stored on your phone. Malicious applications can use this to erase or modify your contact data." ], "READ_CALENDAR" : [ "dangerous" , "read calendar events" , "Allows an application to read all of the calendar events stored on your phone. Malicious applications can use this to send your calendar events to other people." ], "WRITE_CALENDAR" : [ "dangerous" , "add or modify calendar events and send emails to guests" , "Allows an application to add or change the events on your calendar, which may send emails to guests. Malicious applications can use this to erase or modify your calendar events or to send emails to guests." ], "READ_USER_DICTIONARY" : [ "dangerous" , "read user-defined dictionary" , "Allows an application to read any private words, names and phrases that the user may have stored in the user dictionary." ], "WRITE_USER_DICTIONARY" : [ "normal" , "write to user-defined dictionary" , "Allows an application to write new words into the user dictionary." ], "READ_HISTORY_BOOKMARKS" : [ "dangerous" , "read Browser\'s history and bookmarks" , "Allows the application to read all the URLs that the browser has visited and all of the browser\'s bookmarks." ], "WRITE_HISTORY_BOOKMARKS" : [ "dangerous" , "write Browser\'s history and bookmarks" , "Allows an application to modify the browser\'s history or bookmarks stored on your phone. Malicious applications can use this to erase or modify your browser\'s data." ], "SET_ALARM" : [ "normal" , "set alarm in alarm clock" , "Allows the application to set an alarm in an installed alarm clock application. Some alarm clock applications may not implement this feature." ], "ACCESS_FINE_LOCATION" : [ "dangerous" , "fine (GPS) location" , "Access fine location sources, such as the Global Positioning System on the phone, where available. Malicious applications can use this to determine where you are and may consume additional battery power." ], "ACCESS_COARSE_LOCATION" : [ "dangerous" , "coarse (network-based) location" , "Access coarse location sources, such as the mobile network database, to determine an approximate phone location, where available. Malicious applications can use this to determine approximately where you are." ], "ACCESS_MOCK_LOCATION" : [ "dangerous" , "mock location sources for testing" , "Create mock location sources for testing. Malicious applications can use this to override the location and/or status returned by real-location sources such as GPS or Network providers." ], "ACCESS_LOCATION_EXTRA_COMMANDS" : [ "normal" , "access extra location provider commands" , "Access extra location provider commands. Malicious applications could use this to interfere with the operation of the GPS or other location sources." ], "INSTALL_LOCATION_PROVIDER" : [ "signatureOrSystem" , "permission to install a location provider" , "Create mock location sources for testing. Malicious applications can use this to override the location and/or status returned by real-location sources such as GPS or Network providers, or monitor and report your location to an external source." ], "INTERNET" : [ "dangerous" , "full Internet access" , "Allows an application to create network sockets." ], "ACCESS_NETWORK_STATE" : [ "normal" , "view network status" , "Allows an application to view the status of all networks." ], "ACCESS_WIFI_STATE" : [ "normal" , "view Wi-Fi status" , "Allows an application to view the information about the status of Wi-Fi." ], "BLUETOOTH" : [ "dangerous" , "create Bluetooth connections" , "Allows an application to view configuration of the local Bluetooth phone and to make and accept connections with paired devices." ], "NFC" : [ "dangerous" , "control Near-Field Communication" , "Allows an application to communicate with Near-Field Communication (NFC) tags, cards and readers." ], "USE_SIP" : [ "dangerous" , "make/receive Internet calls" , "Allows an application to use the SIP service to make/receive Internet calls." ], "ACCOUNT_MANAGER" : [ "signature" , "act as the Account Manager Service" , "Allows an application to make calls to Account Authenticators" ], "GET_ACCOUNTS" : [ "normal" , "discover known accounts" , "Allows an application to access the list of accounts known by the phone." ], "AUTHENTICATE_ACCOUNTS" : [ "dangerous" , "act as an account authenticator" , "Allows an application to use the account authenticator capabilities of the Account Manager, including creating accounts as well as obtaining and setting their passwords." ], "USE_CREDENTIALS" : [ "dangerous" , "use the authentication credentials of an account" , "Allows an application to request authentication tokens." ], "MANAGE_ACCOUNTS" : [ "dangerous" , "manage the accounts list" , "Allows an application to perform operations like adding and removing accounts and deleting their password." ], "MODIFY_AUDIO_SETTINGS" : [ "dangerous" , "change your audio settings" , "Allows application to modify global audio settings, such as volume and routing." ], "RECORD_AUDIO" : [ "dangerous" , "record audio" , "Allows application to access the audio record path." ], "CAMERA" : [ "dangerous" , "take pictures and videos" , "Allows application to take pictures and videos with the camera. This allows the application to collect images that the camera is seeing at any time." ], "VIBRATE" : [ "normal" , "control vibrator" , "Allows the application to control the vibrator." ], "FLASHLIGHT" : [ "normal" , "control flashlight" , "Allows the application to control the flashlight." ], "ACCESS_USB" : [ "signatureOrSystem" , "access USB devices" , "Allows the application to access USB devices." ], "HARDWARE_TEST" : [ "signature" , "test hardware" , "Allows the application to control various peripherals for the purpose of hardware testing." ], "PROCESS_OUTGOING_CALLS" : [ "dangerous" , "intercept outgoing calls" , "Allows application to process outgoing calls and change the number to be dialled. Malicious applications may monitor, redirect or prevent outgoing calls." ], "MODIFY_PHONE_STATE" : [ "signatureOrSystem" , "modify phone status" , "Allows the application to control the phone features of the device. An application with this permission can switch networks, turn the phone radio on and off and the like, without ever notifying you." ], "READ_PHONE_STATE" : [ "dangerous" , "read phone state and identity" , "Allows the application to access the phone features of the device. An application with this permission can determine the phone number and serial number of this phone, whether a call is active, the number that call is connected to and so on." ], "WRITE_EXTERNAL_STORAGE" : [ "dangerous" , "modify/delete SD card contents" , "Allows an application to write to the SD card." ], "WRITE_SETTINGS" : [ "dangerous" , "modify global system settings" , "Allows an application to modify the system\'s settings data. Malicious applications can corrupt your system\'s configuration." ], "WRITE_SECURE_SETTINGS" : [ "signatureOrSystem" , "modify secure system settings" , "Allows an application to modify the system\'s secure settings data. Not for use by normal applications." ], "WRITE_GSERVICES" : [ "signatureOrSystem" , "modify the Google services map" , "Allows an application to modify the Google services map. Not for use by normal applications." ], "EXPAND_STATUS_BAR" : [ "normal" , "expand/collapse status bar" , "Allows application to expand or collapse the status bar." ], "GET_TASKS" : [ "dangerous" , "retrieve running applications" , "Allows application to retrieve information about currently and recently running tasks. May allow malicious applications to discover private information about other applications." ], "REORDER_TASKS" : [ "dangerous" , "reorder applications running" , "Allows an application to move tasks to the foreground and background. Malicious applications can force themselves to the front without your control." ], "CHANGE_CONFIGURATION" : [ "dangerous" , "change your UI settings" , "Allows an application to change the current configuration, such as the locale or overall font size." ], "RESTART_PACKAGES" : [ "normal" , "kill background processes" , "Allows an application to kill background processes of other applications, even if memory is not low." ], "KILL_BACKGROUND_PROCESSES" : [ "normal" , "kill background processes" , "Allows an application to kill background processes of other applications, even if memory is not low." ], "FORCE_STOP_PACKAGES" : [ "signature" , "force-stop other applications" , "Allows an application to stop other applications forcibly." ], "DUMP" : [ "signatureOrSystem" , "retrieve system internal status" , "Allows application to retrieve internal status of the system. Malicious applications may retrieve a wide variety of private and secure information that they should never normally need." ], "SYSTEM_ALERT_WINDOW" : [ "dangerous" , "display system-level alerts" , "Allows an application to show system-alert windows. Malicious applications can take over the entire screen of the phone." ], "SET_ANIMATION_SCALE" : [ "dangerous" , "modify global animation speed" , "Allows an application to change the global animation speed (faster or slower animations) at any time." ], "PERSISTENT_ACTIVITY" : [ "dangerous" , "make application always run" , "Allows an application to make parts of itself persistent, so that the system can\'t use it for other applications." ], "GET_PACKAGE_SIZE" : [ "normal" , "measure application storage space" , "Allows an application to retrieve its code, data and cache sizes" ], "SET_PREFERRED_APPLICATIONS" : [ "signature" , "set preferred applications" , "Allows an application to modify your preferred applications. This can allow malicious applications to silently change the applications that are run, spoofing your existing applications to collect private data from you." ], "RECEIVE_BOOT_COMPLETED" : [ "normal" , "automatically start at boot" , "Allows an application to start itself as soon as the system has finished booting. This can make it take longer to start the phone and allow the application to slow down the overall phone by always running." ], "BROADCAST_STICKY" : [ "normal" , "send sticky broadcast" , "Allows an application to send sticky broadcasts, which remain after the broadcast ends. Malicious applications can make the phone slow or unstable by causing it to use too much memory." ], "WAKE_LOCK" : [ "dangerous" , "prevent phone from sleeping" , "Allows an application to prevent the phone from going to sleep." ], "SET_WALLPAPER" : [ "normal" , "set wallpaper" , "Allows the application to set the system wallpaper." ], "SET_WALLPAPER_HINTS" : [ "normal" , "set wallpaper size hints" , "Allows the application to set the system wallpaper size hints." ], "SET_TIME" : [ "signatureOrSystem" , "set time" , "Allows an application to change the phone\'s clock time." ], "SET_TIME_ZONE" : [ "dangerous" , "set time zone" , "Allows an application to change the phone\'s time zone." ], "MOUNT_UNMOUNT_FILESYSTEMS" : [ "dangerous" , "mount and unmount file systems" , "Allows the application to mount and unmount file systems for removable storage." ], "MOUNT_FORMAT_FILESYSTEMS" : [ "dangerous" , "format external storage" , "Allows the application to format removable storage." ], "ASEC_ACCESS" : [ "signature" , "get information on internal storage" , "Allows the application to get information on internal storage." ], "ASEC_CREATE" : [ "signature" , "create internal storage" , "Allows the application to create internal storage." ], "ASEC_DESTROY" : [ "signature" , "destroy internal storage" , "Allows the application to destroy internal storage." ], "ASEC_MOUNT_UNMOUNT" : [ "signature" , "mount/unmount internal storage" , "Allows the application to mount/unmount internal storage." ], "ASEC_RENAME" : [ "signature" , "rename internal storage" , "Allows the application to rename internal storage." ], "DISABLE_KEYGUARD" : [ "dangerous" , "disable key lock" , "Allows an application to disable the key lock and any associated password security. A legitimate example of this is the phone disabling the key lock when receiving an incoming phone call, then re-enabling the key lock when the call is finished." ], "READ_SYNC_SETTINGS" : [ "normal" , "read sync settings" , "Allows an application to read the sync settings, such as whether sync is enabled for Contacts." ], "WRITE_SYNC_SETTINGS" : [ "dangerous" , "write sync settings" , "Allows an application to modify the sync settings, such as whether sync is enabled for Contacts." ], "READ_SYNC_STATS" : [ "normal" , "read sync statistics" , "Allows an application to read the sync stats; e.g. the history of syncs that have occurred." ], "WRITE_APN_SETTINGS" : [ "dangerous" , "write Access Point Name settings" , "Allows an application to modify the APN settings, such as Proxy and Port of any APN." ], "SUBSCRIBED_FEEDS_READ" : [ "normal" , "read subscribed feeds" , "Allows an application to receive details about the currently synced feeds." ], "SUBSCRIBED_FEEDS_WRITE" : [ "dangerous" , "write subscribed feeds" , "Allows an application to modify your currently synced feeds. This could allow a malicious application to change your synced feeds." ], "CHANGE_NETWORK_STATE" : [ "dangerous" , "change network connectivity" , "Allows an application to change the state of network connectivity." ], "CHANGE_WIFI_STATE" : [ "dangerous" , "change Wi-Fi status" , "Allows an application to connect to and disconnect from Wi-Fi access points and to make changes to configured Wi-Fi networks." ], "CHANGE_WIFI_MULTICAST_STATE" : [ "dangerous" , "allow Wi-Fi Multicast reception" , "Allows an application to receive packets not directly addressed to your device. This can be useful when discovering services offered nearby. It uses more power than the non-multicast mode." ], "BLUETOOTH_ADMIN" : [ "dangerous" , "bluetooth administration" , "Allows an application to configure the local Bluetooth phone and to discover and pair with remote devices." ], "CLEAR_APP_CACHE" : [ "dangerous" , "delete all application cache data" , "Allows an application to free phone storage by deleting files in application cache directory. Access is usually very restricted to system process." ], "READ_LOGS" : [ "dangerous" , "read sensitive log data" , "Allows an application to read from the system\'s various log files. This allows it to discover general information about what you are doing with the phone, potentially including personal or private information." ], "SET_DEBUG_APP" : [ "dangerous" , "enable application debugging" , "Allows an application to turn on debugging for another application. Malicious applications can use this to kill other applications." ], "SET_PROCESS_LIMIT" : [ "dangerous" , "limit number of running processes" , "Allows an application to control the maximum number of processes that will run. Never needed for normal applications." ], "SET_ALWAYS_FINISH" : [ "dangerous" , "make all background applications close" , "Allows an application to control whether activities are always finished as soon as they go to the background. Never needed for normal applications." ], "SIGNAL_PERSISTENT_PROCESSES" : [ "dangerous" , "send Linux signals to applications" , "Allows application to request that the supplied signal be sent to all persistent processes." ], "DIAGNOSTIC" : [ "signature" , "read/write to resources owned by diag" , "Allows an application to read and write to any resource owned by the diag group; for example, files in /dev. This could potentially affect system stability and security. This should ONLY be used for hardware-specific diagnostics by the manufacturer or operator." ], "STATUS_BAR" : [ "signatureOrSystem" , "disable or modify status bar" , "Allows application to disable the status bar or add and remove system icons." ], "STATUS_BAR_SERVICE" : [ "signature" , "status bar" , "Allows the application to be the status bar." ], "FORCE_BACK" : [ "signature" , "force application to close" , "Allows an application to force any activity that is in the foreground to close and go back. Should never be needed for normal applications." ], "UPDATE_DEVICE_STATS" : [ "signatureOrSystem" , "modify battery statistics" , "Allows the modification of collected battery statistics. Not for use by normal applications." ], "INTERNAL_SYSTEM_WINDOW" : [ "signature" , "display unauthorised windows" , "Allows the creation of windows that are intended to be used by the internal system user interface. Not for use by normal applications." ], "MANAGE_APP_TOKENS" : [ "signature" , "manage application tokens" , "Allows applications to create and manage their own tokens, bypassing their normal Z-ordering. Should never be needed for normal applications." ], "INJECT_EVENTS" : [ "signature" , "press keys and control buttons" , "Allows an application to deliver its own input events (key presses, etc.) to other applications. Malicious applications can use this to take over the phone." ], "SET_ACTIVITY_WATCHER" : [ "signature" , "monitor and control all application launching" , "Allows an application to monitor and control how the system launches activities. Malicious applications may compromise the system completely. This permission is needed only for development, never for normal phone usage." ], "SHUTDOWN" : [ "signature" , "partial shutdown" , "Puts the activity manager into a shut-down state. Does not perform a complete shut down." ], "STOP_APP_SWITCHES" : [ "signature" , "prevent app switches" , "Prevents the user from switching to another application." ], "READ_INPUT_STATE" : [ "signature" , "record what you type and actions that you take" , "Allows applications to watch the keys that you press even when interacting with another application (such as entering a password). Should never be needed for normal applications." ], "BIND_INPUT_METHOD" : [ "signature" , "bind to an input method" , "Allows the holder to bind to the top-level interface of an input method. Should never be needed for normal applications." ], "BIND_WALLPAPER" : [ "signatureOrSystem" , "bind to wallpaper" , "Allows the holder to bind to the top-level interface of wallpaper. Should never be needed for normal applications." ], "BIND_DEVICE_ADMIN" : [ "signature" , "interact with device admin" , "Allows the holder to send intents to a device administrator. Should never be needed for normal applications." ], "SET_ORIENTATION" : [ "signature" , "change screen orientation" , "Allows an application to change the rotation of the screen at any time. Should never be needed for normal applications." ], "INSTALL_PACKAGES" : [ "signatureOrSystem" , "directly install applications" , "Allows an application to install new or updated Android packages. Malicious applications can use this to add new applications with arbitrarily powerful permissions." ], "CLEAR_APP_USER_DATA" : [ "signature" , "delete other applications\' data" , "Allows an application to clear user data." ], "DELETE_CACHE_FILES" : [ "signatureOrSystem" , "delete other applications\' caches" , "Allows an application to delete cache files." ], "DELETE_PACKAGES" : [ "signatureOrSystem" , "delete applications" , "Allows an application to delete Android packages. Malicious applications can use this to delete important applications." ], "MOVE_PACKAGE" : [ "signatureOrSystem" , "Move application resources" , "Allows an application to move application resources from internal to external media and vice versa." ], "CHANGE_COMPONENT_ENABLED_STATE" : [ "signatureOrSystem" , "enable or disable application components" , "Allows an application to change whether or not a component of another application is enabled. Malicious applications can use this to disable important phone capabilities. It is important to be careful with permission, as it is possible to bring application components into an unusable, inconsistent or unstable state." ], "ACCESS_SURFACE_FLINGER" : [ "signature" , "access SurfaceFlinger" , "Allows application to use SurfaceFlinger low-level features." ], "READ_FRAME_BUFFER" : [ "signature" , "read frame buffer" , "Allows application to read the content of the frame buffer." ], "BRICK" : [ "signature" , "permanently disable phone" , "Allows the application to disable the entire phone permanently. This is very dangerous." ], "REBOOT" : [ "signatureOrSystem" , "force phone reboot" , "Allows the application to force the phone to reboot." ], "DEVICE_POWER" : [ "signature" , "turn phone on or off" , "Allows the application to turn the phone on or off." ], "FACTORY_TEST" : [ "signature" , "run in factory test mode" , "Run as a low-level manufacturer test, allowing complete access to the phone hardware. Only available when a phone is running in manufacturer test mode." ], "BROADCAST_PACKAGE_REMOVED" : [ "signature" , "send package removed broadcast" , "Allows an application to broadcast a notification that an application package has been removed. Malicious applications may use this to kill any other application running." ], "BROADCAST_SMS" : [ "signature" , "send SMS-received broadcast" , "Allows an application to broadcast a notification that an SMS message has been received. Malicious applications may use this to forge incoming SMS messages." ], "BROADCAST_WAP_PUSH" : [ "signature" , "send WAP-PUSH-received broadcast" , "Allows an application to broadcast a notification that a WAP-PUSH message has been received. Malicious applications may use this to forge MMS message receipt or to replace the content of any web page silently with malicious variants." ], "MASTER_CLEAR" : [ "signatureOrSystem" , "reset system to factory defaults" , "Allows an application to completely reset the system to its factory settings, erasing all data, configuration and installed applications." ], "CALL_PRIVILEGED" : [ "signatureOrSystem" , "directly call any phone numbers" , "Allows the application to call any phone number, including emergency numbers, without your intervention. Malicious applications may place unnecessary and illegal calls to emergency services." ], "PERFORM_CDMA_PROVISIONING" : [ "signatureOrSystem" , "directly start CDMA phone setup" , "Allows the application to start CDMA provisioning. Malicious applications may start CDMA provisioning unnecessarily" ], "CONTROL_LOCATION_UPDATES" : [ "signatureOrSystem" , "control location update notifications" , "Allows enabling/disabling location update notifications from the radio. Not for use by normal applications." ], "ACCESS_CHECKIN_PROPERTIES" : [ "signatureOrSystem" , "access check-in properties" , "Allows read/write access to properties uploaded by the check-in service. Not for use by normal applications." ], "PACKAGE_USAGE_STATS" : [ "signature" , "update component usage statistics" , "Allows the modification of collected component usage statistics. Not for use by normal applications." ], "BATTERY_STATS" : [ "normal" , "modify battery statistics" , "Allows the modification of collected battery statistics. Not for use by normal applications." ], "BACKUP" : [ "signatureOrSystem" , "control system back up and restore" , "Allows the application to control the system\'s back-up and restore mechanism. Not for use by normal applications." ], "BIND_APPWIDGET" : [ "signatureOrSystem" , "choose widgets" , "Allows the application to tell the system which widgets can be used by which application. With this permission, applications can give access to personal data to other applications. Not for use by normal applications." ], "CHANGE_BACKGROUND_DATA_SETTING" : [ "signature" , "change background data usage setting" , "Allows an application to change the background data usage setting." ], "GLOBAL_SEARCH" : [ "signatureOrSystem" , "" , "" ], "GLOBAL_SEARCH_CONTROL" : [ "signature" , "" , "" ], "SET_WALLPAPER_COMPONENT" : [ "signatureOrSystem" , "" , "" ], "ACCESS_CACHE_FILESYSTEM" : [ "signatureOrSystem" , "access the cache file system" , "Allows an application to read and write the cache file system." ], "COPY_PROTECTED_DATA" : [ "signature" , "Allows to invoke default container service to copy content. Not for use by normal applications." , "Allows to invoke default container service to copy content. Not for use by normal applications." ], "C2D_MESSAGE" : [ "signature" , "" , "" ], }, "MANIFEST_PERMISSION_GROUP" : { "ACCOUNTS" : "Permissions for direct access to the accounts managed by the Account Manager.", "COST_MONEY" : "Used for permissions that can be used to make the user spend money without their direct involvement.", "DEVELOPMENT_TOOLS" : "Group of permissions that are related to development features.", "HARDWARE_CONTROLS" : "Used for permissions that provide direct access to the hardware on the device.", "LOCATION" : "Used for permissions that allow access to the user's current location.", "MESSAGES" : "Used for permissions that allow an application to send messages on behalf of the user or intercept messages being received by the user.", "NETWORK" : "Used for permissions that provide access to networking services.", "PERSONAL_INFO" : "Used for permissions that provide access to the user's private data, such as contacts, calendar events, e-mail messages, etc.", "PHONE_CALLS" : "Used for permissions that are associated with accessing and modifyign telephony state: intercepting outgoing calls, reading and modifying the phone state.", "STORAGE" : "Group of permissions that are related to SD card access.", "SYSTEM_TOOLS" : "Group of permissions that are related to system APIs.", }, }
Python
# Radare ! from r2 import r_bin from r2 import r_asm from r2 import r_anal from r2 import r_core from miasm.arch.arm_arch import arm_mn from miasm.core.bin_stream import bin_stream from miasm.core import asmbloc class ARM2 : def __init__(self) : b = r_bin.RBin () b.load("./apks/exploits/617efb2d51ad5c4aed50b76119ad880c6adcd4d2e386b3170930193525b0563d", None) baddr= b.get_baddr() print '-> Sections' for i in b.get_sections (): print 'offset=0x%08x va=0x%08x size=%05i %s' % (i.offset, baddr+i.rva, i.size, i.name) core = r_core.RCore() core.config.set_i("io.va", 1) core.config.set_i("anal.split", 1) core.file_open("./apks/exploits/617efb2d51ad5c4aed50b76119ad880c6adcd4d2e386b3170930193525b0563d", 0, 0) core.bin_load( None ) core.anal_all() for fcn in core.anal.get_fcns() : print type(fcn), fcn.type, "%x" % fcn.addr, fcn.ninstr, fcn.name # if (fcn.type == FcnType_FCN or fcn.type == FcnType_SYM): for s in core.bin.get_entries() : print s, type(s), s.rva, "%x" % s.offset #a = r_asm.RAsm() for s in core.bin.get_symbols() : print s, s.name, s.rva, s.offset, s.size if s.name == "rootshell" : #print core.disassemble_bytes( 0x8000 + s.offset, s.size ) #core.assembler.mdisassemble( 0x8000 + s.offset, s.size ) z = core.op_anal( 0x8000 + s.offset ) print z.mnemonic raise("oo") print core.bin.bins, core.bin.user d = core.bin.read_at( 0x8000 + s.offset, x, s.size ) print d raise("ooo") j = 0 while j < s.size : v = core.disassemble( 0x8000 + s.offset + j ) v1 = core.op_str( 0x8000 + s.offset + j ) print v1 # print 0x8000 + s.offset + j, j, v.inst_len, v.buf_asm j += v.inst_len #for i in core.asm_bwdisassemble(s.rva, 4, s.size/4) : # print "la", i # print a.mdisassemble( 20, 0x90 ) #"main", "main" ) #s.name )
Python
# This file is part of Androguard. # # Copyright (C) 2012 Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import random from androconf import error import jvm class Automaton : def __init__(self, _analysis) : self.__analysis = _analysis try : from networkx import DiGraph from networkx import draw_graphviz, write_dot except ImportError : error("module networkx not found") self.__G = DiGraph() for m in self.__analysis.get_methods() : for bb in m.basic_blocks.get() : for trace in bb.stack_traces.get() : for mre in jvm.MATH_JVM_RE : if mre[0].match( trace[2].get_name() ) : for i in trace[3].gets() : self._add( str(i) ) def _add(self, elem) : l = [] x = "" for i in elem : if i not in jvm.MATH_JVM_OPCODES.values() : x += i else : l.append( x ) l.append( i ) x = "" if len(l) > 1 : l.append( x ) self._add_expr( l ) def _add_expr(self, l) : if l == [] : return i = 0 while i < (len(l)-1) : self.__G.add_edge( self._transform(l[i]), self._transform(l[i+1]) ) i += 1 def _transform(self, i) : if "VARIABLE" in i : return "V" return i def new(self, loop) : expr = [] l = list( self.__G.node ) init = l[ random.randint(0, len(l) - 1) ] while init in jvm.MATH_JVM_OPCODES.values() : init = l[ random.randint(0, len(l) - 1) ] expr.append( init ) i = 0 while i <= loop : l = list( self.__G.edge[ init ] ) if l == [] : break init = l[ random.randint(0, len(l) - 1) ] expr.append( init ) i += 1 return expr def show(self) : print self.__G.node print self.__G.edge #draw_graphviz(self.__G) #write_dot(self.__G,'file.dot') class JVMGenerate : def __init__(self, _vm, _analysis) : self.__vm = _vm self.__analysis = _analysis self.__automaton = Automaton( self.__analysis ) self.__automaton.show() def create_affectation(self, method_name, desc) : l = [] if desc[0] == 0 : l.append( [ "aload_0" ] ) l.append( [ "bipush", desc[2] ] ) l.append( [ "putfield", desc[1].get_name(), desc[1].get_descriptor() ] ) return l def write(self, method, offset, field) : print method, offset, field expr = self.__automaton.new( 5 ) print field.get_name(), "EXPR ->", expr self._transform( expr ) def _transform(self, expr) : if len(expr) == 1 : return x = [ expr.pop(0), expr.pop(1), expr.pop(0) ] # while expr != [] :
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from androguard.core import bytecode from androguard.core import androconf from androguard.core.bytecode import SV from androguard.core.bytecodes.dvm_permissions import DVM_PERMISSIONS import zipfile, StringIO from struct import pack, unpack from xml.dom import minidom from xml.sax.saxutils import escape from zlib import crc32 import re import sys if sys.hexversion < 0x2070000 : try : import chilkat ZIPMODULE = 0 # UNLOCK : change it with your valid key ! try : CHILKAT_KEY = open("key.txt", "rb").read() except Exception : CHILKAT_KEY = "testme" except ImportError : ZIPMODULE = 1 else : ZIPMODULE = 1 ################################################### CHILKAT ZIP FORMAT ##################################################### class ChilkatZip : def __init__(self, raw) : self.files = [] self.zip = chilkat.CkZip() self.zip.UnlockComponent( CHILKAT_KEY ) self.zip.OpenFromMemory( raw, len(raw) ) filename = chilkat.CkString() e = self.zip.FirstEntry() while e != None : e.get_FileName(filename) self.files.append( filename.getString() ) e = e.NextEntry() def delete(self, patterns) : el = [] filename = chilkat.CkString() e = self.zip.FirstEntry() while e != None : e.get_FileName(filename) if re.match(patterns, filename.getString()) != None : el.append( e ) e = e.NextEntry() for i in el : self.zip.DeleteEntry( i ) def remplace_file(self, filename, buff) : entry = self.zip.GetEntryByName(filename) if entry != None : obj = chilkat.CkByteData() obj.append( buff, len(buff) ) return entry.ReplaceData( obj ) return False def write(self) : obj = chilkat.CkByteData() self.zip.WriteToMemory( obj ) return obj.getBytes() def namelist(self) : return self.files def read(self, elem) : e = self.zip.GetEntryByName( elem ) s = chilkat.CkByteData() e.Inflate( s ) return s.getBytes() def sign_apk(filename, keystore, storepass) : from subprocess import Popen, PIPE, STDOUT # jarsigner -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore tmp/androguard.androtrace tmp/toto.apk alias_name compile = Popen([ androconf.CONF["PATH_JARSIGNER"], "-sigalg", "MD5withRSA", "-digestalg", "SHA1", "-storepass", storepass, "-keystore", keystore, filename, "alias_name" ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() ######################################################## APK FORMAT ######################################################## class APK : """APK manages apk file format""" def __init__(self, filename, raw=False, mode="r") : """ @param filename : specify the path of the file, or raw data @param raw : specify (boolean) if the filename is a path or raw data @param mode """ self.filename = filename self.xml = {} self.package = "" self.androidversion = {} self.permissions = [] self.validAPK = False self.files = {} self.files_crc32 = {} if raw == True : self.__raw = filename else : fd = open( filename, "rb" ) self.__raw = fd.read() fd.close() if ZIPMODULE == 0 : self.zip = ChilkatZip( self.__raw ) else : self.zip = zipfile.ZipFile( StringIO.StringIO( self.__raw ), mode=mode ) # CHECK if there is only one embedded file #self._reload_apk() for i in self.zip.namelist() : if i == "AndroidManifest.xml" : self.xml[i] = minidom.parseString( AXMLPrinter( self.zip.read( i ) ).getBuff() ) self.package = self.xml[i].documentElement.getAttribute( "package" ) self.androidversion["Code"] = self.xml[i].documentElement.getAttribute( "android:versionCode" ) self.androidversion["Name"] = self.xml[i].documentElement.getAttribute( "android:versionName") for item in self.xml[i].getElementsByTagName('uses-permission') : self.permissions.append( str( item.getAttribute("android:name") ) ) self.validAPK = True def get_AndroidManifest(self) : """ Return the Android Manifest XML file """ return self.xml["AndroidManifest.xml"] def is_valid_APK(self) : """ Return true if APK is valid, false otherwise """ return self.validAPK #def _reload_apk(self) : # if len(files) == 1 : # if ".apk" in files[0] : # self.__raw = self.zip.read( files[0] ) # if ZIPMODULE == 0 : # self.zip = ChilkatZip( self.__raw ) # else : # self.zip = zipfile.ZipFile( StringIO.StringIO( self.__raw ) ) def get_filename(self) : """ Return the filename of the APK """ return self.filename def get_package(self) : """ Return the name of the package """ return self.package def get_androidversion_code(self) : """ Return the android version code """ return self.androidversion["Code"] def get_androidversion_name(self) : """ Return the android version name """ return self.androidversion["Name"] def get_files(self) : """ Return the files inside the APK """ return self.zip.namelist() def get_files_types(self) : """ Return the files inside the APK with their types (by using python-magic) """ try : import magic except ImportError : for i in self.get_files() : buffer = self.zip.read( i ) self.files_crc32[ i ] = crc32( buffer ) return self.files if self.files != {} : return self.files builtin_magic = 0 try : getattr(magic, "Magic") except AttributeError : builtin_magic = 1 if builtin_magic : ms = magic.open(magic.MAGIC_NONE) ms.load() for i in self.get_files() : buffer = self.zip.read( i ) self.files[ i ] = ms.buffer( buffer ) self.files[ i ] = self.patch_magic(buffer, self.files[ i ]) self.files_crc32[ i ] = crc32( buffer ) else : m = magic.Magic() for i in self.get_files() : buffer = self.zip.read( i ) self.files[ i ] = m.from_buffer( buffer ) self.files[ i ] = self.patch_magic(buffer, self.files[ i ]) self.files_crc32[ i ] = crc32( buffer ) return self.files def patch_magic(self, buffer, orig) : if ("Zip" in orig) or ("DBase" in orig) : val = androconf.is_android_raw( buffer ) if val == "APK" : return "Android application package file" elif val == "AXML" : return "Android's binary XML" return orig def get_files_crc32(self) : if self.files_crc32 == {} : self.get_files_types() return self.files_crc32 def get_files_information(self) : if self.files == {} : self.get_files_types() for i in self.get_files() : yield i, self.files[ i ], self.files_crc32[ i ] def get_raw(self) : """ Return raw bytes of the APK """ return self.__raw def get_file(self, filename) : """ Return the raw data of the specified filename """ try : return self.zip.read( filename ) except KeyError : return "" def get_dex(self) : """ Return the raw data of the classes dex file """ return self.get_file( "classes.dex" ) def get_elements(self, tag_name, attribute) : """ Return elements in xml files which match with the tag name and the specific attribute @param tag_name : a string which specify the tag name @param attribute : a string which specify the attribute """ l = [] for i in self.xml : for item in self.xml[i].getElementsByTagName(tag_name) : value = item.getAttribute(attribute) value = self.format_value( value ) l.append( str( value ) ) return l def format_value(self, value) : if len(value) > 0 : if value[0] == "." : value = self.package + value else : v_dot = value.find(".") if v_dot == 0 : value = self.package + "." + value elif v_dot == -1 : value = self.package + "." + value return value def get_element(self, tag_name, attribute) : """ Return element in xml files which match with the tag name and the specific attribute @param tag_name : a string which specify the tag name @param attribute : a string which specify the attribute """ for i in self.xml : for item in self.xml[i].getElementsByTagName(tag_name) : value = item.getAttribute(attribute) if len(value) > 0 : return value return None def get_main_activity(self) : """ Return the name of the main activity """ for i in self.xml : x = set() y = set() for item in self.xml[i].getElementsByTagName("activity") : for sitem in item.getElementsByTagName( "action" ) : val = sitem.getAttribute( "android:name" ) if val == "android.intent.action.MAIN" : x.add( item.getAttribute( "android:name" ) ) for sitem in item.getElementsByTagName( "category" ) : val = sitem.getAttribute( "android:name" ) if val == "android.intent.category.LAUNCHER" : y.add( item.getAttribute( "android:name" ) ) z = x.intersection(y) if len(z) > 0 : return self.format_value(z.pop()) return None def get_activities(self) : """ Return the android:name attribute of all activities """ return self.get_elements("activity", "android:name") def get_services(self) : """ Return the android:name attribute of all services """ return self.get_elements("service", "android:name") def get_receivers(self) : """ Return the android:name attribute of all receivers """ return self.get_elements("receiver", "android:name") def get_providers(self) : """ Return the android:name attribute of all providers """ return self.get_elements("provider", "android:name") def get_permissions(self) : """ Return permissions """ return self.permissions def get_details_permissions(self) : """ Return permissions with details """ l = {} for i in self.permissions : perm = i pos = i.rfind(".") if pos != -1 : perm = i[pos+1:] try : l[ i ] = DVM_PERMISSIONS["MANIFEST_PERMISSION"][ perm ] except KeyError : l[ i ] = [ "dangerous", "Unknown permission from android reference", "Unknown permission from android reference" ] return l def get_min_sdk_version(self) : """ Return the android:minSdkVersion attribute """ return self.get_element( "uses-sdk", "android:minSdkVersion" ) def get_target_sdk_version(self) : """ Return the android:targetSdkVersion attribute """ return self.get_element( "uses-sdk", "android:targetSdkVersion" ) def get_libraries(self) : """ Return the android:name attributes for libraries """ return self.get_elements( "uses-library", "android:name" ) def show(self) : self.get_files_types() print "FILES: " for i in self.get_files() : try : print "\t", i, self.files[i], "%x" % self.files_crc32[i] except KeyError : print "\t", i, "%x" % self.files_crc32[i] print "PERMISSIONS: " details_permissions = self.get_details_permissions() for i in details_permissions : print "\t", i, details_permissions[i] print "MAIN ACTIVITY: ", self.get_main_activity() print "ACTIVITIES: ", self.get_activities() print "SERVICES: ", self.get_services() print "RECEIVERS: ", self.get_receivers() print "PROVIDERS: ", self.get_providers() def get_certificate(self, filename) : """ Return a certificate object by giving the name in the apk file """ import chilkat cert = chilkat.CkCert() f = self.get_file( filename ) success = cert.LoadFromBinary(f, len(f)) return success, cert def new_zip(self, filename, deleted_files=None, new_files={}) : zout = zipfile.ZipFile (filename, 'w') for item in self.zip.infolist() : if deleted_files != None : if re.match(deleted_files, item.filename) == None : if item.filename in new_files : zout.writestr(item, new_files[item.filename]) else : buffer = self.zip.read(item.filename) zout.writestr(item, buffer) zout.close() def show_Certificate(cert) : print "Issuer: C=%s, CN=%s, DN=%s, E=%s, L=%s, O=%s, OU=%s, S=%s" % (cert.issuerC(), cert.issuerCN(), cert.issuerDN(), cert.issuerE(), cert.issuerL(), cert.issuerO(), cert.issuerOU(), cert.issuerS()) print "Subject: C=%s, CN=%s, DN=%s, E=%s, L=%s, O=%s, OU=%s, S=%s" % (cert.subjectC(), cert.subjectCN(), cert.subjectDN(), cert.subjectE(), cert.subjectL(), cert.subjectO(), cert.subjectOU(), cert.subjectS()) ######################################################## AXML FORMAT ######################################################## # Translated from http://code.google.com/p/android4me/source/browse/src/android/content/res/AXmlResourceParser.java class StringBlock : def __init__(self, buff) : buff.read( 4 ) self.chunkSize = SV( '<L', buff.read( 4 ) ) self.stringCount = SV( '<L', buff.read( 4 ) ) self.styleOffsetCount = SV( '<L', buff.read( 4 ) ) # unused value ? buff.read(4) # ? self.stringsOffset = SV( '<L', buff.read( 4 ) ) self.stylesOffset = SV( '<L', buff.read( 4 ) ) self.m_stringOffsets = [] self.m_styleOffsets = [] self.m_strings = [] self.m_styles = [] for i in range(0, self.stringCount.get_value()) : self.m_stringOffsets.append( SV( '<L', buff.read( 4 ) ) ) for i in range(0, self.styleOffsetCount.get_value()) : self.m_stylesOffsets.append( SV( '<L', buff.read( 4 ) ) ) size = self.chunkSize.get_value() - self.stringsOffset.get_value() if self.stylesOffset.get_value() != 0 : size = self.stylesOffset.get_value() - self.stringsOffset.get_value() # FIXME if (size%4) != 0 : pass for i in range(0, size / 4) : self.m_strings.append( SV( '=L', buff.read( 4 ) ) ) if self.stylesOffset.get_value() != 0 : size = self.chunkSize.get_value() - self.stringsOffset.get_value() # FIXME if (size%4) != 0 : pass for i in range(0, size / 4) : self.m_styles.append( SV( '=L', buff.read( 4 ) ) ) def getRaw(self, idx) : if idx < 0 or self.m_stringOffsets == [] or idx >= len(self.m_stringOffsets) : return None offset = self.m_stringOffsets[ idx ].get_value() length = self.getShort(self.m_strings, offset) data = "" while length > 0 : offset += 2 # Unicode character data += unichr( self.getShort(self.m_strings, offset) ) # FIXME if data[-1] == "&" : data = data[:-1] length -= 1 return data def getShort(self, array, offset) : value = array[offset/4].get_value() if ((offset%4)/2) == 0 : return value & 0xFFFF else : return value >> 16 ATTRIBUTE_IX_NAMESPACE_URI = 0 ATTRIBUTE_IX_NAME = 1 ATTRIBUTE_IX_VALUE_STRING = 2 ATTRIBUTE_IX_VALUE_TYPE = 3 ATTRIBUTE_IX_VALUE_DATA = 4 ATTRIBUTE_LENGHT = 5 CHUNK_AXML_FILE = 0x00080003 CHUNK_RESOURCEIDS = 0x00080180 CHUNK_XML_FIRST = 0x00100100 CHUNK_XML_START_NAMESPACE = 0x00100100 CHUNK_XML_END_NAMESPACE = 0x00100101 CHUNK_XML_START_TAG = 0x00100102 CHUNK_XML_END_TAG = 0x00100103 CHUNK_XML_TEXT = 0x00100104 CHUNK_XML_LAST = 0x00100104 START_DOCUMENT = 0 END_DOCUMENT = 1 START_TAG = 2 END_TAG = 3 TEXT = 4 class AXMLParser : def __init__(self, raw_buff) : self.reset() self.buff = bytecode.BuffHandle( raw_buff ) self.buff.read(4) self.buff.read(4) self.sb = StringBlock( self.buff ) self.m_resourceIDs = [] self.m_prefixuri = {} self.m_uriprefix = {} self.m_prefixuriL = [] def reset(self) : self.m_event = -1 self.m_lineNumber = -1 self.m_name = -1 self.m_namespaceUri = -1 self.m_attributes = [] self.m_idAttribute = -1 self.m_classAttribute = -1 self.m_styleAttribute = -1 def next(self) : self.doNext() return self.m_event def doNext(self) : if self.m_event == END_DOCUMENT : return event = self.m_event self.reset() while 1 : chunkType = -1 # Fake END_DOCUMENT event. if event == END_TAG : pass # START_DOCUMENT if event == START_DOCUMENT : chunkType = CHUNK_XML_START_TAG else : if self.buff.end() == True : self.m_event = END_DOCUMENT break chunkType = SV( '<L', self.buff.read( 4 ) ).get_value() if chunkType == CHUNK_RESOURCEIDS : chunkSize = SV( '<L', self.buff.read( 4 ) ).get_value() # FIXME if chunkSize < 8 or chunkSize%4 != 0 : raise("ooo") for i in range(0, chunkSize/4-2) : self.m_resourceIDs.append( SV( '<L', self.buff.read( 4 ) ) ) continue # FIXME if chunkType < CHUNK_XML_FIRST or chunkType > CHUNK_XML_LAST : raise("ooo") # Fake START_DOCUMENT event. if chunkType == CHUNK_XML_START_TAG and event == -1 : self.m_event = START_DOCUMENT break self.buff.read( 4 ) #/*chunkSize*/ lineNumber = SV( '<L', self.buff.read( 4 ) ).get_value() self.buff.read( 4 ) #0xFFFFFFFF if chunkType == CHUNK_XML_START_NAMESPACE or chunkType == CHUNK_XML_END_NAMESPACE : if chunkType == CHUNK_XML_START_NAMESPACE : prefix = SV( '<L', self.buff.read( 4 ) ).get_value() uri = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_prefixuri[ prefix ] = uri self.m_uriprefix[ uri ] = prefix self.m_prefixuriL.append( (prefix, uri) ) else : self.buff.read( 4 ) self.buff.read( 4 ) (prefix, uri) = self.m_prefixuriL.pop() #del self.m_prefixuri[ prefix ] #del self.m_uriprefix[ uri ] continue self.m_lineNumber = lineNumber if chunkType == CHUNK_XML_START_TAG : self.m_namespaceUri = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_name = SV( '<L', self.buff.read( 4 ) ).get_value() # FIXME self.buff.read( 4 ) #flags attributeCount = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_idAttribute = (attributeCount>>16) - 1 attributeCount = attributeCount & 0xFFFF self.m_classAttribute = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_styleAttribute = (self.m_classAttribute>>16) - 1 self.m_classAttribute = (self.m_classAttribute & 0xFFFF) - 1 for i in range(0, attributeCount*ATTRIBUTE_LENGHT) : self.m_attributes.append( SV( '<L', self.buff.read( 4 ) ).get_value() ) for i in range(ATTRIBUTE_IX_VALUE_TYPE, len(self.m_attributes), ATTRIBUTE_LENGHT) : self.m_attributes[i] = (self.m_attributes[i]>>24) self.m_event = START_TAG break if chunkType == CHUNK_XML_END_TAG : self.m_namespaceUri = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_name = SV( '<L', self.buff.read( 4 ) ).get_value() self.m_event = END_TAG break if chunkType == CHUNK_XML_TEXT : self.m_name = SV( '<L', self.buff.read( 4 ) ).get_value() # FIXME self.buff.read( 4 ) #? self.buff.read( 4 ) #? self.m_event = TEXT break def getPrefixByUri(self, uri) : try : return self.m_uriprefix[ uri ] except KeyError : return -1 def getPrefix(self) : try : return self.sb.getRaw(self.m_prefixuri[ self.m_namespaceUri ]) except KeyError : return "" def getName(self) : if self.m_name == -1 or (self.m_event != START_TAG and self.m_event != END_TAG) : return "" return self.sb.getRaw(self.m_name) def getText(self) : if self.m_name == -1 or self.m_event != TEXT : return "" return self.sb.getRaw(self.m_name) def getNamespacePrefix(self, pos) : prefix = self.m_prefixuriL[ pos ][0] return self.sb.getRaw( prefix ) def getNamespaceUri(self, pos) : uri = self.m_prefixuriL[ pos ][1] return self.sb.getRaw( uri ) def getXMLNS(self) : buff = "" i = 0 while 1 : try : buff += "xmlns:%s=\"%s\"\n" % ( self.getNamespacePrefix( i ), self.getNamespaceUri( i ) ) except IndexError: break i += 1 return buff def getNamespaceCount(self, pos) : pass def getAttributeOffset(self, index) : # FIXME if self.m_event != START_TAG : raise("Current event is not START_TAG.") offset = index * 5 # FIXME if offset >= len(self.m_attributes) : raise("Invalid attribute index") return offset def getAttributeCount(self) : if self.m_event != START_TAG : return -1 return len(self.m_attributes) / ATTRIBUTE_LENGHT def getAttributePrefix(self, index) : offset = self.getAttributeOffset(index) uri = self.m_attributes[offset+ATTRIBUTE_IX_NAMESPACE_URI] prefix = self.getPrefixByUri( uri ) if prefix == -1 : return "" return self.sb.getRaw( prefix ) def getAttributeName(self, index) : offset = self.getAttributeOffset(index) name = self.m_attributes[offset+ATTRIBUTE_IX_NAME] if name == -1 : return "" return self.sb.getRaw( name ) def getAttributeValueType(self, index) : offset = self.getAttributeOffset(index) return self.m_attributes[offset+ATTRIBUTE_IX_VALUE_TYPE] def getAttributeValueData(self, index) : offset = self.getAttributeOffset(index) return self.m_attributes[offset+ATTRIBUTE_IX_VALUE_DATA] def getAttributeValue(self, index) : offset = self.getAttributeOffset(index) valueType = self.m_attributes[offset+ATTRIBUTE_IX_VALUE_TYPE] if valueType == TYPE_STRING : valueString = self.m_attributes[offset+ATTRIBUTE_IX_VALUE_STRING] return self.sb.getRaw( valueString ) # WIP return "" #int valueData=m_attributes[offset+ATTRIBUTE_IX_VALUE_DATA]; #return TypedValue.coerceToString(valueType,valueData); TYPE_ATTRIBUTE = 2 TYPE_DIMENSION = 5 TYPE_FIRST_COLOR_INT = 28 TYPE_FIRST_INT = 16 TYPE_FLOAT = 4 TYPE_FRACTION = 6 TYPE_INT_BOOLEAN = 18 TYPE_INT_COLOR_ARGB4 = 30 TYPE_INT_COLOR_ARGB8 = 28 TYPE_INT_COLOR_RGB4 = 31 TYPE_INT_COLOR_RGB8 = 29 TYPE_INT_DEC = 16 TYPE_INT_HEX = 17 TYPE_LAST_COLOR_INT = 31 TYPE_LAST_INT = 31 TYPE_NULL = 0 TYPE_REFERENCE = 1 TYPE_STRING = 3 RADIX_MULTS = [ 0.00390625, 3.051758E-005, 1.192093E-007, 4.656613E-010 ] DIMENSION_UNITS = [ "px","dip","sp","pt","in","mm","","" ] FRACTION_UNITS = [ "%","%p","","","","","","" ] COMPLEX_UNIT_MASK = 15 class AXMLPrinter : def __init__(self, raw_buff) : self.axml = AXMLParser( raw_buff ) self.xmlns = False self.buff = "" while 1 : _type = self.axml.next() # print "tagtype = ", _type if _type == START_DOCUMENT : self.buff += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" elif _type == START_TAG : self.buff += "<%s%s\n" % ( self.getPrefix( self.axml.getPrefix() ), self.axml.getName() ) # FIXME : use namespace if self.xmlns == False : self.buff += self.axml.getXMLNS() self.xmlns = True for i in range(0, self.axml.getAttributeCount()) : self.buff += "%s%s=\"%s\"\n" % ( self.getPrefix( self.axml.getAttributePrefix(i) ), self.axml.getAttributeName(i), self._escape( self.getAttributeValue( i ) ) ) self.buff += ">\n" elif _type == END_TAG : self.buff += "</%s%s>\n" % ( self.getPrefix( self.axml.getPrefix() ), self.axml.getName() ) elif _type == TEXT : self.buff += "%s\n" % self.axml.getText() elif _type == END_DOCUMENT : break # pleed patch def _escape(self, s) : s = s.replace("&","&amp;") s = s.replace('"',"&quot;") s = s.replace("'","&apos;") s = s.replace("<","&lt;") s = s.replace(">","&gt;") return escape(s) def getBuff(self) : return self.buff.encode("utf-8") def getPrefix(self, prefix) : if prefix == None or len(prefix) == 0 : return "" return prefix + ":" def getAttributeValue(self, index) : _type = self.axml.getAttributeValueType(index) _data = self.axml.getAttributeValueData(index) #print _type, _data if _type == TYPE_STRING : return self.axml.getAttributeValue( index ) elif _type == TYPE_ATTRIBUTE : return "?%s%08X" % (self.getPackage(_data), _data) elif _type == TYPE_REFERENCE : return "@%s%08X" % (self.getPackage(_data), _data) # WIP elif _type == TYPE_FLOAT : return "%f" % unpack("=f", pack("=L", _data))[0] elif _type == TYPE_INT_HEX : return "0x%08X" % _data elif _type == TYPE_INT_BOOLEAN : if _data == 0 : return "false" return "true" elif _type == TYPE_DIMENSION : return "%f%s" % (self.complexToFloat(_data), DIMENSION_UNITS[_data & COMPLEX_UNIT_MASK]) elif _type == TYPE_FRACTION : return "%f%s" % (self.complexToFloat(_data), FRACTION_UNITS[_data & COMPLEX_UNIT_MASK]) elif _type >= TYPE_FIRST_COLOR_INT and _type <= TYPE_LAST_COLOR_INT : return "#%08X" % _data elif _type >= TYPE_FIRST_INT and _type <= TYPE_LAST_INT : return "%d" % androconf.long2int( _data ) return "<0x%X, type 0x%02X>" % (_data, _type) def complexToFloat(self, xcomplex) : return (float)(xcomplex & 0xFFFFFF00)*RADIX_MULTS[(xcomplex>>4) & 3]; def getPackage(self, id) : if id >> 24 == 1 : return "android:" return ""
Python
DVM_PERMISSIONS_BY_PERMISSION = { "BIND_DEVICE_ADMIN" : { "Landroid/app/admin/DeviceAdminReceiver;" : [ ("C", "ACTION_DEVICE_ADMIN_ENABLED", "Ljava/lang/String;"), ], "Landroid/app/admin/DevicePolicyManager;" : [ ("F", "getRemoveWarning", "(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)"), ("F", "reportFailedPasswordAttempt", "()"), ("F", "reportSuccessfulPasswordAttempt", "()"), ("F", "setActiveAdmin", "(Landroid/content/ComponentName;)"), ("F", "setActivePasswordState", "(I I)"), ], "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;" : [ ("F", "getRemoveWarning", "(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)"), ("F", "reportFailedPasswordAttempt", "()"), ("F", "reportSuccessfulPasswordAttempt", "()"), ("F", "setActiveAdmin", "(Landroid/content/ComponentName;)"), ("F", "setActivePasswordState", "(I I)"), ], }, "READ_SYNC_SETTINGS" : { "Landroid/app/ContextImpl$ApplicationContentResolver;" : [ ("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getMasterSyncAutomatically", "()"), ("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/ContentService;" : [ ("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getMasterSyncAutomatically", "()"), ("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/ContentResolver;" : [ ("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getMasterSyncAutomatically", "()"), ("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/IContentService$Stub$Proxy;" : [ ("F", "getIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getMasterSyncAutomatically", "()"), ("F", "getPeriodicSyncs", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "getSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], }, "FACTORY_TEST" : { "Landroid/content/pm/ApplicationInfo;" : [ ("C", "FLAG_FACTORY_TEST", "I"), ("C", "flags", "I"), ], "Landroid/content/Intent;" : [ ("C", "IntentResolution", "Ljava/lang/String;"), ("C", "ACTION_FACTORY_TEST", "Ljava/lang/String;"), ], }, "SET_ALWAYS_FINISH" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "setAlwaysFinish", "(B)"), ], }, "READ_CALENDAR" : { "Landroid/provider/Calendar$CalendarAlerts;" : [ ("F", "alarmExists", "(Landroid/content/ContentResolver; J J J)"), ("F", "findNextAlarmTime", "(Landroid/content/ContentResolver; J)"), ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"), ], "Landroid/provider/Calendar$Calendars;" : [ ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/provider/Calendar$Events;" : [ ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"), ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"), ], "Landroid/provider/Calendar$Instances;" : [ ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J Ljava/lang/String; Ljava/lang/String;)"), ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J)"), ], "Landroid/provider/Calendar$EventDays;" : [ ("F", "query", "(Landroid/content/ContentResolver; I I)"), ], }, "ACCESS_DRM" : { "Landroid/provider/DrmStore;" : [ ("F", "enforceAccessDrmPermission", "(Landroid/content/Context;)"), ], }, "CHANGE_CONFIGURATION" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "updateConfiguration", "(Landroid/content/res/Configuration;)"), ], }, "SET_ACTIVITY_WATCHER" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "profileControl", "(Ljava/lang/String; B Ljava/lang/String; Landroid/os/ParcelFileDescriptor;)"), ("F", "setActivityController", "(Landroid/app/IActivityController;)"), ], }, "GET_PACKAGE_SIZE" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "getPackageSizeInfo", "(Ljava/lang/String; LIPackageStatsObserver;)"), ("F", "getPackageSizeInfo", "(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "getPackageSizeInfo", "(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)"), ], }, "CONTROL_LOCATION_UPDATES" : { "Landroid/telephony/TelephonyManager;" : [ ("F", "disableLocationUpdates", "()"), ("F", "enableLocationUpdates", "()"), ], "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [ ("F", "disableLocationUpdates", "()"), ("F", "enableLocationUpdates", "()"), ], }, "CLEAR_APP_CACHE" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "freeStorage", "(J LIntentSender;)"), ("F", "freeStorageAndNotify", "(J LIPackageDataObserver;)"), ("F", "freeStorage", "(J Landroid/content/IntentSender;)"), ("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "freeStorage", "(J Landroid/content/IntentSender;)"), ("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "freeStorage", "(J Landroid/content/IntentSender;)"), ("F", "freeStorageAndNotify", "(J Landroid/content/pm/IPackageDataObserver;)"), ], }, "BIND_INPUT_METHOD" : { "Landroid/view/inputmethod/InputMethod;" : [ ("C", "SERVICE_INTERFACE", "Ljava/lang/String;"), ], }, "SIGNAL_PERSISTENT_PROCESSES" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "signalPersistentProcesses", "(I)"), ], }, "BATTERY_STATS" : { "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;" : [ ("F", "getAwakeTimeBattery", "()"), ("F", "getAwakeTimePlugged", "()"), ("F", "getStatistics", "()"), ], }, "AUTHENTICATE_ACCOUNTS" : { "Landroid/accounts/AccountManager;" : [ ("F", "addAccountExplicitly", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getPassword", "(Landroid/accounts/Account;)"), ("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ("F", "addAccountExplicitly", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getPassword", "(Landroid/accounts/Account;)"), ("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/accounts/AccountManagerService;" : [ ("F", "addAccount", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "checkAuthenticateAccountsPermission", "(Landroid/accounts/Account;)"), ("F", "getPassword", "(Landroid/accounts/Account;)"), ("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/accounts/IAccountManager$Stub$Proxy;" : [ ("F", "addAccount", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getPassword", "(Landroid/accounts/Account;)"), ("F", "getUserData", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "peekAuthToken", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setPassword", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "setUserData", "(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)"), ], }, "CHANGE_BACKGROUND_DATA_SETTING" : { "Landroid/net/IConnectivityManager$Stub$Proxy;" : [ ("F", "setBackgroundDataSetting", "(B)"), ], "Landroid/net/ConnectivityManager;" : [ ("F", "setBackgroundDataSetting", "(B)"), ], }, "RESTART_PACKAGES" : { "Landroid/app/ActivityManagerNative;" : [ ("F", "killBackgroundProcesses", "(Ljava/lang/String;)"), ("F", "restartPackage", "(Ljava/lang/String;)"), ], "Landroid/app/ActivityManager;" : [ ("F", "killBackgroundProcesses", "(Ljava/lang/String;)"), ("F", "restartPackage", "(Ljava/lang/String;)"), ], }, "CALL_PRIVILEGED" : { "Landroid/telephony/TelephonyManager;" : [ ("F", "getCompleteVoiceMailNumber", "()"), ], "Landroid/telephony/PhoneNumberUtils;" : [ ("F", "getNumberFromIntent", "(Landroid/content/Intent; Landroid/content/Context;)"), ], }, "SET_WALLPAPER_COMPONENT" : { "Landroid/app/IWallpaperManager$Stub$Proxy;" : [ ("F", "setWallpaperComponent", "(Landroid/content/ComponentName;)"), ], }, "DISABLE_KEYGUARD" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "disableKeyguard", "(Landroid/os/IBinder; Ljava/lang/String;)"), ("F", "exitKeyguardSecurely", "(Landroid/view/IOnKeyguardExitResult;)"), ("F", "reenableKeyguard", "(Landroid/os/IBinder;)"), ], "Landroid/app/KeyguardManager;" : [ ("F", "exitKeyguardSecurely", "(Landroid/app/KeyguardManager$OnKeyguardExitResult;)"), ], "Landroid/app/KeyguardManager$KeyguardLock;" : [ ("F", "disableKeyguard", "()"), ("F", "reenableKeyguard", "()"), ], }, "DELETE_PACKAGES" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"), ("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "deletePackage", "(Ljava/lang/String; LIPackageDeleteObserver; I)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "deletePackage", "(Ljava/lang/String; Landroid/content/pm/IPackageDeleteObserver; I)"), ], }, "CHANGE_COMPONENT_ENABLED_STATE" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"), ("F", "setComponentEnabledSetting", "(LComponentName; I I)"), ("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"), ("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"), ("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "setApplicationEnabledSetting", "(Ljava/lang/String; I I)"), ("F", "setComponentEnabledSetting", "(Landroid/content/ComponentName; I I)"), ], }, "ASEC_ACCESS" : { "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "getSecureContainerList", "()"), ("F", "getSecureContainerPath", "(Ljava/lang/String;)"), ("F", "isSecureContainerMounted", "(Ljava/lang/String;)"), ], }, "UPDATE_DEVICE_STATS " : { "Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [ ("F", "noteLaunchTime", "(LComponentName;)"), ], }, "RECORD_AUDIO" : { "Landroid/net/sip/SipAudioCall;" : [ ("F", "startAudio", "()"), ], "Landroid/media/MediaRecorder;" : [ ("F", "setAudioSource", "(I)"), ], "Landroid/speech/SpeechRecognizer;" : [ ("F", "cancel", "()"), ("F", "handleCancelMessage", "()"), ("F", "handleStartListening", "(Landroid/content/Intent;)"), ("F", "handleStopMessage", "()"), ("F", "startListening", "(Landroid/content/Intent;)"), ("F", "stopListening", "()"), ], "Landroid/media/AudioRecord;" : [ ("F", "<init>", "(I I I I I)"), ], }, "ACCESS_MOCK_LOCATION" : { "Landroid/location/LocationManager;" : [ ("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"), ("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"), ("F", "clearTestProviderLocation", "(Ljava/lang/String;)"), ("F", "clearTestProviderStatus", "(Ljava/lang/String;)"), ("F", "removeTestProvider", "(Ljava/lang/String;)"), ("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"), ("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"), ("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"), ("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"), ("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"), ("F", "clearTestProviderLocation", "(Ljava/lang/String;)"), ("F", "clearTestProviderStatus", "(Ljava/lang/String;)"), ("F", "removeTestProvider", "(Ljava/lang/String;)"), ("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"), ("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"), ("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"), ], "Landroid/location/ILocationManager$Stub$Proxy;" : [ ("F", "addTestProvider", "(Ljava/lang/String; B B B B B B B I I)"), ("F", "clearTestProviderEnabled", "(Ljava/lang/String;)"), ("F", "clearTestProviderLocation", "(Ljava/lang/String;)"), ("F", "clearTestProviderStatus", "(Ljava/lang/String;)"), ("F", "removeTestProvider", "(Ljava/lang/String;)"), ("F", "setTestProviderEnabled", "(Ljava/lang/String; B)"), ("F", "setTestProviderLocation", "(Ljava/lang/String; Landroid/location/Location;)"), ("F", "setTestProviderStatus", "(Ljava/lang/String; I Landroid/os/Bundle; J)"), ], }, "VIBRATE" : { "Landroid/media/AudioManager;" : [ ("C", "EXTRA_RINGER_MODE", "Ljava/lang/String;"), ("C", "EXTRA_VIBRATE_SETTING", "Ljava/lang/String;"), ("C", "EXTRA_VIBRATE_TYPE", "Ljava/lang/String;"), ("C", "FLAG_REMOVE_SOUND_AND_VIBRATE", "I"), ("C", "FLAG_VIBRATE", "I"), ("C", "RINGER_MODE_VIBRATE", "I"), ("C", "VIBRATE_SETTING_CHANGED_ACTION", "Ljava/lang/String;"), ("C", "VIBRATE_SETTING_OFF", "I"), ("C", "VIBRATE_SETTING_ON", "I"), ("C", "VIBRATE_SETTING_ONLY_SILENT", "I"), ("C", "VIBRATE_TYPE_NOTIFICATION", "I"), ("C", "VIBRATE_TYPE_RINGER", "I"), ("F", "getRingerMode", "()"), ("F", "getVibrateSetting", "(I)"), ("F", "setRingerMode", "(I)"), ("F", "setVibrateSetting", "(I I)"), ("F", "shouldVibrate", "(I)"), ], "Landroid/os/Vibrator;" : [ ("F", "cancel", "()"), ("F", "vibrate", "([L; I)"), ("F", "vibrate", "(J)"), ], "Landroid/provider/Settings/System;" : [ ("C", "VIBRATE_ON", "Ljava/lang/String;"), ], "Landroid/app/NotificationManager;" : [ ("F", "notify", "(I Landroid/app/Notification;)"), ("F", "notify", "(Ljava/lang/String; I Landroid/app/Notification;)"), ], "Landroid/app/Notification/Builder;" : [ ("F", "setDefaults", "(I)"), ], "Landroid/os/IVibratorService$Stub$Proxy;" : [ ("F", "cancelVibrate", "(Landroid/os/IBinder;)"), ("F", "vibrate", "(J Landroid/os/IBinder;)"), ("F", "vibratePattern", "([L; I Landroid/os/IBinder;)"), ], "Landroid/app/Notification;" : [ ("C", "DEFAULT_VIBRATE", "I"), ("C", "defaults", "I"), ], }, "ASEC_CREATE" : { "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "createSecureContainer", "(Ljava/lang/String; I Ljava/lang/String; Ljava/lang/String; I)"), ("F", "finalizeSecureContainer", "(Ljava/lang/String;)"), ], }, "WRITE_SECURE_SETTINGS" : { "Landroid/bluetooth/BluetoothAdapter;" : [ ("F", "setScanMode", "(I I)"), ("F", "setScanMode", "(I)"), ], "Landroid/server/BluetoothService;" : [ ("F", "setScanMode", "(I I)"), ], "Landroid/os/IPowerManager$Stub$Proxy;" : [ ("F", "setMaximumScreenOffTimeount", "(I)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "setInstallLocation", "(I)"), ], "Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [ ("F", "setScanMode", "(I I)"), ], }, "SET_ORIENTATION" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "setRotation", "(I B I)"), ], }, "PACKAGE_USAGE_STATS" : { "Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [ ("F", "getAllPkgUsageStats", "()"), ("F", "getPkgUsageStats", "(LComponentName;)"), ], }, "FLASHLIGHT" : { "Landroid/os/IHardwareService$Stub$Proxy;" : [ ("F", "setFlashlightEnabled", "(B)"), ], }, "GLOBAL_SEARCH" : { "Landroid/app/SearchManager;" : [ ("C", "EXTRA_SELECT_QUERY", "Ljava/lang/String;"), ("C", "INTENT_ACTION_GLOBAL_SEARCH", "Ljava/lang/String;"), ], "Landroid/server/search/Searchables;" : [ ("F", "buildSearchableList", "()"), ("F", "findGlobalSearchActivity", "()"), ], }, "CHANGE_WIFI_STATE" : { "Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [ ("F", "addOrUpdateNetwork", "(Landroid/net/wifi/WifiConfiguration;)"), ("F", "disableNetwork", "(I)"), ("F", "disconnect", "()"), ("F", "enableNetwork", "(I B)"), ("F", "pingSupplicant", "()"), ("F", "reassociate", "()"), ("F", "reconnect", "()"), ("F", "removeNetwork", "(I)"), ("F", "saveConfiguration", "()"), ("F", "setNumAllowedChannels", "(I B)"), ("F", "setWifiApEnabled", "(Landroid/net/wifi/WifiConfiguration; B)"), ("F", "setWifiEnabled", "(B)"), ("F", "startScan", "(B)"), ], "Landroid/net/wifi/WifiManager;" : [ ("F", "addNetwork", "(Landroid/net/wifi/WifiConfiguration;)"), ("F", "addOrUpdateNetwork", "(Landroid/net/wifi/WifiConfiguration;)"), ("F", "disableNetwork", "(I)"), ("F", "disconnect", "()"), ("F", "enableNetwork", "(I B)"), ("F", "pingSupplicant", "()"), ("F", "reassociate", "()"), ("F", "reconnect", "()"), ("F", "removeNetwork", "(I)"), ("F", "saveConfiguration", "()"), ("F", "setNumAllowedChannels", "(I B)"), ("F", "setWifiApEnabled", "(Landroid/net/wifi/WifiConfiguration; B)"), ("F", "setWifiEnabled", "(B)"), ("F", "startScan", "()"), ("F", "startScanActive", "()"), ], }, "BROADCAST_STICKY" : { "Landroid/app/ExpandableListActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/accessibilityservice/AccessibilityService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/accounts/GrantCredentialsPermissionActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/backup/BackupAgent;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/service/wallpaper/WallpaperService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/backup/BackupAgentHelper;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/accounts/AccountAuthenticatorActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "unbroadcastIntent", "(Landroid/app/IApplicationThread; Landroid/content/Intent;)"), ], "Landroid/app/ActivityGroup;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/content/ContextWrapper;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/Activity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/ContextImpl;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/AliasActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/content/Context;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/service/urlrenderer/UrlRendererService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/FullBackupAgent;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/TabActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/view/ContextThemeWrapper;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/speech/RecognitionService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/IntentService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/inputmethodservice/AbstractInputMethodService;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/Application;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/ListActivity;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/app/Service;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/content/MutableContextWrapper;" : [ ("F", "removeStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyBroadcast", "(Landroid/content/Intent;)"), ("F", "sendStickyOrderedBroadcast", "(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)"), ], }, "FORCE_STOP_PACKAGES" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "forceStopPackage", "(Ljava/lang/String;)"), ], "Landroid/app/ActivityManagerNative;" : [ ("F", "forceStopPackage", "(Ljava/lang/String;)"), ], "Landroid/app/ActivityManager;" : [ ("F", "forceStopPackage", "(Ljava/lang/String;)"), ], }, "KILL_BACKGROUND_PROCESSES" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "killBackgroundProcesses", "(Ljava/lang/String;)"), ], "Landroid/app/ActivityManager;" : [ ("F", "killBackgroundProcesses", "(Ljava/lang/String;)"), ], }, "SET_TIME_ZONE" : { "Landroid/app/AlarmManager;" : [ ("F", "setTimeZone", "(Ljava/lang/String;)"), ("F", "setTimeZone", "(Ljava/lang/String;)"), ], "Landroid/app/IAlarmManager$Stub$Proxy;" : [ ("F", "setTimeZone", "(Ljava/lang/String;)"), ], }, "BLUETOOTH_ADMIN" : { "Landroid/server/BluetoothA2dpService;" : [ ("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/bluetooth/BluetoothPbap;" : [ ("F", "disconnect", "()"), ], "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;" : [ ("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/bluetooth/BluetoothAdapter;" : [ ("F", "cancelDiscovery", "()"), ("F", "disable", "()"), ("F", "enable", "()"), ("F", "setName", "(Ljava/lang/String;)"), ("F", "startDiscovery", "()"), ("F", "cancelDiscovery", "()"), ("F", "disable", "()"), ("F", "enable", "()"), ("F", "setDiscoverableTimeout", "(I)"), ("F", "setName", "(Ljava/lang/String;)"), ("F", "startDiscovery", "()"), ], "Landroid/server/BluetoothService;" : [ ("F", "cancelBondProcess", "(Ljava/lang/String;)"), ("F", "cancelDiscovery", "()"), ("F", "cancelPairingUserInput", "(Ljava/lang/String;)"), ("F", "createBond", "(Ljava/lang/String;)"), ("F", "disable", "()"), ("F", "disable", "(B)"), ("F", "enable", "()"), ("F", "enable", "(B)"), ("F", "removeBond", "(Ljava/lang/String;)"), ("F", "setDiscoverableTimeout", "(I)"), ("F", "setName", "(Ljava/lang/String;)"), ("F", "setPairingConfirmation", "(Ljava/lang/String; B)"), ("F", "setPasskey", "(Ljava/lang/String; I)"), ("F", "setPin", "(Ljava/lang/String; [L;)"), ("F", "setTrust", "(Ljava/lang/String; B)"), ("F", "startDiscovery", "()"), ], "Landroid/bluetooth/BluetoothHeadset;" : [ ("F", "connectHeadset", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnectHeadset", "()"), ("F", "setPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ], "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;" : [ ("F", "connectHeadset", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnectHeadset", "()"), ("F", "setPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ], "Landroid/bluetooth/BluetoothDevice;" : [ ("F", "cancelBondProcess", "()"), ("F", "cancelPairingUserInput", "()"), ("F", "createBond", "()"), ("F", "removeBond", "()"), ("F", "setPairingConfirmation", "(B)"), ("F", "setPasskey", "(I)"), ("F", "setPin", "([L;)"), ], "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;" : [ ("F", "connect", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnect", "()"), ], "Landroid/bluetooth/BluetoothA2dp;" : [ ("F", "connectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "disconnectSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "resumeSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "setSinkPriority", "(Landroid/bluetooth/BluetoothDevice; I)"), ("F", "suspendSink", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [ ("F", "cancelBondProcess", "(Ljava/lang/String;)"), ("F", "cancelDiscovery", "()"), ("F", "cancelPairingUserInput", "(Ljava/lang/String;)"), ("F", "createBond", "(Ljava/lang/String;)"), ("F", "disable", "(B)"), ("F", "enable", "()"), ("F", "removeBond", "(Ljava/lang/String;)"), ("F", "setDiscoverableTimeout", "(I)"), ("F", "setName", "(Ljava/lang/String;)"), ("F", "setPairingConfirmation", "(Ljava/lang/String; B)"), ("F", "setPasskey", "(Ljava/lang/String; I)"), ("F", "setPin", "(Ljava/lang/String; [L;)"), ("F", "setTrust", "(Ljava/lang/String; B)"), ("F", "startDiscovery", "()"), ], }, "INJECT_EVENTS" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "injectKeyEvent", "(Landroid/view/KeyEvent; B)"), ("F", "injectPointerEvent", "(Landroid/view/MotionEvent; B)"), ("F", "injectTrackballEvent", "(Landroid/view/MotionEvent; B)"), ], "Landroid/app/Instrumentation;" : [ ("F", "invokeContextMenuAction", "(Landroid/app/Activity; I I)"), ("F", "sendCharacterSync", "(I)"), ("F", "sendKeyDownUpSync", "(I)"), ("F", "sendKeySync", "(Landroid/view/KeyEvent;)"), ("F", "sendPointerSync", "(Landroid/view/MotionEvent;)"), ("F", "sendStringSync", "(Ljava/lang/String;)"), ("F", "sendTrackballEventSync", "(Landroid/view/MotionEvent;)"), ], }, "CAMERA" : { "Landroid/hardware/Camera/ErrorCallback;" : [ ("F", "onError", "(I Landroid/hardware/Camera;)"), ], "Landroid/media/MediaRecorder;" : [ ("F", "setVideoSource", "(I)"), ], "Landroid/view/KeyEvent;" : [ ("C", "KEYCODE_CAMERA", "I"), ], "Landroid/bluetooth/BluetoothClass/Device;" : [ ("C", "AUDIO_VIDEO_VIDEO_CAMERA", "I"), ], "Landroid/provider/MediaStore;" : [ ("C", "INTENT_ACTION_STILL_IMAGE_CAMERA", "Ljava/lang/String;"), ("C", "INTENT_ACTION_VIDEO_CAMERA", "Ljava/lang/String;"), ], "Landroid/hardware/Camera/CameraInfo;" : [ ("C", "CAMERA_FACING_BACK", "I"), ("C", "CAMERA_FACING_FRONT", "I"), ("C", "facing", "I"), ], "Landroid/provider/ContactsContract/StatusColumns;" : [ ("C", "CAPABILITY_HAS_CAMERA", "I"), ], "Landroid/hardware/Camera/Parameters;" : [ ("F", "setRotation", "(I)"), ], "Landroid/media/MediaRecorder/VideoSource;" : [ ("C", "CAMERA", "I"), ], "Landroid/content/Intent;" : [ ("C", "IntentResolution", "Ljava/lang/String;"), ("C", "ACTION_CAMERA_BUTTON", "Ljava/lang/String;"), ], "Landroid/content/pm/PackageManager;" : [ ("C", "FEATURE_CAMERA", "Ljava/lang/String;"), ("C", "FEATURE_CAMERA_AUTOFOCUS", "Ljava/lang/String;"), ("C", "FEATURE_CAMERA_FLASH", "Ljava/lang/String;"), ("C", "FEATURE_CAMERA_FRONT", "Ljava/lang/String;"), ], "Landroid/hardware/Camera;" : [ ("C", "CAMERA_ERROR_SERVER_DIED", "I"), ("C", "CAMERA_ERROR_UNKNOWN", "I"), ("F", "setDisplayOrientation", "(I)"), ("F", "native_setup", "(Ljava/lang/Object;)"), ("F", "open", "()"), ], }, "SET_WALLPAPER" : { "Landroid/app/Activity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/ExpandableListActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/accessibilityservice/AccessibilityService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/accounts/GrantCredentialsPermissionActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/backup/BackupAgent;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/service/wallpaper/WallpaperService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/backup/BackupAgentHelper;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/accounts/AccountAuthenticatorActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/IWallpaperManager$Stub$Proxy;" : [ ("F", "setWallpaper", "(Ljava/lang/String;)"), ], "Landroid/app/ActivityGroup;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/content/ContextWrapper;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/WallpaperManager;" : [ ("F", "setBitmap", "(Landroid/graphics/Bitmap;)"), ("F", "clear", "()"), ("F", "setBitmap", "(Landroid/graphics/Bitmap;)"), ("F", "setResource", "(I)"), ("F", "setStream", "(Ljava/io/InputStream;)"), ], "Landroid/app/ContextImpl;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/AliasActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/content/Context;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/service/urlrenderer/UrlRendererService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/FullBackupAgent;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/TabActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/view/ContextThemeWrapper;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/speech/RecognitionService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/IntentService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/inputmethodservice/AbstractInputMethodService;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/Application;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/ListActivity;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/app/Service;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], "Landroid/content/MutableContextWrapper;" : [ ("F", "clearWallpaper", "()"), ("F", "setWallpaper", "(Landroid/graphics/Bitmap;)"), ("F", "setWallpaper", "(Ljava/io/InputStream;)"), ], }, "WAKE_LOCK" : { "Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [ ("F", "acquireWifiLock", "(Landroid/os/IBinder; I Ljava/lang/String;)"), ("F", "releaseWifiLock", "(Landroid/os/IBinder;)"), ], "Landroid/bluetooth/HeadsetBase;" : [ ("F", "acquireWakeLock", "()"), ("F", "finalize", "()"), ("F", "handleInput", "(Ljava/lang/String;)"), ("F", "releaseWakeLock", "()"), ], "Landroid/os/PowerManager$WakeLock;" : [ ("F", "acquire", "()"), ("F", "acquire", "(J)"), ("F", "release", "()"), ("F", "release", "(I)"), ], "Landroid/media/MediaPlayer;" : [ ("F", "setWakeMode", "(Landroid/content/Context; I)"), ("F", "start", "()"), ("F", "stayAwake", "(B)"), ("F", "stop", "()"), ], "Landroid/bluetooth/ScoSocket;" : [ ("F", "acquireWakeLock", "()"), ("F", "close", "()"), ("F", "finalize", "()"), ("F", "releaseWakeLock", "()"), ("F", "releaseWakeLockNow", "()"), ], "Landroid/media/AsyncPlayer;" : [ ("F", "acquireWakeLock", "()"), ("F", "enqueueLocked", "(Landroid/media/AsyncPlayer$Command;)"), ("F", "play", "(Landroid/content/Context; Landroid/net/Uri; B I)"), ("F", "releaseWakeLock", "()"), ("F", "stop", "()"), ], "Landroid/net/wifi/WifiManager$WifiLock;" : [ ("F", "acquire", "()"), ("F", "finalize", "()"), ("F", "release", "()"), ], "Landroid/os/IPowerManager$Stub$Proxy;" : [ ("F", "acquireWakeLock", "(I Landroid/os/IBinder; Ljava/lang/String;)"), ("F", "releaseWakeLock", "(Landroid/os/IBinder; I)"), ], "Landroid/net/sip/SipAudioCall;" : [ ("F", "startAudio", "()"), ], "Landroid/os/PowerManager;" : [ ("C", "ACQUIRE_CAUSES_WAKEUP", "I"), ("C", "FULL_WAKE_LOCK", "I"), ("C", "ON_AFTER_RELEASE", "I"), ("C", "PARTIAL_WAKE_LOCK", "I"), ("C", "SCREEN_BRIGHT_WAKE_LOCK", "I"), ("C", "SCREEN_DIM_WAKE_LOCK", "I"), ("F", "newWakeLock", "(I Ljava/lang/String;)"), ], }, "MANAGE_ACCOUNTS" : { "Landroid/accounts/AccountManager;" : [ ("F", "addAccount", "(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "clearPassword", "(Landroid/accounts/Account;)"), ("F", "confirmCredentials", "(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "editProperties", "(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "getAuthTokenByFeatures", "(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "removeAccount", "(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)"), ("F", "updateCredentials", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "addAccount", "(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "clearPassword", "(Landroid/accounts/Account;)"), ("F", "confirmCredentials", "(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "editProperties", "(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "removeAccount", "(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "updateCredentials", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ], "Landroid/accounts/AccountManagerService;" : [ ("F", "addAcount", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)"), ("F", "checkManageAccountsOrUseCredentialsPermissions", "()"), ("F", "checkManageAccountsPermission", "()"), ("F", "clearPassword", "(Landroid/accounts/Account;)"), ("F", "confirmCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)"), ("F", "editProperties", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)"), ("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "removeAccount", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)"), ("F", "updateCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)"), ], "Landroid/accounts/IAccountManager$Stub$Proxy;" : [ ("F", "addAcount", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)"), ("F", "clearPassword", "(Landroid/accounts/Account;)"), ("F", "confirmCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)"), ("F", "editProperties", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)"), ("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "removeAccount", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)"), ("F", "updateCredentials", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)"), ], }, "WRITE_CALENDAR" : { "Landroid/provider/Calendar$CalendarAlerts;" : [ ("F", "insert", "(Landroid/content/ContentResolver; J J J J I)"), ], "Landroid/provider/Calendar$Calendars;" : [ ("F", "delete", "(Landroid/content/ContentResolver; Ljava/lang/String; [L[Ljava/lang/Strin;)"), ("F", "deleteCalendarsForAccount", "(Landroid/content/ContentResolver; Landroid/accounts/Account;)"), ], }, "BIND_APPWIDGET" : { "Landroid/appwidget/AppWidgetManager;" : [ ("F", "bindAppWidgetId", "(I Landroid/content/ComponentName;)"), ], "Lcom/android/internal/appwidget/IAppWidgetService$Stub$Proxy;" : [ ("F", "bindAppWidgetId", "(I LComponentName;)"), ], }, "ASEC_MOUNT_UNMOUNT" : { "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "mountSecureContainer", "(Ljava/lang/String; Ljava/lang/String; I)"), ("F", "unmountSecureContainer", "(Ljava/lang/String; B)"), ], }, "SET_PREFERRED_APPLICATIONS" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "addPreferredActivity", "(LIntentFilter; I [LComponentName; LComponentName;)"), ("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"), ("F", "replacePreferredActivity", "(LIntentFilter; I [LComponentName; LComponentName;)"), ("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"), ("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"), ("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"), ("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"), ("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "addPreferredActivity", "(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)"), ("F", "clearPackagePreferredActivities", "(Ljava/lang/String;)"), ("F", "replacePreferredActivity", "(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)"), ], }, "NFC" : { "Landroid/inputmethodservice/InputMethodService;" : [ ("C", "SoftInputView", "I"), ("C", "CandidatesView", "I"), ("C", "FullscreenMode", "I"), ("C", "GeneratingText", "I"), ], "Landroid/nfc/tech/NfcA;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "get", "(Landroid/nfc/Tag;)"), ("F", "transceive", "([B)"), ], "Landroid/nfc/tech/NfcB;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "get", "(Landroid/nfc/Tag;)"), ("F", "transceive", "([B)"), ], "Landroid/nfc/NfcAdapter;" : [ ("C", "ACTION_TECH_DISCOVERED", "Ljava/lang/String;"), ("F", "disableForegroundDispatch", "(Landroid/app/Activity;)"), ("F", "disableForegroundNdefPush", "(Landroid/app/Activity;)"), ("F", "enableForegroundDispatch", "(Landroid/app/Activity; Landroid/app/PendingIntent; [Landroid/content/IntentFilter; [[Ljava/lang/String[];)"), ("F", "enableForegroundNdefPush", "(Landroid/app/Activity; Landroid/nfc/NdefMessage;)"), ("F", "getDefaultAdapter", "()"), ("F", "getDefaultAdapter", "(Landroid/content/Context;)"), ("F", "isEnabled", "()"), ], "Landroid/nfc/tech/NfcF;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "get", "(Landroid/nfc/Tag;)"), ("F", "transceive", "([B)"), ], "Landroid/nfc/tech/NdefFormatable;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "format", "(Landroid/nfc/NdefMessage;)"), ("F", "formatReadOnly", "(Landroid/nfc/NdefMessage;)"), ], "Landroid/app/Activity;" : [ ("C", "Fragments", "I"), ("C", "ActivityLifecycle", "I"), ("C", "ConfigurationChanges", "I"), ("C", "StartingActivities", "I"), ("C", "SavingPersistentState", "I"), ("C", "Permissions", "I"), ("C", "ProcessLifecycle", "I"), ], "Landroid/nfc/tech/MifareClassic;" : [ ("C", "KEY_NFC_FORUM", "[B"), ("F", "authenticateSectorWithKeyA", "(I [B)"), ("F", "authenticateSectorWithKeyB", "(I [B)"), ("F", "close", "()"), ("F", "connect", "()"), ("F", "decrement", "(I I)"), ("F", "increment", "(I I)"), ("F", "readBlock", "(I)"), ("F", "restore", "(I)"), ("F", "transceive", "([B)"), ("F", "transfer", "(I)"), ("F", "writeBlock", "(I [B)"), ], "Landroid/nfc/Tag;" : [ ("F", "getTechList", "()"), ], "Landroid/app/Service;" : [ ("C", "WhatIsAService", "I"), ("C", "ServiceLifecycle", "I"), ("C", "Permissions", "I"), ("C", "ProcessLifecycle", "I"), ("C", "LocalServiceSample", "I"), ("C", "RemoteMessengerServiceSample", "I"), ], "Landroid/nfc/NfcManager;" : [ ("F", "getDefaultAdapter", "()"), ], "Landroid/nfc/tech/MifareUltralight;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "readPages", "(I)"), ("F", "transceive", "([B)"), ("F", "writePage", "(I [B)"), ], "Landroid/nfc/tech/NfcV;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "get", "(Landroid/nfc/Tag;)"), ("F", "transceive", "([B)"), ], "Landroid/nfc/tech/TagTechnology;" : [ ("F", "close", "()"), ("F", "connect", "()"), ], "Landroid/preference/PreferenceActivity;" : [ ("C", "SampleCode", "Ljava/lang/String;"), ], "Landroid/content/pm/PackageManager;" : [ ("C", "FEATURE_NFC", "Ljava/lang/String;"), ], "Landroid/content/Context;" : [ ("C", "NFC_SERVICE", "Ljava/lang/String;"), ], "Landroid/nfc/tech/Ndef;" : [ ("C", "NFC_FORUM_TYPE_1", "Ljava/lang/String;"), ("C", "NFC_FORUM_TYPE_2", "Ljava/lang/String;"), ("C", "NFC_FORUM_TYPE_3", "Ljava/lang/String;"), ("C", "NFC_FORUM_TYPE_4", "Ljava/lang/String;"), ("F", "close", "()"), ("F", "connect", "()"), ("F", "getType", "()"), ("F", "isWritable", "()"), ("F", "makeReadOnly", "()"), ("F", "writeNdefMessage", "(Landroid/nfc/NdefMessage;)"), ], "Landroid/nfc/tech/IsoDep;" : [ ("F", "close", "()"), ("F", "connect", "()"), ("F", "setTimeout", "(I)"), ("F", "transceive", "([B)"), ], }, "CALL_PHONE" : { "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [ ("F", "call", "(Ljava/lang/String;)"), ("F", "endCall", "()"), ], }, "INTERNET" : { "Lcom/android/http/multipart/FilePart;" : [ ("F", "sendData", "(Ljava/io/OutputStream;)"), ("F", "sendDispositionHeader", "(Ljava/io/OutputStream;)"), ], "Ljava/net/HttpURLConnection;" : [ ("F", "<init>", "(Ljava/net/URL;)"), ("F", "connect", "()"), ], "Landroid/webkit/WebSettings;" : [ ("F", "setBlockNetworkLoads", "(B)"), ("F", "verifyNetworkAccess", "()"), ], "Lorg/apache/http/impl/client/DefaultHttpClient;" : [ ("F", "<init>", "()"), ("F", "<init>", "(Lorg/apache/http/params/HttpParams;)"), ("F", "<init>", "(Lorg/apache/http/conn/ClientConnectionManager; Lorg/apache/http/params/HttpParams;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"), ], "Lorg/apache/http/impl/client/HttpClient;" : [ ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"), ("F", "execute", "(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)"), ("F", "execute", "(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)"), ], "Lcom/android/http/multipart/Part;" : [ ("F", "send", "(Ljava/io/OutputStream;)"), ("F", "sendParts", "(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part;)"), ("F", "sendParts", "(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part; [B)"), ("F", "sendStart", "(Ljava/io/OutputStream;)"), ("F", "sendTransferEncodingHeader", "(Ljava/io/OutputStream;)"), ], "Landroid/drm/DrmErrorEvent;" : [ ("C", "TYPE_NO_INTERNET_CONNECTION", "I"), ], "Landroid/webkit/WebViewCore;" : [ ("F", "<init>", "(Landroid/content/Context; Landroid/webkit/WebView; Landroid/webkit/CallbackProxy; Ljava/util/Map;)"), ], "Ljava/net/URLConnection;" : [ ("F", "connect", "()"), ("F", "getInputStream", "()"), ], "Landroid/app/Activity;" : [ ("F", "setContentView", "(I)"), ], "Ljava/net/MulticastSocket;" : [ ("F", "<init>", "()"), ("F", "<init>", "(I)"), ("F", "<init>", "(Ljava/net/SocketAddress;)"), ], "Lcom/android/http/multipart/StringPart;" : [ ("F", "sendData", "(Ljava/io/OuputStream;)"), ], "Ljava/net/URL;" : [ ("F", "getContent", "([Ljava/lang/Class;)"), ("F", "getContent", "()"), ("F", "openConnection", "(Ljava/net/Proxy;)"), ("F", "openConnection", "()"), ("F", "openStream", "()"), ], "Ljava/net/DatagramSocket;" : [ ("F", "<init>", "()"), ("F", "<init>", "(I)"), ("F", "<init>", "(I Ljava/net/InetAddress;)"), ("F", "<init>", "(Ljava/net/SocketAddress;)"), ], "Ljava/net/ServerSocket;" : [ ("F", "<init>", "()"), ("F", "<init>", "(I)"), ("F", "<init>", "(I I)"), ("F", "<init>", "(I I Ljava/net/InetAddress;)"), ("F", "bind", "(Ljava/net/SocketAddress;)"), ("F", "bind", "(Ljava/net/SocketAddress; I)"), ], "Ljava/net/Socket;" : [ ("F", "<init>", "()"), ("F", "<init>", "(Ljava/lang/String; I)"), ("F", "<init>", "(Ljava/lang/String; I Ljava/net/InetAddress; I)"), ("F", "<init>", "(Ljava/lang/String; I B)"), ("F", "<init>", "(Ljava/net/InetAddress; I)"), ("F", "<init>", "(Ljava/net/InetAddress; I Ljava/net/InetAddress; I)"), ("F", "<init>", "(Ljava/net/InetAddress; I B)"), ], "Landroid/webkit/WebView;" : [ ("F", "<init>", "(Landroid/content/Context; Landroid/util/AttributeSet; I)"), ("F", "<init>", "(Landroid/content/Context; Landroid/util/AttributeSet;)"), ("F", "<init>", "(Landroid/content/Context;)"), ], "Ljava/net/NetworkInterface;" : [ ("F", "<init>", "()"), ("F", "<init>", "(Ljava/lang/String; I Ljava/net/InetAddress;)"), ], }, "ACCESS_FINE_LOCATION" : { "Landroid/webkit/WebChromeClient;" : [ ("F", "onGeolocationPermissionsShowPrompt", "(Ljava/lang/String; Landroid/webkit/GeolocationPermissions/Callback;)"), ], "Landroid/location/LocationManager;" : [ ("C", "GPS_PROVIDER", "Ljava/lang/String;"), ("C", "NETWORK_PROVIDER", "Ljava/lang/String;"), ("C", "PASSIVE_PROVIDER", "Ljava/lang/String;"), ("F", "addGpsStatusListener", "(Landroid/location/GpsStatus/Listener;)"), ("F", "addNmeaListener", "(Landroid/location/GpsStatus/NmeaListener;)"), ("F", "_requestLocationUpdates", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"), ("F", "_requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)"), ("F", "addGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)"), ("F", "addNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)"), ("F", "addProximityAlert", "(D D F J Landroid/app/PendingIntent;)"), ("F", "best", "(Ljava/util/List;)"), ("F", "getBestProvider", "(Landroid/location/Criteria; B)"), ("F", "getLastKnownLocation", "(Ljava/lang/String;)"), ("F", "getProvider", "(Ljava/lang/String;)"), ("F", "getProviders", "(Landroid/location/Criteria; B)"), ("F", "getProviders", "(B)"), ("F", "isProviderEnabled", "(Ljava/lang/String;)"), ("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"), ("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)"), ("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/LocationListener;)"), ("F", "sendExtraCommand", "(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/webkit/GeolocationService;" : [ ("F", "registerForLocationUpdates", "()"), ("F", "setEnableGps", "(B)"), ("F", "start", "()"), ], "Landroid/telephony/TelephonyManager;" : [ ("F", "getCellLocation", "()"), ("F", "getCellLocation", "()"), ("F", "getNeighboringCellInfo", "()"), ], "Landroid/location/ILocationManager$Stub$Proxy;" : [ ("F", "addGpsStatusListener", "(Landroid/location/IGpsStatusListener;)"), ("F", "addProximityAlert", "(D D F J Landroid/app/PendingIntent;)"), ("F", "getLastKnownLocation", "(Ljava/lang/String;)"), ("F", "getProviderInfo", "(Ljava/lang/String;)"), ("F", "getProviders", "(B)"), ("F", "isProviderEnabled", "(Ljava/lang/String;)"), ("F", "requestLocationUpdates", "(Ljava/lang/String; J F Landroid/location/ILocationListener;)"), ("F", "requestLocationUpdatesPI", "(Ljava/lang/String; J F Landroid/app/PendingIntent;)"), ("F", "sendExtraCommand", "(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)"), ], "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [ ("F", "getCellLocation", "()"), ("F", "getNeighboringCellInfo", "()"), ], "Landroid/webkit/GeolocationPermissions$Callback;" : [ ("F", "invok", "()"), ], }, "READ_SMS" : { "Landroid/provider/Telephony$Sms$Inbox;" : [ ("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B)"), ], "Landroid/provider/Telephony$Threads;" : [ ("F", "getOrCreateThreadId", "(Landroid/content/Context; Ljava/lang/String;)"), ("F", "getOrCreateThreadId", "(Landroid/content/Context; Ljava/util/Set;)"), ], "Landroid/provider/Telephony$Mms;" : [ ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"), ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"), ], "Landroid/provider/Telephony$Sms$Draft;" : [ ("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)"), ], "Landroid/provider/Telephony$Sms$Sent;" : [ ("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)"), ], "Landroid/provider/Telephony$Sms;" : [ ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)"), ("F", "query", "(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)"), ], }, "ACCESS_SURFACE_FLINGER" : { "Landroid/view/SurfaceSession;" : [ ("F", "<init>", "()"), ], "Landroid/view/Surface;" : [ ("F", "closeTransaction", "()"), ("F", "freezeDisplay", "(I)"), ("F", "setOrientation", "(I I I)"), ("F", "setOrientation", "(I I)"), ("F", "unfreezeDisplay", "(I)"), ], }, "REORDER_TASKS" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "moveTaskBackwards", "(I)"), ("F", "moveTaskToBack", "(I)"), ("F", "moveTaskToFront", "(I)"), ], "Landroid/app/ActivityManager;" : [ ("F", "moveTaskToFront", "(I I)"), ], }, "MODIFY_AUDIO_SETTINGS" : { "Landroid/net/sip/SipAudioCall;" : [ ("F", "setSpeakerMode", "(B)"), ], "Landroid/server/BluetoothA2dpService;" : [ ("F", "checkSinkSuspendState", "(I)"), ("F", "handleSinkStateChange", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "onBluetoothDisable", "()"), ("F", "onBluetoothEnable", "()"), ], "Landroid/media/IAudioService$Stub$Proxy;" : [ ("F", "setBluetoothScoOn", "(B)"), ("F", "setMode", "(I Landroid/os/IBinder;)"), ("F", "setSpeakerphoneOn", "(B)"), ("F", "startBluetoothSco", "(Landroid/os/IBinder;)"), ("F", "stopBluetoothSco", "(Landroid/os/IBinder;)"), ], "Landroid/media/AudioService;" : [ ("F", "setBluetoothScoOn", "(B)"), ("F", "setMode", "(I Landroid/os/IBinder;)"), ("F", "setSpeakerphoneOn", "(B)"), ("F", "startBluetoothSco", "(Landroid/os/IBinder;)"), ("F", "stopBluetoothSco", "(Landroid/os/IBinder;)"), ], "Landroid/media/AudioManager;" : [ ("F", "startBluetoothSco", "()"), ("F", "stopBluetoothSco", "()"), ("F", "isBluetoothA2dpOn", "()"), ("F", "isWiredHeadsetOn", "()"), ("F", "setBluetoothScoOn", "(B)"), ("F", "setMicrophoneMute", "(B)"), ("F", "setMode", "(I)"), ("F", "setParameter", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "setParameters", "(Ljava/lang/String;)"), ("F", "setSpeakerphoneOn", "(B)"), ("F", "startBluetoothSco", "()"), ("F", "stopBluetoothSco", "()"), ], }, "READ_PHONE_STATE" : { "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;" : [ ("F", "getDeviceId", "()"), ("F", "getDeviceSvn", "()"), ("F", "getIccSerialNumber", "()"), ("F", "getLine1AlphaTag", "()"), ("F", "getLine1Number", "()"), ("F", "getSubscriberId", "()"), ("F", "getVoiceMailAlphaTag", "()"), ("F", "getVoiceMailNumber", "()"), ], "Landroid/telephony/PhoneStateListener;" : [ ("C", "LISTEN_CALL_FORWARDING_INDICATOR", "I"), ("C", "LISTEN_CALL_STATE", "I"), ("C", "LISTEN_DATA_ACTIVITY", "I"), ("C", "LISTEN_MESSAGE_WAITING_INDICATOR", "I"), ("C", "LISTEN_SIGNAL_STRENGTH", "I"), ], "Landroid/accounts/AccountManagerService$SimWatcher;" : [ ("F", "onReceive", "(Landroid/content/Context; Landroid/content/Intent;)"), ], "Lcom/android/internal/telephony/CallerInfo;" : [ ("F", "markAsVoiceMail", "()"), ], "Landroid/os/Build/VERSION_CODES;" : [ ("C", "DONUT", "I"), ], "Landroid/telephony/TelephonyManager;" : [ ("C", "ACTION_PHONE_STATE_CHANGED", "Ljava/lang/String;"), ("F", "getDeviceId", "()"), ("F", "getDeviceSoftwareVersion", "()"), ("F", "getLine1Number", "()"), ("F", "getSimSerialNumber", "()"), ("F", "getSubscriberId", "()"), ("F", "getVoiceMailAlphaTag", "()"), ("F", "getVoiceMailNumber", "()"), ("F", "getDeviceId", "()"), ("F", "getDeviceSoftwareVersion", "()"), ("F", "getLine1AlphaTag", "()"), ("F", "getLine1Number", "()"), ("F", "getSimSerialNumber", "()"), ("F", "getSubscriberId", "()"), ("F", "getVoiceMailAlphaTag", "()"), ("F", "getVoiceMailNumber", "()"), ("F", "listen", "(Landroid/telephony/PhoneStateListener; I)"), ], "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;" : [ ("F", "listen", "(Ljava/lang/String; Lcom/android/internal/telephony/IPhoneStateListener; I B)"), ], "Landroid/telephony/PhoneNumberUtils;" : [ ("F", "isVoiceMailNumber", "(Ljava/lang/String;)"), ], "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [ ("F", "isSimPinEnabled", "()"), ], }, "WRITE_SETTINGS" : { "Landroid/media/RingtoneManager;" : [ ("F", "setActualDefaultRingtoneUri", "(Landroid/content/Context; I Landroid/net/Uri;)"), ], "Landroid/os/IPowerManager$Stub$Proxy;" : [ ("F", "setStayOnSetting", "(I)"), ], "Landroid/server/BluetoothService;" : [ ("F", "persistBluetoothOnSetting", "(B)"), ], "Landroid/provider/Settings$Secure;" : [ ("F", "putFloat", "(Landroid/content/ContentResolver; Ljava/lang/String; F)"), ("F", "putInt", "(Landroid/content/ContentResolver; Ljava/lang/String; I)"), ("F", "putLong", "(Landroid/content/ContentResolver; Ljava/lang/String; J)"), ("F", "putString", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setLocationProviderEnabled", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"), ], "Landroid/provider/Settings$Bookmarks;" : [ ("F", "add", "(Landroid/content/ContentResolver; Landroid/content/Intent; Ljava/lang/String; Ljava/lang/String; C I)"), ("F", "getIntentForShortcut", "(Landroid/content/ContentResolver; C)"), ], "Landroid/os/IMountService$Stub$Proxy;" : [ ("F", "setAutoStartUm", "()"), ("F", "setPlayNotificationSound", "()"), ], "Landroid/provider/Settings$System;" : [ ("F", "putConfiguration", "(Landroid/content/ContentResolver; Landroid/content/res/Configuration;)"), ("F", "putFloat", "(Landroid/content/ContentResolver; Ljava/lang/String; F)"), ("F", "putInt", "(Landroid/content/ContentResolver; Ljava/lang/String; I)"), ("F", "putLong", "(Landroid/content/ContentResolver; Ljava/lang/String; J)"), ("F", "putString", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setShowGTalkServiceStatus", "(Landroid/content/ContentResolver; B)"), ], }, "BIND_WALLPAPER" : { "Landroid/service/wallpaper/WallpaperService;" : [ ("C", "SERVICE_INTERFACE", "Ljava/lang/String;"), ], "Lcom/android/server/WallpaperManagerService;" : [ ("F", "bindWallpaperComponentLocked", "(Landroid/content/ComponentName;)"), ], }, "DUMP" : { "Landroid/content/ContentService;" : [ ("F", "dump", "(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Strin;)"), ], "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "isViewServerRunning", "()"), ("F", "startViewServer", "(I)"), ("F", "stopViewServer", "()"), ], "Landroid/os/Debug;" : [ ("F", "dumpService", "(Ljava/lang/String; Ljava/io/FileDescriptor; [Ljava/lang/String;)"), ], "Landroid/os/IBinder;" : [ ("C", "DUMP_TRANSACTION", "I"), ], "Lcom/android/server/WallpaperManagerService;" : [ ("F", "dump", "(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Stri;)"), ], }, "USE_CREDENTIALS" : { "Landroid/accounts/AccountManager;" : [ ("F", "blockingGetAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)"), ("F", "invalidateAuthToken", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "blockingGetAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "getAuthToken", "(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ], "Landroid/accounts/AccountManagerService;" : [ ("F", "getAuthToken", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)"), ], "Landroid/accounts/IAccountManager$Stub$Proxy;" : [ ("F", "getAuthToken", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)"), ], }, "UPDATE_DEVICE_STATS" : { "Lcom/android/internal/app/IUsageStats$Stub$Proxy;" : [ ("F", "notePauseComponent", "(LComponentName;)"), ("F", "noteResumeComponent", "(LComponentName;)"), ], "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;" : [ ("F", "noteFullWifiLockAcquired", "(I)"), ("F", "noteFullWifiLockReleased", "(I)"), ("F", "noteInputEvent", "()"), ("F", "notePhoneDataConnectionState", "(I B)"), ("F", "notePhoneOff", "()"), ("F", "notePhoneOn", "()"), ("F", "notePhoneSignalStrength", "(LSignalStrength;)"), ("F", "notePhoneState", "(I)"), ("F", "noteScanWifiLockAcquired", "(I)"), ("F", "noteScanWifiLockReleased", "(I)"), ("F", "noteScreenBrightness", "(I)"), ("F", "noteScreenOff", "()"), ("F", "noteScreenOn", "()"), ("F", "noteStartGps", "(I)"), ("F", "noteStartSensor", "(I I)"), ("F", "noteStartWakelock", "(I Ljava/lang/String; I)"), ("F", "noteStopGps", "(I)"), ("F", "noteStopSensor", "(I I)"), ("F", "noteStopWakelock", "(I Ljava/lang/String; I)"), ("F", "noteUserActivity", "(I I)"), ("F", "noteWifiMulticastDisabled", "(I)"), ("F", "noteWifiMulticastEnabled", "(I)"), ("F", "noteWifiOff", "(I)"), ("F", "noteWifiOn", "(I)"), ("F", "noteWifiRunning", "()"), ("F", "noteWifiStopped", "()"), ("F", "recordCurrentLevel", "(I)"), ("F", "setOnBattery", "(B I)"), ], }, "SEND_SMS" : { "Landroid/telephony/gsm/SmsManager;" : [ ("F", "getDefault", "()"), ("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendMultipartTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)"), ("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ], "Landroid/telephony/SmsManager;" : [ ("F", "getDefault", "()"), ("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendDataMessage", "(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendMultipartTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)"), ("F", "sendTextMessage", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ], "Lcom/android/internal/telephony/ISms$Stub$Proxy;" : [ ("F", "sendData", "(Ljava/lang/String; Ljava/lang/String; I [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ("F", "sendMultipartText", "(Ljava/lang/String; Ljava/lang/String; Ljava/util/List; Ljava/util/List; Ljava/util/List;)"), ("F", "sendText", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)"), ], }, "WRITE_USER_DICTIONARY" : { "Landroid/provider/UserDictionary$Words;" : [ ("F", "addWord", "(Landroid/content/Context; Ljava/lang/String; I I)"), ], }, "ACCESS_COARSE_LOCATION" : { "Landroid/telephony/TelephonyManager;" : [ ("F", "getCellLocation", "()"), ], "Landroid/telephony/PhoneStateListener;" : [ ("C", "LISTEN_CELL_LOCATION", "I"), ], "Landroid/location/LocationManager;" : [ ("C", "NETWORK_PROVIDER", "Ljava/lang/String;"), ], }, "ASEC_RENAME" : { "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "renameSecureContainer", "(Ljava/lang/String; Ljava/lang/String;)"), ], }, "SYSTEM_ALERT_WINDOW" : { "Landroid/view/IWindowSession$Stub$Proxy;" : [ ("F", "add", "(Landroid/view/IWindow; Landroid/view/WindowManager$LayoutParams; I Landroid/graphics/Rect;)"), ], }, "CHANGE_WIFI_MULTICAST_STATE" : { "Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [ ("F", "acquireMulticastLock", "(Landroid/os/IBinder; Ljava/lang/String;)"), ("F", "initializeMulticastFiltering", "()"), ("F", "releaseMulticastLock", "()"), ], "Landroid/net/wifi/WifiManager$MulticastLock;" : [ ("F", "acquire", "()"), ("F", "finalize", "()"), ("F", "release", "()"), ], "Landroid/net/wifi/WifiManager;" : [ ("F", "initializeMulticastFiltering", "()"), ], }, "RECEIVE_BOOT_COMPLETED" : { "Landroid/content/Intent;" : [ ("C", "ACTION_BOOT_COMPLETED", "Ljava/lang/String;"), ], }, "SET_ALARM" : { "Landroid/provider/AlarmClock;" : [ ("C", "ACTION_SET_ALARM", "Ljava/lang/String;"), ("C", "EXTRA_HOUR", "Ljava/lang/String;"), ("C", "EXTRA_MESSAGE", "Ljava/lang/String;"), ("C", "EXTRA_MINUTES", "Ljava/lang/String;"), ("C", "EXTRA_SKIP_UI", "Ljava/lang/String;"), ], }, "WRITE_CONTACTS" : { "Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;" : [ ("F", "updateAdnRecordsInEfByIndex", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ("F", "updateAdnRecordsInEfBySearch", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/provider/Contacts$People;" : [ ("F", "addToGroup", "(Landroid/content/ContentResolver; J J)"), ], "Landroid/provider/ContactsContract$Contacts;" : [ ("F", "markAsContacted", "(Landroid/content/ContentResolver; J)"), ], "Landroid/provider/Contacts$Settings;" : [ ("F", "setSetting", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], "Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;" : [ ("F", "updateAdnRecordsInEfByIndex", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ("F", "updateAdnRecordsInEfBySearch", "(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/provider/CallLog$Calls;" : [ ("F", "removeExpiredEntries", "(Landroid/content/Context;)"), ], "Landroid/pim/vcard/VCardEntryCommitter;" : [ ("F", "onEntryCreated", "(Landroid/pim/vcard/VCardEntry;)"), ], "Landroid/pim/vcard/VCardEntryHandler;" : [ ("F", "onEntryCreated", "(Landroid/pim/vcard/VCardEntry;)"), ], "Landroid/pim/vcard/VCardEntry;" : [ ("F", "pushIntoContentResolver", "(Landroid/content/ContentResolver;)"), ], }, "PROCESS_OUTGOING_CALLS" : { "Landroid/content/Intent;" : [ ("C", "ACTION_NEW_OUTGOING_CALL", "Ljava/lang/String;"), ], }, "EXPAND_STATUS_BAR" : { "Landroid/app/StatusBarManager;" : [ ("F", "collapse", "()"), ("F", "expand", "()"), ("F", "toggle", "()"), ], "Landroid/app/IStatusBar$Stub$Proxy;" : [ ("F", "activate", "()"), ("F", "deactivate", "()"), ("F", "toggle", "()"), ], }, "MODIFY_PHONE_STATE" : { "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;" : [ ("F", "answerRingingCall", "()"), ("F", "cancelMissedCallsNotification", "()"), ("F", "disableApnType", "(Ljava/lang/String;)"), ("F", "disableDataConnectivity", "()"), ("F", "enableApnType", "(Ljava/lang/String;)"), ("F", "enableDataConnectivity", "()"), ("F", "handlePinMmi", "(Ljava/lang/String;)"), ("F", "setRadio", "(B)"), ("F", "silenceRinger", "()"), ("F", "supplyPin", "(Ljava/lang/String;)"), ("F", "toggleRadioOnOff", "()"), ], "Landroid/net/MobileDataStateTracker;" : [ ("F", "reconnect", "()"), ("F", "setRadio", "(B)"), ("F", "teardown", "()"), ], "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;" : [ ("F", "notifyCallForwardingChanged", "(B)"), ("F", "notifyCallState", "(I Ljava/lang/String;)"), ("F", "notifyCellLocation", "(Landroid/os/Bundle;)"), ("F", "notifyDataActivity", "(I)"), ("F", "notifyDataConnection", "(I B Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Ljava/lang/String; I)"), ("F", "notifyDataConnectionFailed", "(Ljava/lang/String;)"), ("F", "notifyMessageWaitingChanged", "(B)"), ("F", "notifyServiceState", "(Landroid/telephony/ServiceState;)"), ("F", "notifySignalStrength", "(Landroid/telephony/SignalStrength;)"), ], }, "MOUNT_FORMAT_FILESYSTEMS" : { "Landroid/os/IMountService$Stub$Proxy;" : [ ("F", "formatMedi", "()"), ], "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "formatVolume", "(Ljava/lang/String;)"), ], }, "ACCESS_DOWNLOAD_MANAGER" : { "Landroid/net/Downloads$DownloadBase;" : [ ("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/net/Downloads$ByUri;" : [ ("F", "getCurrentOtaDownloads", "(Landroid/content/Context; Ljava/lang/String;)"), ("F", "getProgressCursor", "(Landroid/content/Context; J)"), ("F", "getStatus", "(Landroid/content/Context; Ljava/lang/String; J)"), ("F", "removeAllDownloadsByPackage", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String;)"), ("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/net/Downloads$ById;" : [ ("F", "deleteDownload", "(Landroid/content/Context; J)"), ("F", "getMimeTypeForId", "(Landroid/content/Context; J)"), ("F", "getStatus", "(Landroid/content/Context; J)"), ("F", "openDownload", "(Landroid/content/Context; J Ljava/lang/String;)"), ("F", "openDownloadStream", "(Landroid/content/Context; J)"), ("F", "startDownloadByUri", "(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ], }, "READ_INPUT_STATE" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "getDPadKeycodeState", "(I)"), ("F", "getDPadScancodeState", "(I)"), ("F", "getKeycodeState", "(I)"), ("F", "getKeycodeStateForDevice", "(I I)"), ("F", "getScancodeState", "(I)"), ("F", "getScancodeStateForDevice", "(I I)"), ("F", "getSwitchState", "(I)"), ("F", "getSwitchStateForDevice", "(I I)"), ("F", "getTrackballKeycodeState", "(I)"), ("F", "getTrackballScancodeState", "(I)"), ], }, "READ_SYNC_STATS" : { "Landroid/app/ContextImpl$ApplicationContentResolver;" : [ ("F", "getCurrentSync", "()"), ("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/ContentService;" : [ ("F", "getCurrentSync", "()"), ("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/ContentResolver;" : [ ("F", "getCurrentSync", "()"), ("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], "Landroid/content/IContentService$Stub$Proxy;" : [ ("F", "getCurrentSync", "()"), ("F", "getSyncStatus", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncActive", "(Landroid/accounts/Account; Ljava/lang/String;)"), ("F", "isSyncPending", "(Landroid/accounts/Account; Ljava/lang/String;)"), ], }, "SET_TIME" : { "Landroid/app/AlarmManager;" : [ ("F", "setTime", "(J)"), ("F", "setTimeZone", "(Ljava/lang/String;)"), ("F", "setTime", "(J)"), ], "Landroid/app/IAlarmManager$Stub$Proxy;" : [ ("F", "setTime", "(J)"), ], }, "CHANGE_WIMAX_STATE" : { "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;" : [ ("F", "setWimaxEnable", "()"), ], }, "MOUNT_UNMOUNT_FILESYSTEMS" : { "Landroid/os/IMountService$Stub$Proxy;" : [ ("F", "mountMedi", "()"), ("F", "unmountMedi", "()"), ], "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "getStorageUsers", "(Ljava/lang/String;)"), ("F", "mountVolume", "(Ljava/lang/String;)"), ("F", "setUsbMassStorageEnabled", "(B)"), ("F", "unmountVolume", "(Ljava/lang/String; B)"), ], "Landroid/os/storage/StorageManager;" : [ ("F", "disableUsbMassStorage", "()"), ("F", "enableUsbMassStorage", "()"), ], }, "MOVE_PACKAGE" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"), ("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "movePackage", "(Ljava/lang/String; LIPackageMoveObserver; I)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "movePackage", "(Ljava/lang/String; Landroid/content/pm/IPackageMoveObserver; I)"), ], }, "ACCESS_WIMAX_STATE" : { "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;" : [ ("F", "getConnectionInf", "()"), ("F", "getWimaxStat", "()"), ("F", "isBackoffStat", "()"), ("F", "isWimaxEnable", "()"), ], }, "ACCESS_WIFI_STATE" : { "Landroid/net/sip/SipAudioCall;" : [ ("F", "startAudio", "()"), ], "Landroid/net/wifi/IWifiManager$Stub$Proxy;" : [ ("F", "getConfiguredNetworks", "()"), ("F", "getConnectionInfo", "()"), ("F", "getDhcpInfo", "()"), ("F", "getNumAllowedChannels", "()"), ("F", "getScanResults", "()"), ("F", "getValidChannelCounts", "()"), ("F", "getWifiApEnabledState", "()"), ("F", "getWifiEnabledState", "()"), ("F", "isMulticastEnabled", "()"), ], "Landroid/net/wifi/WifiManager;" : [ ("F", "getConfiguredNetworks", "()"), ("F", "getConnectionInfo", "()"), ("F", "getDhcpInfo", "()"), ("F", "getNumAllowedChannels", "()"), ("F", "getScanResults", "()"), ("F", "getValidChannelCounts", "()"), ("F", "getWifiApState", "()"), ("F", "getWifiState", "()"), ("F", "isMulticastEnabled", "()"), ("F", "isWifiApEnabled", "()"), ("F", "isWifiEnabled", "()"), ], }, "READ_HISTORY_BOOKMARKS" : { "Landroid/webkit/WebIconDatabase;" : [ ("F", "bulkRequestIconForPageUrl", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)"), ], "Landroid/provider/Browser;" : [ ("C", "BOOKMARKS_URI", "Landroid/net/Uri;"), ("C", "SEARCHES_URI", "Landroid/net/Uri;"), ("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "canClearHistory", "(Landroid/content/ContentResolver;)"), ("F", "getAllBookmarks", "(Landroid/content/ContentResolver;)"), ("F", "getAllVisitedUrls", "(Landroid/content/ContentResolver;)"), ("F", "requestAllIcons", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase/IconListener;)"), ("F", "truncateHistory", "(Landroid/content/ContentResolver;)"), ("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"), ("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "canClearHistory", "(Landroid/content/ContentResolver;)"), ("F", "clearHistory", "(Landroid/content/ContentResolver;)"), ("F", "deleteFromHistory", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "deleteHistoryTimeFrame", "(Landroid/content/ContentResolver; J J)"), ("F", "deleteHistoryWhere", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "getAllBookmarks", "(Landroid/content/ContentResolver;)"), ("F", "getAllVisitedUrls", "(Landroid/content/ContentResolver;)"), ("F", "getVisitedHistory", "(Landroid/content/ContentResolver;)"), ("F", "getVisitedLike", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "requestAllIcons", "(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)"), ("F", "truncateHistory", "(Landroid/content/ContentResolver;)"), ("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"), ], }, "ASEC_DESTROY" : { "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "destroySecureContainer", "(Ljava/lang/String; B)"), ], }, "ACCESS_NETWORK_STATE" : { "Landroid/net/ThrottleManager;" : [ ("F", "getByteCount", "(Ljava/lang/String; I I I)"), ("F", "getCliffLevel", "(Ljava/lang/String; I)"), ("F", "getCliffThreshold", "(Ljava/lang/String; I)"), ("F", "getHelpUri", "()"), ("F", "getPeriodStartTime", "(Ljava/lang/String;)"), ("F", "getResetTime", "(Ljava/lang/String;)"), ], "Landroid/net/NetworkInfo;" : [ ("F", "isConnectedOrConnecting", "()"), ], "Landroid/os/INetworkManagementService$Stub$Proxy;" : [ ("F", "getDnsForwarders", "()"), ("F", "getInterfaceRxCounter", "(Ljava/lang/String;)"), ("F", "getInterfaceRxThrottle", "(Ljava/lang/String;)"), ("F", "getInterfaceTxCounter", "(Ljava/lang/String;)"), ("F", "getInterfaceTxThrottle", "(Ljava/lang/String;)"), ("F", "getIpForwardingEnabled", "()"), ("F", "isTetheringStarted", "()"), ("F", "isUsbRNDISStarted", "()"), ("F", "listInterfaces", "()"), ("F", "listTetheredInterfaces", "()"), ("F", "listTtys", "()"), ], "Landroid/net/IConnectivityManager$Stub$Proxy;" : [ ("F", "getActiveNetworkInfo", "()"), ("F", "getAllNetworkInfo", "()"), ("F", "getLastTetherError", "(Ljava/lang/String;)"), ("F", "getMobileDataEnabled", "()"), ("F", "getNetworkInfo", "(I)"), ("F", "getNetworkPreference", "()"), ("F", "getTetherableIfaces", "()"), ("F", "getTetherableUsbRegexs", "()"), ("F", "getTetherableWifiRegexs", "()"), ("F", "getTetheredIfaces", "()"), ("F", "getTetheringErroredIfaces", "()"), ("F", "isTetheringSupported", "()"), ("F", "startUsingNetworkFeature", "(I Ljava/lang/String; Landroid/os/IBinder;)"), ], "Landroid/net/IThrottleManager$Stub$Proxy;" : [ ("F", "getByteCount", "(Ljava/lang/String; I I I)"), ("F", "getCliffLevel", "(Ljava/lang/String; I)"), ("F", "getCliffThreshold", "(Ljava/lang/String; I)"), ("F", "getHelpUri", "()"), ("F", "getPeriodStartTime", "(Ljava/lang/String;)"), ("F", "getResetTime", "(Ljava/lang/String;)"), ("F", "getThrottle", "(Ljava/lang/String;)"), ], "Landroid/net/ConnectivityManager;" : [ ("F", "getActiveNetworkInfo", "()"), ("F", "getAllNetworkInfo", "()"), ("F", "getLastTetherError", "(Ljava/lang/String;)"), ("F", "getMobileDataEnabled", "()"), ("F", "getNetworkInfo", "(I)"), ("F", "getNetworkPreference", "()"), ("F", "getTetherableIfaces", "()"), ("F", "getTetherableUsbRegexs", "()"), ("F", "getTetherableWifiRegexs", "()"), ("F", "getTetheredIfaces", "()"), ("F", "getTetheringErroredIfaces", "()"), ("F", "isTetheringSupported", "()"), ], "Landroid/net/http/RequestQueue;" : [ ("F", "enablePlatformNotifications", "()"), ("F", "setProxyConfig", "()"), ], }, "GET_TASKS" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "getRecentTasks", "(I I)"), ("F", "getTasks", "(I I Landroid/app/IThumbnailReceiver;)"), ], "Landroid/app/ActivityManagerNative;" : [ ("F", "getRecentTasks", "(I I)"), ("F", "getRunningTasks", "(I)"), ], "Landroid/app/ActivityManager;" : [ ("F", "getRecentTasks", "(I I)"), ("F", "getRunningTasks", "(I)"), ("F", "getRecentTasks", "(I I)"), ("F", "getRunningTasks", "(I)"), ], }, "STATUS_BAR" : { "Landroid/view/View/OnSystemUiVisibilityChangeListener;" : [ ("F", "onSystemUiVisibilityChange", "(I)"), ], "Landroid/view/View;" : [ ("C", "STATUS_BAR_HIDDEN", "I"), ("C", "STATUS_BAR_VISIBLE", "I"), ], "Landroid/app/StatusBarManager;" : [ ("F", "addIcon", "(Ljava/lang/String; I I)"), ("F", "disable", "(I)"), ("F", "removeIcon", "(Landroid/os/IBinder;)"), ("F", "updateIcon", "(Landroid/os/IBinder; Ljava/lang/String; I I)"), ], "Landroid/view/WindowManager/LayoutParams;" : [ ("C", "TYPE_STATUS_BAR", "I"), ("C", "TYPE_STATUS_BAR_PANEL", "I"), ("C", "systemUiVisibility", "I"), ("C", "type", "I"), ], "Landroid/app/IStatusBar$Stub$Proxy;" : [ ("F", "addIcon", "(Ljava/lang/String; Ljava/lang/String; I I)"), ("F", "disable", "(I Landroid/os/IBinder; Ljava/lang/String;)"), ("F", "removeIcon", "(Landroid/os/IBinder;)"), ("F", "updateIcon", "(Landroid/os/IBinder; Ljava/lang/String; Ljava/lang/String; I I)"), ], }, "SHUTDOWN" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "shutdown", "(I)"), ], "Landroid/os/IMountService$Stub$Proxy;" : [ ("F", "shutdow", "()"), ], "Landroid/os/storage/IMountService$Stub$Proxy;" : [ ("F", "shutdown", "(Landroid/os/storage/IMountShutdownObserver;)"), ], "Landroid/os/INetworkManagementService$Stub$Proxy;" : [ ("F", "shutdown", "()"), ], }, "READ_LOGS" : { "Landroid/os/DropBoxManager;" : [ ("C", "ACTION_DROPBOX_ENTRY_ADDED", "Ljava/lang/String;"), ("F", "getNextEntry", "(Ljava/lang/String; J)"), ("F", "getNextEntry", "(Ljava/lang/String; J)"), ], "Lcom/android/internal/os/IDropBoxManagerService$Stub$Proxy;" : [ ("F", "getNextEntry", "(Ljava/lang/String; J)"), ], "Ljava/lang/Runtime;" : [ ("F", "exec", "(Ljava/lang/String;)"), ("F", "exec", "([Ljava/lang/String;)"), ("F", "exec", "([Ljava/lang/String; [Ljava/lang/String;)"), ("F", "exec", "([Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)"), ("F", "exec", "(Ljava/lang/String; [Ljava/lang/String;)"), ("F", "exec", "(Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)"), ], }, "BLUETOOTH" : { "Landroid/os/Process;" : [ ("C", "BLUETOOTH_GID", "I"), ], "Landroid/bluetooth/BluetoothA2dp;" : [ ("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_PLAYING_STATE_CHANGED", "Ljava/lang/String;"), ("F", "getConnectedDevices", "()"), ("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getDevicesMatchingConnectionStates", "([I)"), ("F", "isA2dpPlaying", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getConnectedSinks", "()"), ("F", "getNonDisconnectedSinks", "()"), ("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "isSinkConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/media/AudioManager;" : [ ("C", "ROUTE_BLUETOOTH", "I"), ("C", "ROUTE_BLUETOOTH_A2DP", "I"), ("C", "ROUTE_BLUETOOTH_SCO", "I"), ], "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;" : [ ("F", "getConnectedSinks", "()"), ("F", "getNonDisconnectedSinks", "()"), ("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/bluetooth/BluetoothSocket;" : [ ("F", "connect", "()"), ], "Landroid/bluetooth/BluetoothPbap;" : [ ("F", "getClient", "()"), ("F", "getState", "()"), ("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/provider/Settings/System;" : [ ("C", "AIRPLANE_MODE_RADIOS", "Ljava/lang/String;"), ("C", "BLUETOOTH_DISCOVERABILITY", "Ljava/lang/String;"), ("C", "BLUETOOTH_DISCOVERABILITY_TIMEOUT", "Ljava/lang/String;"), ("C", "BLUETOOTH_ON", "Ljava/lang/String;"), ("C", "RADIO_BLUETOOTH", "Ljava/lang/String;"), ("C", "VOLUME_BLUETOOTH_SCO", "Ljava/lang/String;"), ], "Landroid/provider/Settings;" : [ ("C", "ACTION_BLUETOOTH_SETTINGS", "Ljava/lang/String;"), ], "Landroid/bluetooth/IBluetooth$Stub$Proxy;" : [ ("F", "addRfcommServiceRecord", "(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)"), ("F", "fetchRemoteUuids", "(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)"), ("F", "getAddress", "()"), ("F", "getBluetoothState", "()"), ("F", "getBondState", "(Ljava/lang/String;)"), ("F", "getDiscoverableTimeout", "()"), ("F", "getName", "()"), ("F", "getRemoteClass", "(Ljava/lang/String;)"), ("F", "getRemoteName", "(Ljava/lang/String;)"), ("F", "getRemoteServiceChannel", "(Ljava/lang/String; Landroid/os/ParcelUuid;)"), ("F", "getRemoteUuids", "(Ljava/lang/String;)"), ("F", "getScanMode", "()"), ("F", "getTrustState", "(Ljava/lang/String;)"), ("F", "isDiscovering", "()"), ("F", "isEnabled", "()"), ("F", "listBonds", "()"), ("F", "removeServiceRecord", "(I)"), ], "Landroid/bluetooth/BluetoothAdapter;" : [ ("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_DISCOVERY_FINISHED", "Ljava/lang/String;"), ("C", "ACTION_DISCOVERY_STARTED", "Ljava/lang/String;"), ("C", "ACTION_LOCAL_NAME_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_REQUEST_DISCOVERABLE", "Ljava/lang/String;"), ("C", "ACTION_REQUEST_ENABLE", "Ljava/lang/String;"), ("C", "ACTION_SCAN_MODE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_STATE_CHANGED", "Ljava/lang/String;"), ("F", "cancelDiscovery", "()"), ("F", "disable", "()"), ("F", "enable", "()"), ("F", "getAddress", "()"), ("F", "getBondedDevices", "()"), ("F", "getName", "()"), ("F", "getScanMode", "()"), ("F", "getState", "()"), ("F", "isDiscovering", "()"), ("F", "isEnabled", "()"), ("F", "listenUsingInsecureRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"), ("F", "listenUsingRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"), ("F", "setName", "(Ljava/lang/String;)"), ("F", "startDiscovery", "()"), ("F", "getAddress", "()"), ("F", "getBondedDevices", "()"), ("F", "getDiscoverableTimeout", "()"), ("F", "getName", "()"), ("F", "getScanMode", "()"), ("F", "getState", "()"), ("F", "isDiscovering", "()"), ("F", "isEnabled", "()"), ("F", "listenUsingRfcommWithServiceRecord", "(Ljava/lang/String; Ljava/util/UUID;)"), ], "Landroid/bluetooth/BluetoothProfile;" : [ ("F", "getConnectedDevices", "()"), ("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getDevicesMatchingConnectionStates", "([I)"), ], "Landroid/bluetooth/BluetoothHeadset;" : [ ("C", "ACTION_AUDIO_STATE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_CONNECTION_STATE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_VENDOR_SPECIFIC_HEADSET_EVENT", "Ljava/lang/String;"), ("F", "getConnectedDevices", "()"), ("F", "getConnectionState", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getDevicesMatchingConnectionStates", "([I)"), ("F", "isAudioConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "startVoiceRecognition", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "stopVoiceRecognition", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getBatteryUsageHint", "()"), ("F", "getCurrentHeadset", "()"), ("F", "getPriority", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getState", "()"), ("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "startVoiceRecognition", "()"), ("F", "stopVoiceRecognition", "()"), ], "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;" : [ ("F", "getBatteryUsageHint", "()"), ("F", "getCurrentHeadset", "()"), ("F", "getPriority", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getState", "()"), ("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "startVoiceRecognition", "()"), ("F", "stopVoiceRecognition", "()"), ], "Landroid/bluetooth/BluetoothDevice;" : [ ("C", "ACTION_ACL_CONNECTED", "Ljava/lang/String;"), ("C", "ACTION_ACL_DISCONNECTED", "Ljava/lang/String;"), ("C", "ACTION_ACL_DISCONNECT_REQUESTED", "Ljava/lang/String;"), ("C", "ACTION_BOND_STATE_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_CLASS_CHANGED", "Ljava/lang/String;"), ("C", "ACTION_FOUND", "Ljava/lang/String;"), ("C", "ACTION_NAME_CHANGED", "Ljava/lang/String;"), ("F", "createInsecureRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"), ("F", "createRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"), ("F", "getBluetoothClass", "()"), ("F", "getBondState", "()"), ("F", "getName", "()"), ("F", "createRfcommSocketToServiceRecord", "(Ljava/util/UUID;)"), ("F", "fetchUuidsWithSdp", "()"), ("F", "getBondState", "()"), ("F", "getName", "()"), ("F", "getServiceChannel", "(Landroid/os/ParcelUuid;)"), ("F", "getUuids", "()"), ], "Landroid/server/BluetoothA2dpService;" : [ ("F", "<init>", "(Landroid/content/Context; Landroid/server/BluetoothService;)"), ("F", "addAudioSink", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getConnectedSinks", "()"), ("F", "getNonDisconnectedSinks", "()"), ("F", "getSinkPriority", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "getSinkState", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "isSinkDevice", "(Landroid/bluetooth/BluetoothDevice;)"), ("F", "lookupSinksMatchingStates", "([I)"), ("F", "onConnectSinkResult", "(Ljava/lang/String; B)"), ("F", "onSinkPropertyChanged", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"), ], "Landroid/provider/Settings/Secure;" : [ ("C", "BLUETOOTH_ON", "Ljava/lang/String;"), ], "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;" : [ ("F", "getClient", "()"), ("F", "getState", "()"), ("F", "isConnected", "(Landroid/bluetooth/BluetoothDevice;)"), ], "Landroid/server/BluetoothService;" : [ ("F", "addRemoteDeviceProperties", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"), ("F", "addRfcommServiceRecord", "(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)"), ("F", "fetchRemoteUuids", "(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)"), ("F", "getAddress", "()"), ("F", "getAddressFromObjectPath", "(Ljava/lang/String;)"), ("F", "getAllProperties", "()"), ("F", "getBluetoothState", "()"), ("F", "getBondState", "(Ljava/lang/String;)"), ("F", "getDiscoverableTimeout", "()"), ("F", "getName", "()"), ("F", "getObjectPathFromAddress", "(Ljava/lang/String;)"), ("F", "getProperty", "(Ljava/lang/String;)"), ("F", "getPropertyInternal", "(Ljava/lang/String;)"), ("F", "getRemoteClass", "(Ljava/lang/String;)"), ("F", "getRemoteName", "(Ljava/lang/String;)"), ("F", "getRemoteServiceChannel", "(Ljava/lang/String; Landroid/os/ParcelUuid;)"), ("F", "getRemoteUuids", "(Ljava/lang/String;)"), ("F", "getScanMode", "()"), ("F", "getTrustState", "(Ljava/lang/String;)"), ("F", "isDiscovering", "()"), ("F", "isEnabled", "()"), ("F", "listBonds", "()"), ("F", "removeServiceRecord", "(I)"), ("F", "sendUuidIntent", "(Ljava/lang/String;)"), ("F", "setLinkTimeout", "(Ljava/lang/String; I)"), ("F", "setPropertyBoolean", "(Ljava/lang/String; B)"), ("F", "setPropertyInteger", "(Ljava/lang/String; I)"), ("F", "setPropertyString", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "updateDeviceServiceChannelCache", "(Ljava/lang/String;)"), ("F", "updateRemoteDevicePropertiesCache", "(Ljava/lang/String;)"), ], "Landroid/content/pm/PackageManager;" : [ ("C", "FEATURE_BLUETOOTH", "Ljava/lang/String;"), ], "Landroid/bluetooth/BluetoothAssignedNumbers;" : [ ("C", "BLUETOOTH_SIG", "I"), ], }, "CLEAR_APP_USER_DATA" : { "Landroid/app/ActivityManagerNative;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"), ("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"), ], "Landroid/app/ActivityManager;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; LIPackageDataObserver;)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "clearApplicationUserData", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], }, "WRITE_SMS" : { "Landroid/provider/Telephony$Sms;" : [ ("F", "addMessageToUri", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B J)"), ("F", "addMessageToUri", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B)"), ("F", "moveMessageToFolder", "(Landroid/content/Context; Landroid/net/Uri; I I)"), ], "Landroid/provider/Telephony$Sms$Outbox;" : [ ("F", "addMessage", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B J)"), ], "Landroid/provider/Telephony$Sms$Draft;" : [ ("F", "saveMessage", "(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String;)"), ], }, "SET_PROCESS_LIMIT" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "setProcessForeground", "(Landroid/os/IBinder; I B)"), ("F", "setProcessLimit", "(I)"), ], }, "DEVICE_POWER" : { "Landroid/os/PowerManager;" : [ ("F", "goToSleep", "(J)"), ("F", "setBacklightBrightness", "(I)"), ], "Landroid/os/IPowerManager$Stub$Proxy;" : [ ("F", "clearUserActivityTimeout", "(J J)"), ("F", "goToSleep", "(J)"), ("F", "goToSleepWithReason", "(J I)"), ("F", "preventScreenOn", "(B)"), ("F", "setAttentionLight", "(B I)"), ("F", "setBacklightBrightness", "(I)"), ("F", "setPokeLock", "(I Landroid/os/IBinder; Ljava/lang/String;)"), ("F", "userActivityWithForce", "(J B B)"), ], }, "PERSISTENT_ACTIVITY" : { "Landroid/app/ExpandableListActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/accounts/GrantCredentialsPermissionActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/app/Activity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/app/ListActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/app/AliasActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/accounts/AccountAuthenticatorActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "setPersistent", "(Landroid/os/IBinder; B)"), ], "Landroid/app/TabActivity;" : [ ("F", "setPersistent", "(B)"), ], "Landroid/app/ActivityGroup;" : [ ("F", "setPersistent", "(B)"), ], }, "MANAGE_APP_TOKENS" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "addAppToken", "(I Landroid/view/IApplicationToken; I I B)"), ("F", "addWindowToken", "(Landroid/os/IBinder; I)"), ("F", "executeAppTransition", "()"), ("F", "moveAppToken", "(I Landroid/os/IBinder;)"), ("F", "moveAppTokensToBottom", "(Ljava/util/List;)"), ("F", "moveAppTokensToTop", "(Ljava/util/List;)"), ("F", "pauseKeyDispatching", "(Landroid/os/IBinder;)"), ("F", "prepareAppTransition", "(I)"), ("F", "removeAppToken", "(Landroid/os/IBinder;)"), ("F", "removeWindowToken", "(Landroid/os/IBinder;)"), ("F", "resumeKeyDispatching", "(Landroid/os/IBinder;)"), ("F", "setAppGroupId", "(Landroid/os/IBinder; I)"), ("F", "setAppOrientation", "(Landroid/view/IApplicationToken; I)"), ("F", "setAppStartingWindow", "(Landroid/os/IBinder; Ljava/lang/String; I Ljava/lang/CharSequence; I I Landroid/os/IBinder; B)"), ("F", "setAppVisibility", "(Landroid/os/IBinder; B)"), ("F", "setAppWillBeHidden", "(Landroid/os/IBinder;)"), ("F", "setEventDispatching", "(B)"), ("F", "setFocusedApp", "(Landroid/os/IBinder; B)"), ("F", "setNewConfiguration", "(Landroid/content/res/Configuration;)"), ("F", "startAppFreezingScreen", "(Landroid/os/IBinder; I)"), ("F", "stopAppFreezingScreen", "(Landroid/os/IBinder; B)"), ("F", "updateOrientationFromAppTokens", "(Landroid/content/res/Configuration; Landroid/os/IBinder;)"), ], }, "WRITE_HISTORY_BOOKMARKS" : { "Landroid/provider/Browser;" : [ ("C", "BOOKMARKS_URI", "Landroid/net/Uri;"), ("C", "SEARCHES_URI", "Landroid/net/Uri;"), ("F", "addSearchUrl", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "clearHistory", "(Landroid/content/ContentResolver;)"), ("F", "clearSearches", "(Landroid/content/ContentResolver;)"), ("F", "deleteFromHistory", "(Landroid/content/ContentResolver; Ljava/lang/String;)"), ("F", "deleteHistoryTimeFrame", "(Landroid/content/ContentResolver; J J)"), ("F", "truncateHistory", "(Landroid/content/ContentResolver;)"), ("F", "updateVisitedHistory", "(Landroid/content/ContentResolver; Ljava/lang/String; B)"), ("F", "clearSearches", "(Landroid/content/ContentResolver;)"), ], }, "FORCE_BACK" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "unhandledBack", "(I)"), ], }, "CHANGE_NETWORK_STATE" : { "Landroid/net/IConnectivityManager$Stub$Proxy;" : [ ("F", "requestRouteToHost", "(I I)"), ("F", "setMobileDataEnabled", "(B)"), ("F", "setNetworkPreference", "(I)"), ("F", "setRadio", "(I B)"), ("F", "setRadios", "(B)"), ("F", "stopUsingNetworkFeature", "(I Ljava/lang/String;)"), ("F", "tether", "(Ljava/lang/String;)"), ("F", "untether", "(Ljava/lang/String;)"), ], "Landroid/net/ConnectivityManager;" : [ ("F", "requestRouteToHost", "(I I)"), ("F", "setMobileDataEnabled", "(B)"), ("F", "setNetworkPreference", "(I)"), ("F", "setRadio", "(I B)"), ("F", "setRadios", "(B)"), ("F", "startUsingNetworkFeature", "(I Ljava/lang/String;)"), ("F", "stopUsingNetworkFeature", "(I Ljava/lang/String;)"), ("F", "tether", "(Ljava/lang/String;)"), ("F", "untether", "(Ljava/lang/String;)"), ], "Landroid/os/INetworkManagementService$Stub$Proxy;" : [ ("F", "attachPppd", "(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)"), ("F", "detachPppd", "(Ljava/lang/String;)"), ("F", "disableNat", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "enableNat", "(Ljava/lang/String; Ljava/lang/String;)"), ("F", "setAccessPoint", "(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)"), ("F", "setInterfaceThrottle", "(Ljava/lang/String; I I)"), ("F", "setIpForwardingEnabled", "(B)"), ("F", "startAccessPoint", "(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)"), ("F", "startUsbRNDIS", "()"), ("F", "stopAccessPoint", "()"), ("F", "stopTethering", "()"), ("F", "stopUsbRNDIS", "()"), ("F", "tetherInterface", "(Ljava/lang/String;)"), ("F", "unregisterObserver", "(Landroid/net/INetworkManagementEventObserver;)"), ("F", "untetherInterface", "(Ljava/lang/String;)"), ], }, "WRITE_SYNC_SETTINGS" : { "Landroid/app/ContextImpl$ApplicationContentResolver;" : [ ("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"), ("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"), ("F", "setMasterSyncAutomatically", "(B)"), ("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ], "Landroid/content/ContentService;" : [ ("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"), ("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"), ("F", "setMasterSyncAutomatically", "(B)"), ("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ], "Landroid/content/ContentResolver;" : [ ("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"), ("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"), ("F", "setMasterSyncAutomatically", "(B)"), ("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ], "Landroid/content/IContentService$Stub$Proxy;" : [ ("F", "addPeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)"), ("F", "removePeriodicSync", "(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "setIsSyncable", "(Landroid/accounts/Account; Ljava/lang/String; I)"), ("F", "setMasterSyncAutomatically", "(B)"), ("F", "setSyncAutomatically", "(Landroid/accounts/Account; Ljava/lang/String; B)"), ], }, "ACCOUNT_MANAGER" : { "Landroid/accounts/AccountManager;" : [ ("C", "KEY_ACCOUNT_MANAGER_RESPONSE", "Ljava/lang/String;"), ], "Landroid/accounts/AbstractAccountAuthenticator;" : [ ("F", "checkBinderPermission", "()"), ("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"), ("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"), ("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"), ("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"), ], "Landroid/accounts/AbstractAccountAuthenticator$Transport;" : [ ("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"), ("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"), ("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"), ("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"), ("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ], "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;" : [ ("F", "addAccount", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)"), ("F", "confirmCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)"), ("F", "editProperties", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "getAccountRemovalAllowed", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)"), ("F", "getAuthToken", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ("F", "getAuthTokenLabel", "(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)"), ("F", "hasFeatures", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"), ("F", "updateCredentials", "(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)"), ], }, "SET_ANIMATION_SCALE" : { "Landroid/view/IWindowManager$Stub$Proxy;" : [ ("F", "setAnimationScale", "(I F)"), ("F", "setAnimationScales", "([L;)"), ], }, "GET_ACCOUNTS" : { "Landroid/accounts/AccountManager;" : [ ("F", "getAccounts", "()"), ("F", "getAccountsByType", "(Ljava/lang/String;)"), ("F", "getAccountsByTypeAndFeatures", "(Ljava/lang/String; [Ljava/lang/String; [Landroid/accounts/AccountManagerCallback<android/accounts/Account[; Landroid/os/Handler;)"), ("F", "hasFeatures", "(Landroid/accounts/Account; [Ljava/lang/String; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)"), ("F", "addOnAccountsUpdatedListener", "(Landroid/accounts/OnAccountsUpdateListener; Landroid/os/Handler; B)"), ("F", "getAccounts", "()"), ("F", "getAccountsByType", "(Ljava/lang/String;)"), ("F", "getAccountsByTypeAndFeatures", "(Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "getAuthTokenByFeatures", "(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ("F", "hasFeatures", "(Landroid/accounts/Account; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)"), ], "Landroid/content/ContentService;" : [ ("F", "<init>", "(Landroid/content/Context; B)"), ("F", "main", "(Landroid/content/Context; B)"), ], "Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;" : [ ("F", "doWork", "()"), ("F", "start", "()"), ], "Landroid/accounts/AccountManager$AmsTask;" : [ ("F", "doWork", "()"), ("F", "start", "()"), ], "Landroid/accounts/IAccountManager$Stub$Proxy;" : [ ("F", "getAccounts", "(Ljava/lang/String;)"), ("F", "getAccountsByFeatures", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)"), ("F", "hasFeatures", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"), ], "Landroid/accounts/AccountManagerService;" : [ ("F", "checkReadAccountsPermission", "()"), ("F", "getAccounts", "(Ljava/lang/String;)"), ("F", "getAccountsByFeatures", "(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)"), ("F", "hasFeatures", "(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)"), ], }, "RECEIVE_SMS" : { "Landroid/telephony/gsm/SmsManager;" : [ ("F", "copyMessageToSim", "([L; [L; I)"), ("F", "deleteMessageFromSim", "(I)"), ("F", "getAllMessagesFromSim", "()"), ("F", "updateMessageOnSim", "(I I [L;)"), ], "Landroid/telephony/SmsManager;" : [ ("F", "copyMessageToIcc", "([L; [L; I)"), ("F", "deleteMessageFromIcc", "(I)"), ("F", "getAllMessagesFromIcc", "()"), ("F", "updateMessageOnIcc", "(I I [L;)"), ], "Lcom/android/internal/telephony/ISms$Stub$Proxy;" : [ ("F", "copyMessageToIccEf", "(I [B [B)"), ("F", "getAllMessagesFromIccEf", "()"), ("F", "updateMessageOnIccEf", "(I I [B)"), ], }, "STOP_APP_SWITCHES" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "resumeAppSwitches", "()"), ("F", "stopAppSwitches", "()"), ], }, "DELETE_CACHE_FILES" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; LIPackageDataObserver;)"), ("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "deleteApplicationCacheFiles", "(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)"), ], }, "WRITE_EXTERNAL_STORAGE" : { "Landroid/os/Build/VERSION_CODES;" : [ ("C", "DONUT", "I"), ], "Landroid/app/DownloadManager/Request;" : [ ("F", "setDestinationUri", "(Landroid/net/Uri;)"), ], }, "REBOOT" : { "Landroid/os/RecoverySystem;" : [ ("F", "installPackage", "(Landroid/content/Context; Ljava/io/File;)"), ("F", "rebootWipeUserData", "(Landroid/content/Context;)"), ("F", "bootCommand", "(Landroid/content/Context; Ljava/lang/String;)"), ("F", "installPackage", "(Landroid/content/Context; Ljava/io/File;)"), ("F", "rebootWipeUserData", "(Landroid/content/Context;)"), ], "Landroid/content/Intent;" : [ ("C", "IntentResolution", "Ljava/lang/String;"), ("C", "ACTION_REBOOT", "Ljava/lang/String;"), ], "Landroid/os/PowerManager;" : [ ("F", "reboot", "(Ljava/lang/String;)"), ("F", "reboot", "(Ljava/lang/String;)"), ], "Landroid/os/IPowerManager$Stub$Proxy;" : [ ("F", "crash", "(Ljava/lang/String;)"), ("F", "reboot", "(Ljava/lang/String;)"), ], }, "INSTALL_PACKAGES" : { "Landroid/app/ContextImpl$ApplicationPackageManager;" : [ ("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"), ("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"), ], "Landroid/content/pm/PackageManager;" : [ ("F", "installPackage", "(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)"), ], "Landroid/content/pm/IPackageManager$Stub$Proxy;" : [ ("F", "installPackage", "(Landroid/net/Uri; Landroid/content/pm/IPackageInstallObserver; I Ljava/lang/String;)"), ], }, "SET_DEBUG_APP" : { "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "setDebugApp", "(Ljava/lang/String; B B)"), ], }, "INSTALL_LOCATION_PROVIDER" : { "Landroid/location/ILocationManager$Stub$Proxy;" : [ ("F", "reportLocation", "(Landroid/location/Location; B)"), ], }, "SET_WALLPAPER_HINTS" : { "Landroid/app/WallpaperManager;" : [ ("F", "suggestDesiredDimensions", "(I I)"), ], "Landroid/app/IWallpaperManager$Stub$Proxy;" : [ ("F", "setDimensionHints", "(I I)"), ], }, "READ_CONTACTS" : { "Landroid/app/ContextImpl$ApplicationContentResolver;" : [ ("F", "openFileDescriptor", "(Landroid/net/Uri; Ljava/lang/String;)"), ("F", "openInputStream", "(Landroid/net/Uri;)"), ("F", "openOutputStream", "(Landroid/net/Uri;)"), ("F", "query", "(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"), ], "Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;" : [ ("F", "getAdnRecordsInEf", "(I)"), ], "Landroid/provider/Contacts$People;" : [ ("F", "addToGroup", "(Landroid/content/ContentResolver; J Ljava/lang/String;)"), ("F", "addToMyContactsGroup", "(Landroid/content/ContentResolver; J)"), ("F", "createPersonInMyContactsGroup", "(Landroid/content/ContentResolver; Landroid/content/ContentValues;)"), ("F", "loadContactPhoto", "(Landroid/content/Context; Landroid/net/Uri; I Landroid/graphics/BitmapFactory$Options;)"), ("F", "markAsContacted", "(Landroid/content/ContentResolver; J)"), ("F", "openContactPhotoInputStream", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ("F", "queryGroups", "(Landroid/content/ContentResolver; J)"), ("F", "setPhotoData", "(Landroid/content/ContentResolver; Landroid/net/Uri; [L;)"), ("F", "tryGetMyContactsGroupId", "(Landroid/content/ContentResolver;)"), ], "Landroid/provider/ContactsContract$Data;" : [ ("F", "getContactLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ], "Landroid/provider/ContactsContract$Contacts;" : [ ("F", "getLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ("F", "lookupContact", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ("F", "openContactPhotoInputStream", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ], "Landroid/pim/vcard/VCardComposer;" : [ ("F", "createOneEntry", "()"), ("F", "createOneEntry", "(Ljava/lang/reflect/Method;)"), ("F", "createOneEntryInternal", "(Ljava/lang/String; Ljava/lang/reflect/Method;)"), ("F", "init", "()"), ("F", "init", "(Ljava/lang/String; [L[Ljava/lang/Strin;)"), ], "Landroid/pim/vcard/VCardComposer$OneEntryHandler;" : [ ("F", "onInit", "(Landroid/content/Context;)"), ], "Lcom/android/internal/telephony/CallerInfo;" : [ ("F", "getCallerId", "(Landroid/content/Context; Ljava/lang/String;)"), ("F", "getCallerInfo", "(Landroid/content/Context; Ljava/lang/String;)"), ], "Landroid/provider/Contacts$Settings;" : [ ("F", "getSetting", "(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)"), ], "Landroid/provider/ContactsContract$RawContacts;" : [ ("F", "getContactLookupUri", "(Landroid/content/ContentResolver; Landroid/net/Uri;)"), ], "Landroid/provider/CallLog$Calls;" : [ ("F", "addCall", "(Lcom/android/internal/telephony/CallerInfo; Landroid/content/Context; Ljava/lang/String; I I J I)"), ("F", "getLastOutgoingCall", "(Landroid/content/Context;)"), ], "Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;" : [ ("F", "getAdnRecordsInEf", "(I)"), ], "Landroid/pim/vcard/VCardComposer$HandlerForOutputStream;" : [ ("F", "onInit", "(Landroid/content/Context;)"), ], "Landroid/provider/ContactsContract$CommonDataKinds$Phone;" : [ ("C", "CONTENT_URI", "Landroid/net/Uri;"), ], "Landroid/widget/QuickContactBadge;" : [ ("F", "assignContactFromEmail", "(Ljava/lang/String; B)"), ("F", "assignContactFromPhone", "(Ljava/lang/String; B)"), ("F", "trigger", "(Landroid/net/Uri;)"), ], "Landroid/content/ContentResolver;" : [ ("F", "openFileDescriptor", "(Landroid/net/Uri; Ljava/lang/String;)"), ("F", "openInputStream", "(Landroid/net/Uri;)"), ("F", "openOutputStream", "(Landroid/net/Uri;)"), ("F", "query", "(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)"), ], }, "BACKUP" : { "Landroid/app/backup/IBackupManager$Stub$Proxy;" : [ ("F", "backupNow", "()"), ("F", "beginRestoreSession", "(Ljava/lang/String;)"), ("F", "clearBackupData", "(Ljava/lang/String;)"), ("F", "dataChanged", "(Ljava/lang/String;)"), ("F", "getCurrentTransport", "()"), ("F", "isBackupEnabled", "()"), ("F", "listAllTransports", "()"), ("F", "selectBackupTransport", "(Ljava/lang/String;)"), ("F", "setAutoRestore", "(B)"), ("F", "setBackupEnabled", "(B)"), ], "Landroid/app/IActivityManager$Stub$Proxy;" : [ ("F", "bindBackupAgent", "(Landroid/content/pm/ApplicationInfo; I)"), ], "Landroid/app/backup/BackupManager;" : [ ("F", "beginRestoreSession", "()"), ("F", "dataChanged", "(Ljava/lang/String;)"), ("F", "requestRestore", "(Landroid/app/backup/RestoreObserver;)"), ], }, } DVM_PERMISSIONS_BY_ELEMENT = { "Landroid/app/admin/DeviceAdminReceiver;-ACTION_DEVICE_ADMIN_ENABLED-Ljava/lang/String;" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/DevicePolicyManager;-getRemoveWarning-(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/DevicePolicyManager;-reportFailedPasswordAttempt-()" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/DevicePolicyManager;-reportSuccessfulPasswordAttempt-()" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/DevicePolicyManager;-setActiveAdmin-(Landroid/content/ComponentName;)" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/DevicePolicyManager;-setActivePasswordState-(I I)" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-getRemoveWarning-(Landroid/content/ComponentName; Landroid/os/RemoteCallback;)" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-reportFailedPasswordAttempt-()" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-reportSuccessfulPasswordAttempt-()" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-setActiveAdmin-(Landroid/content/ComponentName;)" : "BIND_DEVICE_ADMIN", "Landroid/app/admin/IDevicePolicyManager$Stub$Proxy;-setActivePasswordState-(I I)" : "BIND_DEVICE_ADMIN", "Landroid/app/ContextImpl$ApplicationContentResolver;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentService;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentService;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS", "Landroid/content/ContentService;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentService;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentResolver;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentResolver;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS", "Landroid/content/ContentResolver;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/ContentResolver;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-getIsSyncable-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-getMasterSyncAutomatically-()" : "READ_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-getPeriodicSyncs-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-getSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_SETTINGS", "Landroid/content/pm/ApplicationInfo;-FLAG_FACTORY_TEST-I" : "FACTORY_TEST", "Landroid/content/pm/ApplicationInfo;-flags-I" : "FACTORY_TEST", "Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "FACTORY_TEST", "Landroid/content/Intent;-ACTION_FACTORY_TEST-Ljava/lang/String;" : "FACTORY_TEST", "Landroid/app/IActivityManager$Stub$Proxy;-setAlwaysFinish-(B)" : "SET_ALWAYS_FINISH", "Landroid/provider/Calendar$CalendarAlerts;-alarmExists-(Landroid/content/ContentResolver; J J J)" : "READ_CALENDAR", "Landroid/provider/Calendar$CalendarAlerts;-findNextAlarmTime-(Landroid/content/ContentResolver; J)" : "READ_CALENDAR", "Landroid/provider/Calendar$CalendarAlerts;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CALENDAR", "Landroid/provider/Calendar$Calendars;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR", "Landroid/provider/Calendar$Events;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR", "Landroid/provider/Calendar$Events;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_CALENDAR", "Landroid/provider/Calendar$Instances;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J Ljava/lang/String; Ljava/lang/String;)" : "READ_CALENDAR", "Landroid/provider/Calendar$Instances;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; J J)" : "READ_CALENDAR", "Landroid/provider/Calendar$EventDays;-query-(Landroid/content/ContentResolver; I I)" : "READ_CALENDAR", "Landroid/provider/DrmStore;-enforceAccessDrmPermission-(Landroid/content/Context;)" : "ACCESS_DRM", "Landroid/app/IActivityManager$Stub$Proxy;-updateConfiguration-(Landroid/content/res/Configuration;)" : "CHANGE_CONFIGURATION", "Landroid/app/IActivityManager$Stub$Proxy;-profileControl-(Ljava/lang/String; B Ljava/lang/String; Landroid/os/ParcelFileDescriptor;)" : "SET_ACTIVITY_WATCHER", "Landroid/app/IActivityManager$Stub$Proxy;-setActivityController-(Landroid/app/IActivityController;)" : "SET_ACTIVITY_WATCHER", "Landroid/app/ContextImpl$ApplicationPackageManager;-getPackageSizeInfo-(Ljava/lang/String; LIPackageStatsObserver;)" : "GET_PACKAGE_SIZE", "Landroid/app/ContextImpl$ApplicationPackageManager;-getPackageSizeInfo-(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)" : "GET_PACKAGE_SIZE", "Landroid/content/pm/PackageManager;-getPackageSizeInfo-(Ljava/lang/String; Landroid/content/pm/IPackageStatsObserver;)" : "GET_PACKAGE_SIZE", "Landroid/telephony/TelephonyManager;-disableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES", "Landroid/telephony/TelephonyManager;-enableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableLocationUpdates-()" : "CONTROL_LOCATION_UPDATES", "Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorage-(J LIntentSender;)" : "CLEAR_APP_CACHE", "Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorageAndNotify-(J LIPackageDataObserver;)" : "CLEAR_APP_CACHE", "Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE", "Landroid/app/ContextImpl$ApplicationPackageManager;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE", "Landroid/content/pm/PackageManager;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE", "Landroid/content/pm/PackageManager;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE", "Landroid/content/pm/IPackageManager$Stub$Proxy;-freeStorage-(J Landroid/content/IntentSender;)" : "CLEAR_APP_CACHE", "Landroid/content/pm/IPackageManager$Stub$Proxy;-freeStorageAndNotify-(J Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_CACHE", "Landroid/view/inputmethod/InputMethod;-SERVICE_INTERFACE-Ljava/lang/String;" : "BIND_INPUT_METHOD", "Landroid/app/IActivityManager$Stub$Proxy;-signalPersistentProcesses-(I)" : "SIGNAL_PERSISTENT_PROCESSES", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getAwakeTimeBattery-()" : "BATTERY_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getAwakeTimePlugged-()" : "BATTERY_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-getStatistics-()" : "BATTERY_STATS", "Landroid/accounts/AccountManager;-addAccountExplicitly-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-addAccountExplicitly-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManager;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-addAccount-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-checkAuthenticateAccountsPermission-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-addAccount-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-getPassword-(Landroid/accounts/Account;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-getUserData-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-peekAuthToken-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-setAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-setPassword-(Landroid/accounts/Account; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-setUserData-(Landroid/accounts/Account; Ljava/lang/String; Ljava/lang/String;)" : "AUTHENTICATE_ACCOUNTS", "Landroid/net/IConnectivityManager$Stub$Proxy;-setBackgroundDataSetting-(B)" : "CHANGE_BACKGROUND_DATA_SETTING", "Landroid/net/ConnectivityManager;-setBackgroundDataSetting-(B)" : "CHANGE_BACKGROUND_DATA_SETTING", "Landroid/app/ActivityManagerNative;-killBackgroundProcesses-(Ljava/lang/String;)" : "RESTART_PACKAGES", "Landroid/app/ActivityManagerNative;-restartPackage-(Ljava/lang/String;)" : "RESTART_PACKAGES", "Landroid/app/ActivityManager;-killBackgroundProcesses-(Ljava/lang/String;)" : "RESTART_PACKAGES", "Landroid/app/ActivityManager;-restartPackage-(Ljava/lang/String;)" : "RESTART_PACKAGES", "Landroid/telephony/TelephonyManager;-getCompleteVoiceMailNumber-()" : "CALL_PRIVILEGED", "Landroid/telephony/PhoneNumberUtils;-getNumberFromIntent-(Landroid/content/Intent; Landroid/content/Context;)" : "CALL_PRIVILEGED", "Landroid/app/IWallpaperManager$Stub$Proxy;-setWallpaperComponent-(Landroid/content/ComponentName;)" : "SET_WALLPAPER_COMPONENT", "Landroid/view/IWindowManager$Stub$Proxy;-disableKeyguard-(Landroid/os/IBinder; Ljava/lang/String;)" : "DISABLE_KEYGUARD", "Landroid/view/IWindowManager$Stub$Proxy;-exitKeyguardSecurely-(Landroid/view/IOnKeyguardExitResult;)" : "DISABLE_KEYGUARD", "Landroid/view/IWindowManager$Stub$Proxy;-reenableKeyguard-(Landroid/os/IBinder;)" : "DISABLE_KEYGUARD", "Landroid/app/KeyguardManager;-exitKeyguardSecurely-(Landroid/app/KeyguardManager$OnKeyguardExitResult;)" : "DISABLE_KEYGUARD", "Landroid/app/KeyguardManager$KeyguardLock;-disableKeyguard-()" : "DISABLE_KEYGUARD", "Landroid/app/KeyguardManager$KeyguardLock;-reenableKeyguard-()" : "DISABLE_KEYGUARD", "Landroid/app/ContextImpl$ApplicationPackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES", "Landroid/app/ContextImpl$ApplicationPackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES", "Landroid/content/pm/PackageManager;-deletePackage-(Ljava/lang/String; LIPackageDeleteObserver; I)" : "DELETE_PACKAGES", "Landroid/content/pm/IPackageManager$Stub$Proxy;-deletePackage-(Ljava/lang/String; Landroid/content/pm/IPackageDeleteObserver; I)" : "DELETE_PACKAGES", "Landroid/app/ContextImpl$ApplicationPackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/app/ContextImpl$ApplicationPackageManager;-setComponentEnabledSetting-(LComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/app/ContextImpl$ApplicationPackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/app/ContextImpl$ApplicationPackageManager;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/content/pm/PackageManager;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/content/pm/PackageManager;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/content/pm/IPackageManager$Stub$Proxy;-setApplicationEnabledSetting-(Ljava/lang/String; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/content/pm/IPackageManager$Stub$Proxy;-setComponentEnabledSetting-(Landroid/content/ComponentName; I I)" : "CHANGE_COMPONENT_ENABLED_STATE", "Landroid/os/storage/IMountService$Stub$Proxy;-getSecureContainerList-()" : "ASEC_ACCESS", "Landroid/os/storage/IMountService$Stub$Proxy;-getSecureContainerPath-(Ljava/lang/String;)" : "ASEC_ACCESS", "Landroid/os/storage/IMountService$Stub$Proxy;-isSecureContainerMounted-(Ljava/lang/String;)" : "ASEC_ACCESS", "Lcom/android/internal/app/IUsageStats$Stub$Proxy;-noteLaunchTime-(LComponentName;)" : "UPDATE_DEVICE_STATS ", "Landroid/net/sip/SipAudioCall;-startAudio-()" : "RECORD_AUDIO", "Landroid/media/MediaRecorder;-setAudioSource-(I)" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-cancel-()" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-handleCancelMessage-()" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-handleStartListening-(Landroid/content/Intent;)" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-handleStopMessage-()" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-startListening-(Landroid/content/Intent;)" : "RECORD_AUDIO", "Landroid/speech/SpeechRecognizer;-stopListening-()" : "RECORD_AUDIO", "Landroid/media/AudioRecord;-<init>-(I I I I I)" : "RECORD_AUDIO", "Landroid/location/LocationManager;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/LocationManager;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-addTestProvider-(Ljava/lang/String; B B B B B B B I I)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderEnabled-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderLocation-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-clearTestProviderStatus-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-removeTestProvider-(Ljava/lang/String;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderEnabled-(Ljava/lang/String; B)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderLocation-(Ljava/lang/String; Landroid/location/Location;)" : "ACCESS_MOCK_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-setTestProviderStatus-(Ljava/lang/String; I Landroid/os/Bundle; J)" : "ACCESS_MOCK_LOCATION", "Landroid/media/AudioManager;-EXTRA_RINGER_MODE-Ljava/lang/String;" : "VIBRATE", "Landroid/media/AudioManager;-EXTRA_VIBRATE_SETTING-Ljava/lang/String;" : "VIBRATE", "Landroid/media/AudioManager;-EXTRA_VIBRATE_TYPE-Ljava/lang/String;" : "VIBRATE", "Landroid/media/AudioManager;-FLAG_REMOVE_SOUND_AND_VIBRATE-I" : "VIBRATE", "Landroid/media/AudioManager;-FLAG_VIBRATE-I" : "VIBRATE", "Landroid/media/AudioManager;-RINGER_MODE_VIBRATE-I" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_SETTING_CHANGED_ACTION-Ljava/lang/String;" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_SETTING_OFF-I" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_SETTING_ON-I" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_SETTING_ONLY_SILENT-I" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_TYPE_NOTIFICATION-I" : "VIBRATE", "Landroid/media/AudioManager;-VIBRATE_TYPE_RINGER-I" : "VIBRATE", "Landroid/media/AudioManager;-getRingerMode-()" : "VIBRATE", "Landroid/media/AudioManager;-getVibrateSetting-(I)" : "VIBRATE", "Landroid/media/AudioManager;-setRingerMode-(I)" : "VIBRATE", "Landroid/media/AudioManager;-setVibrateSetting-(I I)" : "VIBRATE", "Landroid/media/AudioManager;-shouldVibrate-(I)" : "VIBRATE", "Landroid/os/Vibrator;-cancel-()" : "VIBRATE", "Landroid/os/Vibrator;-vibrate-([L; I)" : "VIBRATE", "Landroid/os/Vibrator;-vibrate-(J)" : "VIBRATE", "Landroid/provider/Settings/System;-VIBRATE_ON-Ljava/lang/String;" : "VIBRATE", "Landroid/app/NotificationManager;-notify-(I Landroid/app/Notification;)" : "VIBRATE", "Landroid/app/NotificationManager;-notify-(Ljava/lang/String; I Landroid/app/Notification;)" : "VIBRATE", "Landroid/app/Notification/Builder;-setDefaults-(I)" : "VIBRATE", "Landroid/os/IVibratorService$Stub$Proxy;-cancelVibrate-(Landroid/os/IBinder;)" : "VIBRATE", "Landroid/os/IVibratorService$Stub$Proxy;-vibrate-(J Landroid/os/IBinder;)" : "VIBRATE", "Landroid/os/IVibratorService$Stub$Proxy;-vibratePattern-([L; I Landroid/os/IBinder;)" : "VIBRATE", "Landroid/app/Notification;-DEFAULT_VIBRATE-I" : "VIBRATE", "Landroid/app/Notification;-defaults-I" : "VIBRATE", "Landroid/os/storage/IMountService$Stub$Proxy;-createSecureContainer-(Ljava/lang/String; I Ljava/lang/String; Ljava/lang/String; I)" : "ASEC_CREATE", "Landroid/os/storage/IMountService$Stub$Proxy;-finalizeSecureContainer-(Ljava/lang/String;)" : "ASEC_CREATE", "Landroid/bluetooth/BluetoothAdapter;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS", "Landroid/bluetooth/BluetoothAdapter;-setScanMode-(I)" : "WRITE_SECURE_SETTINGS", "Landroid/server/BluetoothService;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS", "Landroid/os/IPowerManager$Stub$Proxy;-setMaximumScreenOffTimeount-(I)" : "WRITE_SECURE_SETTINGS", "Landroid/content/pm/IPackageManager$Stub$Proxy;-setInstallLocation-(I)" : "WRITE_SECURE_SETTINGS", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setScanMode-(I I)" : "WRITE_SECURE_SETTINGS", "Landroid/view/IWindowManager$Stub$Proxy;-setRotation-(I B I)" : "SET_ORIENTATION", "Lcom/android/internal/app/IUsageStats$Stub$Proxy;-getAllPkgUsageStats-()" : "PACKAGE_USAGE_STATS", "Lcom/android/internal/app/IUsageStats$Stub$Proxy;-getPkgUsageStats-(LComponentName;)" : "PACKAGE_USAGE_STATS", "Landroid/os/IHardwareService$Stub$Proxy;-setFlashlightEnabled-(B)" : "FLASHLIGHT", "Landroid/app/SearchManager;-EXTRA_SELECT_QUERY-Ljava/lang/String;" : "GLOBAL_SEARCH", "Landroid/app/SearchManager;-INTENT_ACTION_GLOBAL_SEARCH-Ljava/lang/String;" : "GLOBAL_SEARCH", "Landroid/server/search/Searchables;-buildSearchableList-()" : "GLOBAL_SEARCH", "Landroid/server/search/Searchables;-findGlobalSearchActivity-()" : "GLOBAL_SEARCH", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-addOrUpdateNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-disableNetwork-(I)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-disconnect-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-enableNetwork-(I B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-pingSupplicant-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-reassociate-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-reconnect-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-removeNetwork-(I)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-saveConfiguration-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-setNumAllowedChannels-(I B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-setWifiApEnabled-(Landroid/net/wifi/WifiConfiguration; B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-setWifiEnabled-(B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-startScan-(B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-addNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-addOrUpdateNetwork-(Landroid/net/wifi/WifiConfiguration;)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-disableNetwork-(I)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-disconnect-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-enableNetwork-(I B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-pingSupplicant-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-reassociate-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-reconnect-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-removeNetwork-(I)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-saveConfiguration-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-setNumAllowedChannels-(I B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-setWifiApEnabled-(Landroid/net/wifi/WifiConfiguration; B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-setWifiEnabled-(B)" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-startScan-()" : "CHANGE_WIFI_STATE", "Landroid/net/wifi/WifiManager;-startScanActive-()" : "CHANGE_WIFI_STATE", "Landroid/app/ExpandableListActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ExpandableListActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ExpandableListActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/accessibilityservice/AccessibilityService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accessibilityservice/AccessibilityService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accessibilityservice/AccessibilityService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/accounts/GrantCredentialsPermissionActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accounts/GrantCredentialsPermissionActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accounts/GrantCredentialsPermissionActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgent;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgent;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgent;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/service/wallpaper/WallpaperService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/service/wallpaper/WallpaperService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/service/wallpaper/WallpaperService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgentHelper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgentHelper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/backup/BackupAgentHelper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/accounts/AccountAuthenticatorActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accounts/AccountAuthenticatorActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/accounts/AccountAuthenticatorActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/IActivityManager$Stub$Proxy;-unbroadcastIntent-(Landroid/app/IApplicationThread; Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ActivityGroup;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ActivityGroup;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ActivityGroup;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/content/ContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/ContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/ContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/ContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/ContextWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/Activity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Activity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Activity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/ContextImpl;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ContextImpl;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ContextImpl;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/AliasActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/AliasActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/AliasActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/content/Context;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/Context;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/Context;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/Context;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/Context;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/service/urlrenderer/UrlRendererService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/service/urlrenderer/UrlRendererService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/service/urlrenderer/UrlRendererService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/FullBackupAgent;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/FullBackupAgent;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/FullBackupAgent;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/TabActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/TabActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/TabActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/view/ContextThemeWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/view/ContextThemeWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/view/ContextThemeWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/speech/RecognitionService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/speech/RecognitionService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/speech/RecognitionService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/IntentService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/IntentService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/IntentService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/inputmethodservice/AbstractInputMethodService;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/inputmethodservice/AbstractInputMethodService;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/inputmethodservice/AbstractInputMethodService;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/Application;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Application;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Application;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/Application;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/ListActivity;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ListActivity;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/ListActivity;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/Service;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Service;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/app/Service;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/content/MutableContextWrapper;-removeStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/MutableContextWrapper;-sendStickyBroadcast-(Landroid/content/Intent;)" : "BROADCAST_STICKY", "Landroid/content/MutableContextWrapper;-sendStickyOrderedBroadcast-(Landroid/content/Intent; Landroid/content/BroadcastReceiver; Landroid/os/Handler; I Ljava/lang/String; Landroid/os/Bundle;)" : "BROADCAST_STICKY", "Landroid/app/IActivityManager$Stub$Proxy;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES", "Landroid/app/ActivityManagerNative;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES", "Landroid/app/ActivityManager;-forceStopPackage-(Ljava/lang/String;)" : "FORCE_STOP_PACKAGES", "Landroid/app/IActivityManager$Stub$Proxy;-killBackgroundProcesses-(Ljava/lang/String;)" : "KILL_BACKGROUND_PROCESSES", "Landroid/app/ActivityManager;-killBackgroundProcesses-(Ljava/lang/String;)" : "KILL_BACKGROUND_PROCESSES", "Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE", "Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE", "Landroid/app/IAlarmManager$Stub$Proxy;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME_ZONE", "Landroid/server/BluetoothA2dpService;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothA2dpService;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothA2dpService;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothA2dpService;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothA2dpService;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothA2dpService;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothPbap;-disconnect-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-cancelBondProcess-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-cancelDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-cancelPairingUserInput-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-createBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-disable-()" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-disable-(B)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-enable-()" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-enable-(B)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-removeBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setPairingConfirmation-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setPasskey-(Ljava/lang/String; I)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setPin-(Ljava/lang/String; [L;)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-setTrust-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN", "Landroid/server/BluetoothService;-startDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothHeadset;-connectHeadset-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothHeadset;-disconnectHeadset-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothHeadset;-setPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-connectHeadset-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-disconnectHeadset-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-setPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-cancelBondProcess-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-cancelPairingUserInput-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-createBond-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-removeBond-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-setPairingConfirmation-(B)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-setPasskey-(I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothDevice;-setPin-([L;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-connect-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-disconnect-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothA2dp;-connectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothA2dp;-disconnectSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothA2dp;-resumeSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothA2dp;-setSinkPriority-(Landroid/bluetooth/BluetoothDevice; I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/BluetoothA2dp;-suspendSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelBondProcess-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-cancelPairingUserInput-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-createBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-disable-(B)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-enable-()" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-removeBond-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setDiscoverableTimeout-(I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setName-(Ljava/lang/String;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPairingConfirmation-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPasskey-(Ljava/lang/String; I)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setPin-(Ljava/lang/String; [L;)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-setTrust-(Ljava/lang/String; B)" : "BLUETOOTH_ADMIN", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-startDiscovery-()" : "BLUETOOTH_ADMIN", "Landroid/view/IWindowManager$Stub$Proxy;-injectKeyEvent-(Landroid/view/KeyEvent; B)" : "INJECT_EVENTS", "Landroid/view/IWindowManager$Stub$Proxy;-injectPointerEvent-(Landroid/view/MotionEvent; B)" : "INJECT_EVENTS", "Landroid/view/IWindowManager$Stub$Proxy;-injectTrackballEvent-(Landroid/view/MotionEvent; B)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-invokeContextMenuAction-(Landroid/app/Activity; I I)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendCharacterSync-(I)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendKeyDownUpSync-(I)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendKeySync-(Landroid/view/KeyEvent;)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendPointerSync-(Landroid/view/MotionEvent;)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendStringSync-(Ljava/lang/String;)" : "INJECT_EVENTS", "Landroid/app/Instrumentation;-sendTrackballEventSync-(Landroid/view/MotionEvent;)" : "INJECT_EVENTS", "Landroid/hardware/Camera/ErrorCallback;-onError-(I Landroid/hardware/Camera;)" : "CAMERA", "Landroid/media/MediaRecorder;-setVideoSource-(I)" : "CAMERA", "Landroid/view/KeyEvent;-KEYCODE_CAMERA-I" : "CAMERA", "Landroid/bluetooth/BluetoothClass/Device;-AUDIO_VIDEO_VIDEO_CAMERA-I" : "CAMERA", "Landroid/provider/MediaStore;-INTENT_ACTION_STILL_IMAGE_CAMERA-Ljava/lang/String;" : "CAMERA", "Landroid/provider/MediaStore;-INTENT_ACTION_VIDEO_CAMERA-Ljava/lang/String;" : "CAMERA", "Landroid/hardware/Camera/CameraInfo;-CAMERA_FACING_BACK-I" : "CAMERA", "Landroid/hardware/Camera/CameraInfo;-CAMERA_FACING_FRONT-I" : "CAMERA", "Landroid/hardware/Camera/CameraInfo;-facing-I" : "CAMERA", "Landroid/provider/ContactsContract/StatusColumns;-CAPABILITY_HAS_CAMERA-I" : "CAMERA", "Landroid/hardware/Camera/Parameters;-setRotation-(I)" : "CAMERA", "Landroid/media/MediaRecorder/VideoSource;-CAMERA-I" : "CAMERA", "Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "CAMERA", "Landroid/content/Intent;-ACTION_CAMERA_BUTTON-Ljava/lang/String;" : "CAMERA", "Landroid/content/pm/PackageManager;-FEATURE_CAMERA-Ljava/lang/String;" : "CAMERA", "Landroid/content/pm/PackageManager;-FEATURE_CAMERA_AUTOFOCUS-Ljava/lang/String;" : "CAMERA", "Landroid/content/pm/PackageManager;-FEATURE_CAMERA_FLASH-Ljava/lang/String;" : "CAMERA", "Landroid/content/pm/PackageManager;-FEATURE_CAMERA_FRONT-Ljava/lang/String;" : "CAMERA", "Landroid/hardware/Camera;-CAMERA_ERROR_SERVER_DIED-I" : "CAMERA", "Landroid/hardware/Camera;-CAMERA_ERROR_UNKNOWN-I" : "CAMERA", "Landroid/hardware/Camera;-setDisplayOrientation-(I)" : "CAMERA", "Landroid/hardware/Camera;-native_setup-(Ljava/lang/Object;)" : "CAMERA", "Landroid/hardware/Camera;-open-()" : "CAMERA", "Landroid/app/Activity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/Activity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/Activity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/ExpandableListActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/ExpandableListActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/ExpandableListActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/accessibilityservice/AccessibilityService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/accessibilityservice/AccessibilityService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/accessibilityservice/AccessibilityService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/accounts/GrantCredentialsPermissionActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/accounts/GrantCredentialsPermissionActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/accounts/GrantCredentialsPermissionActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgent;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgent;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgent;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/service/wallpaper/WallpaperService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/service/wallpaper/WallpaperService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/service/wallpaper/WallpaperService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgentHelper;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgentHelper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/backup/BackupAgentHelper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/accounts/AccountAuthenticatorActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/accounts/AccountAuthenticatorActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/accounts/AccountAuthenticatorActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/IWallpaperManager$Stub$Proxy;-setWallpaper-(Ljava/lang/String;)" : "SET_WALLPAPER", "Landroid/app/ActivityGroup;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/ActivityGroup;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/ActivityGroup;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/content/ContextWrapper;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/content/ContextWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/content/ContextWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/WallpaperManager;-setBitmap-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/WallpaperManager;-clear-()" : "SET_WALLPAPER", "Landroid/app/WallpaperManager;-setBitmap-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/WallpaperManager;-setResource-(I)" : "SET_WALLPAPER", "Landroid/app/WallpaperManager;-setStream-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/ContextImpl;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/ContextImpl;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/ContextImpl;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/AliasActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/AliasActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/AliasActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/content/Context;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/content/Context;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/content/Context;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/service/urlrenderer/UrlRendererService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/service/urlrenderer/UrlRendererService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/service/urlrenderer/UrlRendererService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/FullBackupAgent;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/FullBackupAgent;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/FullBackupAgent;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/TabActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/TabActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/TabActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/view/ContextThemeWrapper;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/view/ContextThemeWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/view/ContextThemeWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/speech/RecognitionService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/speech/RecognitionService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/speech/RecognitionService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/IntentService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/IntentService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/IntentService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/inputmethodservice/AbstractInputMethodService;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/inputmethodservice/AbstractInputMethodService;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/inputmethodservice/AbstractInputMethodService;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/Application;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/Application;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/Application;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/ListActivity;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/ListActivity;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/ListActivity;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/app/Service;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/app/Service;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/app/Service;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/content/MutableContextWrapper;-clearWallpaper-()" : "SET_WALLPAPER", "Landroid/content/MutableContextWrapper;-setWallpaper-(Landroid/graphics/Bitmap;)" : "SET_WALLPAPER", "Landroid/content/MutableContextWrapper;-setWallpaper-(Ljava/io/InputStream;)" : "SET_WALLPAPER", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-acquireWifiLock-(Landroid/os/IBinder; I Ljava/lang/String;)" : "WAKE_LOCK", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-releaseWifiLock-(Landroid/os/IBinder;)" : "WAKE_LOCK", "Landroid/bluetooth/HeadsetBase;-acquireWakeLock-()" : "WAKE_LOCK", "Landroid/bluetooth/HeadsetBase;-finalize-()" : "WAKE_LOCK", "Landroid/bluetooth/HeadsetBase;-handleInput-(Ljava/lang/String;)" : "WAKE_LOCK", "Landroid/bluetooth/HeadsetBase;-releaseWakeLock-()" : "WAKE_LOCK", "Landroid/os/PowerManager$WakeLock;-acquire-()" : "WAKE_LOCK", "Landroid/os/PowerManager$WakeLock;-acquire-(J)" : "WAKE_LOCK", "Landroid/os/PowerManager$WakeLock;-release-()" : "WAKE_LOCK", "Landroid/os/PowerManager$WakeLock;-release-(I)" : "WAKE_LOCK", "Landroid/media/MediaPlayer;-setWakeMode-(Landroid/content/Context; I)" : "WAKE_LOCK", "Landroid/media/MediaPlayer;-start-()" : "WAKE_LOCK", "Landroid/media/MediaPlayer;-stayAwake-(B)" : "WAKE_LOCK", "Landroid/media/MediaPlayer;-stop-()" : "WAKE_LOCK", "Landroid/bluetooth/ScoSocket;-acquireWakeLock-()" : "WAKE_LOCK", "Landroid/bluetooth/ScoSocket;-close-()" : "WAKE_LOCK", "Landroid/bluetooth/ScoSocket;-finalize-()" : "WAKE_LOCK", "Landroid/bluetooth/ScoSocket;-releaseWakeLock-()" : "WAKE_LOCK", "Landroid/bluetooth/ScoSocket;-releaseWakeLockNow-()" : "WAKE_LOCK", "Landroid/media/AsyncPlayer;-acquireWakeLock-()" : "WAKE_LOCK", "Landroid/media/AsyncPlayer;-enqueueLocked-(Landroid/media/AsyncPlayer$Command;)" : "WAKE_LOCK", "Landroid/media/AsyncPlayer;-play-(Landroid/content/Context; Landroid/net/Uri; B I)" : "WAKE_LOCK", "Landroid/media/AsyncPlayer;-releaseWakeLock-()" : "WAKE_LOCK", "Landroid/media/AsyncPlayer;-stop-()" : "WAKE_LOCK", "Landroid/net/wifi/WifiManager$WifiLock;-acquire-()" : "WAKE_LOCK", "Landroid/net/wifi/WifiManager$WifiLock;-finalize-()" : "WAKE_LOCK", "Landroid/net/wifi/WifiManager$WifiLock;-release-()" : "WAKE_LOCK", "Landroid/os/IPowerManager$Stub$Proxy;-acquireWakeLock-(I Landroid/os/IBinder; Ljava/lang/String;)" : "WAKE_LOCK", "Landroid/os/IPowerManager$Stub$Proxy;-releaseWakeLock-(Landroid/os/IBinder; I)" : "WAKE_LOCK", "Landroid/net/sip/SipAudioCall;-startAudio-()" : "WAKE_LOCK", "Landroid/os/PowerManager;-ACQUIRE_CAUSES_WAKEUP-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-FULL_WAKE_LOCK-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-ON_AFTER_RELEASE-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-PARTIAL_WAKE_LOCK-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-SCREEN_BRIGHT_WAKE_LOCK-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-SCREEN_DIM_WAKE_LOCK-I" : "WAKE_LOCK", "Landroid/os/PowerManager;-newWakeLock-(I Ljava/lang/String;)" : "WAKE_LOCK", "Landroid/accounts/AccountManager;-addAccount-(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-confirmCredentials-(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-editProperties-(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-getAuthTokenByFeatures-(Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-removeAccount-(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-updateCredentials-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-addAccount-(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-confirmCredentials-(Landroid/accounts/Account; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-editProperties-(Ljava/lang/String; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-removeAccount-(Landroid/accounts/Account; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManager;-updateCredentials-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-addAcount-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-checkManageAccountsOrUseCredentialsPermissions-()" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-checkManageAccountsPermission-()" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-confirmCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-editProperties-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-removeAccount-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/AccountManagerService;-updateCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-addAcount-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-clearPassword-(Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-confirmCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Landroid/os/Bundle; B)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-editProperties-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; B)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-removeAccount-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account;)" : "MANAGE_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-updateCredentials-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B Landroid/os/Bundle;)" : "MANAGE_ACCOUNTS", "Landroid/provider/Calendar$CalendarAlerts;-insert-(Landroid/content/ContentResolver; J J J J I)" : "WRITE_CALENDAR", "Landroid/provider/Calendar$Calendars;-delete-(Landroid/content/ContentResolver; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "WRITE_CALENDAR", "Landroid/provider/Calendar$Calendars;-deleteCalendarsForAccount-(Landroid/content/ContentResolver; Landroid/accounts/Account;)" : "WRITE_CALENDAR", "Landroid/appwidget/AppWidgetManager;-bindAppWidgetId-(I Landroid/content/ComponentName;)" : "BIND_APPWIDGET", "Lcom/android/internal/appwidget/IAppWidgetService$Stub$Proxy;-bindAppWidgetId-(I LComponentName;)" : "BIND_APPWIDGET", "Landroid/os/storage/IMountService$Stub$Proxy;-mountSecureContainer-(Ljava/lang/String; Ljava/lang/String; I)" : "ASEC_MOUNT_UNMOUNT", "Landroid/os/storage/IMountService$Stub$Proxy;-unmountSecureContainer-(Ljava/lang/String; B)" : "ASEC_MOUNT_UNMOUNT", "Landroid/app/ContextImpl$ApplicationPackageManager;-addPreferredActivity-(LIntentFilter; I [LComponentName; LComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/app/ContextImpl$ApplicationPackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/app/ContextImpl$ApplicationPackageManager;-replacePreferredActivity-(LIntentFilter; I [LComponentName; LComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/app/ContextImpl$ApplicationPackageManager;-addPreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/app/ContextImpl$ApplicationPackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/app/ContextImpl$ApplicationPackageManager;-replacePreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/PackageManager;-addPreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/PackageManager;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/PackageManager;-replacePreferredActivity-(Landroid/content/IntentFilter; I [Landroid/content/ComponentName; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/IPackageManager$Stub$Proxy;-addPreferredActivity-(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/IPackageManager$Stub$Proxy;-clearPackagePreferredActivities-(Ljava/lang/String;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/content/pm/IPackageManager$Stub$Proxy;-replacePreferredActivity-(Landroid/content/IntentFilter; I [L[Landroid/content/ComponentNam; Landroid/content/ComponentName;)" : "SET_PREFERRED_APPLICATIONS", "Landroid/inputmethodservice/InputMethodService;-SoftInputView-I" : "NFC", "Landroid/inputmethodservice/InputMethodService;-CandidatesView-I" : "NFC", "Landroid/inputmethodservice/InputMethodService;-FullscreenMode-I" : "NFC", "Landroid/inputmethodservice/InputMethodService;-GeneratingText-I" : "NFC", "Landroid/nfc/tech/NfcA;-close-()" : "NFC", "Landroid/nfc/tech/NfcA;-connect-()" : "NFC", "Landroid/nfc/tech/NfcA;-get-(Landroid/nfc/Tag;)" : "NFC", "Landroid/nfc/tech/NfcA;-transceive-([B)" : "NFC", "Landroid/nfc/tech/NfcB;-close-()" : "NFC", "Landroid/nfc/tech/NfcB;-connect-()" : "NFC", "Landroid/nfc/tech/NfcB;-get-(Landroid/nfc/Tag;)" : "NFC", "Landroid/nfc/tech/NfcB;-transceive-([B)" : "NFC", "Landroid/nfc/NfcAdapter;-ACTION_TECH_DISCOVERED-Ljava/lang/String;" : "NFC", "Landroid/nfc/NfcAdapter;-disableForegroundDispatch-(Landroid/app/Activity;)" : "NFC", "Landroid/nfc/NfcAdapter;-disableForegroundNdefPush-(Landroid/app/Activity;)" : "NFC", "Landroid/nfc/NfcAdapter;-enableForegroundDispatch-(Landroid/app/Activity; Landroid/app/PendingIntent; [Landroid/content/IntentFilter; [[Ljava/lang/String[];)" : "NFC", "Landroid/nfc/NfcAdapter;-enableForegroundNdefPush-(Landroid/app/Activity; Landroid/nfc/NdefMessage;)" : "NFC", "Landroid/nfc/NfcAdapter;-getDefaultAdapter-()" : "NFC", "Landroid/nfc/NfcAdapter;-getDefaultAdapter-(Landroid/content/Context;)" : "NFC", "Landroid/nfc/NfcAdapter;-isEnabled-()" : "NFC", "Landroid/nfc/tech/NfcF;-close-()" : "NFC", "Landroid/nfc/tech/NfcF;-connect-()" : "NFC", "Landroid/nfc/tech/NfcF;-get-(Landroid/nfc/Tag;)" : "NFC", "Landroid/nfc/tech/NfcF;-transceive-([B)" : "NFC", "Landroid/nfc/tech/NdefFormatable;-close-()" : "NFC", "Landroid/nfc/tech/NdefFormatable;-connect-()" : "NFC", "Landroid/nfc/tech/NdefFormatable;-format-(Landroid/nfc/NdefMessage;)" : "NFC", "Landroid/nfc/tech/NdefFormatable;-formatReadOnly-(Landroid/nfc/NdefMessage;)" : "NFC", "Landroid/app/Activity;-Fragments-I" : "NFC", "Landroid/app/Activity;-ActivityLifecycle-I" : "NFC", "Landroid/app/Activity;-ConfigurationChanges-I" : "NFC", "Landroid/app/Activity;-StartingActivities-I" : "NFC", "Landroid/app/Activity;-SavingPersistentState-I" : "NFC", "Landroid/app/Activity;-Permissions-I" : "NFC", "Landroid/app/Activity;-ProcessLifecycle-I" : "NFC", "Landroid/nfc/tech/MifareClassic;-KEY_NFC_FORUM-[B" : "NFC", "Landroid/nfc/tech/MifareClassic;-authenticateSectorWithKeyA-(I [B)" : "NFC", "Landroid/nfc/tech/MifareClassic;-authenticateSectorWithKeyB-(I [B)" : "NFC", "Landroid/nfc/tech/MifareClassic;-close-()" : "NFC", "Landroid/nfc/tech/MifareClassic;-connect-()" : "NFC", "Landroid/nfc/tech/MifareClassic;-decrement-(I I)" : "NFC", "Landroid/nfc/tech/MifareClassic;-increment-(I I)" : "NFC", "Landroid/nfc/tech/MifareClassic;-readBlock-(I)" : "NFC", "Landroid/nfc/tech/MifareClassic;-restore-(I)" : "NFC", "Landroid/nfc/tech/MifareClassic;-transceive-([B)" : "NFC", "Landroid/nfc/tech/MifareClassic;-transfer-(I)" : "NFC", "Landroid/nfc/tech/MifareClassic;-writeBlock-(I [B)" : "NFC", "Landroid/nfc/Tag;-getTechList-()" : "NFC", "Landroid/app/Service;-WhatIsAService-I" : "NFC", "Landroid/app/Service;-ServiceLifecycle-I" : "NFC", "Landroid/app/Service;-Permissions-I" : "NFC", "Landroid/app/Service;-ProcessLifecycle-I" : "NFC", "Landroid/app/Service;-LocalServiceSample-I" : "NFC", "Landroid/app/Service;-RemoteMessengerServiceSample-I" : "NFC", "Landroid/nfc/NfcManager;-getDefaultAdapter-()" : "NFC", "Landroid/nfc/tech/MifareUltralight;-close-()" : "NFC", "Landroid/nfc/tech/MifareUltralight;-connect-()" : "NFC", "Landroid/nfc/tech/MifareUltralight;-readPages-(I)" : "NFC", "Landroid/nfc/tech/MifareUltralight;-transceive-([B)" : "NFC", "Landroid/nfc/tech/MifareUltralight;-writePage-(I [B)" : "NFC", "Landroid/nfc/tech/NfcV;-close-()" : "NFC", "Landroid/nfc/tech/NfcV;-connect-()" : "NFC", "Landroid/nfc/tech/NfcV;-get-(Landroid/nfc/Tag;)" : "NFC", "Landroid/nfc/tech/NfcV;-transceive-([B)" : "NFC", "Landroid/nfc/tech/TagTechnology;-close-()" : "NFC", "Landroid/nfc/tech/TagTechnology;-connect-()" : "NFC", "Landroid/preference/PreferenceActivity;-SampleCode-Ljava/lang/String;" : "NFC", "Landroid/content/pm/PackageManager;-FEATURE_NFC-Ljava/lang/String;" : "NFC", "Landroid/content/Context;-NFC_SERVICE-Ljava/lang/String;" : "NFC", "Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_1-Ljava/lang/String;" : "NFC", "Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_2-Ljava/lang/String;" : "NFC", "Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_3-Ljava/lang/String;" : "NFC", "Landroid/nfc/tech/Ndef;-NFC_FORUM_TYPE_4-Ljava/lang/String;" : "NFC", "Landroid/nfc/tech/Ndef;-close-()" : "NFC", "Landroid/nfc/tech/Ndef;-connect-()" : "NFC", "Landroid/nfc/tech/Ndef;-getType-()" : "NFC", "Landroid/nfc/tech/Ndef;-isWritable-()" : "NFC", "Landroid/nfc/tech/Ndef;-makeReadOnly-()" : "NFC", "Landroid/nfc/tech/Ndef;-writeNdefMessage-(Landroid/nfc/NdefMessage;)" : "NFC", "Landroid/nfc/tech/IsoDep;-close-()" : "NFC", "Landroid/nfc/tech/IsoDep;-connect-()" : "NFC", "Landroid/nfc/tech/IsoDep;-setTimeout-(I)" : "NFC", "Landroid/nfc/tech/IsoDep;-transceive-([B)" : "NFC", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-call-(Ljava/lang/String;)" : "CALL_PHONE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-endCall-()" : "CALL_PHONE", "Lcom/android/http/multipart/FilePart;-sendData-(Ljava/io/OutputStream;)" : "INTERNET", "Lcom/android/http/multipart/FilePart;-sendDispositionHeader-(Ljava/io/OutputStream;)" : "INTERNET", "Ljava/net/HttpURLConnection;-<init>-(Ljava/net/URL;)" : "INTERNET", "Ljava/net/HttpURLConnection;-connect-()" : "INTERNET", "Landroid/webkit/WebSettings;-setBlockNetworkLoads-(B)" : "INTERNET", "Landroid/webkit/WebSettings;-verifyNetworkAccess-()" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-()" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-(Lorg/apache/http/params/HttpParams;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-<init>-(Lorg/apache/http/conn/ClientConnectionManager; Lorg/apache/http/params/HttpParams;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET", "Lorg/apache/http/impl/client/DefaultHttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/client/ResponseHandler;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest;)" : "INTERNET", "Lorg/apache/http/impl/client/HttpClient;-execute-(Lorg/apache/http/HttpHost; Lorg/apache/http/client/methods/HttpUriRequest; Lorg/apache/http/protocol/HttpContext;)" : "INTERNET", "Lcom/android/http/multipart/Part;-send-(Ljava/io/OutputStream;)" : "INTERNET", "Lcom/android/http/multipart/Part;-sendParts-(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part;)" : "INTERNET", "Lcom/android/http/multipart/Part;-sendParts-(Ljava/io/OutputStream; [Lcom/android/http/multipart/Part; [B)" : "INTERNET", "Lcom/android/http/multipart/Part;-sendStart-(Ljava/io/OutputStream;)" : "INTERNET", "Lcom/android/http/multipart/Part;-sendTransferEncodingHeader-(Ljava/io/OutputStream;)" : "INTERNET", "Landroid/drm/DrmErrorEvent;-TYPE_NO_INTERNET_CONNECTION-I" : "INTERNET", "Landroid/webkit/WebViewCore;-<init>-(Landroid/content/Context; Landroid/webkit/WebView; Landroid/webkit/CallbackProxy; Ljava/util/Map;)" : "INTERNET", "Ljava/net/URLConnection;-connect-()" : "INTERNET", "Ljava/net/URLConnection;-getInputStream-()" : "INTERNET", "Landroid/app/Activity;-setContentView-(I)" : "INTERNET", "Ljava/net/MulticastSocket;-<init>-()" : "INTERNET", "Ljava/net/MulticastSocket;-<init>-(I)" : "INTERNET", "Ljava/net/MulticastSocket;-<init>-(Ljava/net/SocketAddress;)" : "INTERNET", "Lcom/android/http/multipart/StringPart;-sendData-(Ljava/io/OuputStream;)" : "INTERNET", "Ljava/net/URL;-getContent-([Ljava/lang/Class;)" : "INTERNET", "Ljava/net/URL;-getContent-()" : "INTERNET", "Ljava/net/URL;-openConnection-(Ljava/net/Proxy;)" : "INTERNET", "Ljava/net/URL;-openConnection-()" : "INTERNET", "Ljava/net/URL;-openStream-()" : "INTERNET", "Ljava/net/DatagramSocket;-<init>-()" : "INTERNET", "Ljava/net/DatagramSocket;-<init>-(I)" : "INTERNET", "Ljava/net/DatagramSocket;-<init>-(I Ljava/net/InetAddress;)" : "INTERNET", "Ljava/net/DatagramSocket;-<init>-(Ljava/net/SocketAddress;)" : "INTERNET", "Ljava/net/ServerSocket;-<init>-()" : "INTERNET", "Ljava/net/ServerSocket;-<init>-(I)" : "INTERNET", "Ljava/net/ServerSocket;-<init>-(I I)" : "INTERNET", "Ljava/net/ServerSocket;-<init>-(I I Ljava/net/InetAddress;)" : "INTERNET", "Ljava/net/ServerSocket;-bind-(Ljava/net/SocketAddress;)" : "INTERNET", "Ljava/net/ServerSocket;-bind-(Ljava/net/SocketAddress; I)" : "INTERNET", "Ljava/net/Socket;-<init>-()" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/lang/String; I)" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/lang/String; I Ljava/net/InetAddress; I)" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/lang/String; I B)" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I)" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I Ljava/net/InetAddress; I)" : "INTERNET", "Ljava/net/Socket;-<init>-(Ljava/net/InetAddress; I B)" : "INTERNET", "Landroid/webkit/WebView;-<init>-(Landroid/content/Context; Landroid/util/AttributeSet; I)" : "INTERNET", "Landroid/webkit/WebView;-<init>-(Landroid/content/Context; Landroid/util/AttributeSet;)" : "INTERNET", "Landroid/webkit/WebView;-<init>-(Landroid/content/Context;)" : "INTERNET", "Ljava/net/NetworkInterface;-<init>-()" : "INTERNET", "Ljava/net/NetworkInterface;-<init>-(Ljava/lang/String; I Ljava/net/InetAddress;)" : "INTERNET", "Landroid/webkit/WebChromeClient;-onGeolocationPermissionsShowPrompt-(Ljava/lang/String; Landroid/webkit/GeolocationPermissions/Callback;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-GPS_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-NETWORK_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-PASSIVE_PROVIDER-Ljava/lang/String;" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-addGpsStatusListener-(Landroid/location/GpsStatus/Listener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-addNmeaListener-(Landroid/location/GpsStatus/NmeaListener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-_requestLocationUpdates-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-_requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-addGpsStatusListener-(Landroid/location/GpsStatus$Listener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-addNmeaListener-(Landroid/location/GpsStatus$NmeaListener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-addProximityAlert-(D D F J Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-best-(Ljava/util/List;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-getBestProvider-(Landroid/location/Criteria; B)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-getLastKnownLocation-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-getProvider-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-getProviders-(Landroid/location/Criteria; B)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-getProviders-(B)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-isProviderEnabled-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener; Landroid/os/Looper;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/LocationListener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/LocationManager;-sendExtraCommand-(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCESS_FINE_LOCATION", "Landroid/webkit/GeolocationService;-registerForLocationUpdates-()" : "ACCESS_FINE_LOCATION", "Landroid/webkit/GeolocationService;-setEnableGps-(B)" : "ACCESS_FINE_LOCATION", "Landroid/webkit/GeolocationService;-start-()" : "ACCESS_FINE_LOCATION", "Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_FINE_LOCATION", "Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_FINE_LOCATION", "Landroid/telephony/TelephonyManager;-getNeighboringCellInfo-()" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-addGpsStatusListener-(Landroid/location/IGpsStatusListener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-addProximityAlert-(D D F J Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-getLastKnownLocation-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-getProviderInfo-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-getProviders-(B)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-isProviderEnabled-(Ljava/lang/String;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-requestLocationUpdates-(Ljava/lang/String; J F Landroid/location/ILocationListener;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-requestLocationUpdatesPI-(Ljava/lang/String; J F Landroid/app/PendingIntent;)" : "ACCESS_FINE_LOCATION", "Landroid/location/ILocationManager$Stub$Proxy;-sendExtraCommand-(Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCESS_FINE_LOCATION", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-getCellLocation-()" : "ACCESS_FINE_LOCATION", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-getNeighboringCellInfo-()" : "ACCESS_FINE_LOCATION", "Landroid/webkit/GeolocationPermissions$Callback;-invok-()" : "ACCESS_FINE_LOCATION", "Landroid/provider/Telephony$Sms$Inbox;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B)" : "READ_SMS", "Landroid/provider/Telephony$Threads;-getOrCreateThreadId-(Landroid/content/Context; Ljava/lang/String;)" : "READ_SMS", "Landroid/provider/Telephony$Threads;-getOrCreateThreadId-(Landroid/content/Context; Ljava/util/Set;)" : "READ_SMS", "Landroid/provider/Telephony$Mms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_SMS", "Landroid/provider/Telephony$Mms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_SMS", "Landroid/provider/Telephony$Sms$Draft;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)" : "READ_SMS", "Landroid/provider/Telephony$Sms$Sent;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long;)" : "READ_SMS", "Landroid/provider/Telephony$Sms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin; Ljava/lang/String; Ljava/lang/String;)" : "READ_SMS", "Landroid/provider/Telephony$Sms;-query-(Landroid/content/ContentResolver; [L[Ljava/lang/Strin;)" : "READ_SMS", "Landroid/view/SurfaceSession;-<init>-()" : "ACCESS_SURFACE_FLINGER", "Landroid/view/Surface;-closeTransaction-()" : "ACCESS_SURFACE_FLINGER", "Landroid/view/Surface;-freezeDisplay-(I)" : "ACCESS_SURFACE_FLINGER", "Landroid/view/Surface;-setOrientation-(I I I)" : "ACCESS_SURFACE_FLINGER", "Landroid/view/Surface;-setOrientation-(I I)" : "ACCESS_SURFACE_FLINGER", "Landroid/view/Surface;-unfreezeDisplay-(I)" : "ACCESS_SURFACE_FLINGER", "Landroid/app/IActivityManager$Stub$Proxy;-moveTaskBackwards-(I)" : "REORDER_TASKS", "Landroid/app/IActivityManager$Stub$Proxy;-moveTaskToBack-(I)" : "REORDER_TASKS", "Landroid/app/IActivityManager$Stub$Proxy;-moveTaskToFront-(I)" : "REORDER_TASKS", "Landroid/app/ActivityManager;-moveTaskToFront-(I I)" : "REORDER_TASKS", "Landroid/net/sip/SipAudioCall;-setSpeakerMode-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/server/BluetoothA2dpService;-checkSinkSuspendState-(I)" : "MODIFY_AUDIO_SETTINGS", "Landroid/server/BluetoothA2dpService;-handleSinkStateChange-(Landroid/bluetooth/BluetoothDevice;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/server/BluetoothA2dpService;-onBluetoothDisable-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/server/BluetoothA2dpService;-onBluetoothEnable-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/IAudioService$Stub$Proxy;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/IAudioService$Stub$Proxy;-setMode-(I Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/IAudioService$Stub$Proxy;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/IAudioService$Stub$Proxy;-startBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/IAudioService$Stub$Proxy;-stopBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioService;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioService;-setMode-(I Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioService;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioService;-startBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioService;-stopBluetoothSco-(Landroid/os/IBinder;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-startBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-stopBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-isBluetoothA2dpOn-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-isWiredHeadsetOn-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setBluetoothScoOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setMicrophoneMute-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setMode-(I)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setParameter-(Ljava/lang/String; Ljava/lang/String;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setParameters-(Ljava/lang/String;)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-setSpeakerphoneOn-(B)" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-startBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS", "Landroid/media/AudioManager;-stopBluetoothSco-()" : "MODIFY_AUDIO_SETTINGS", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getDeviceId-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getDeviceSvn-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getIccSerialNumber-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getLine1AlphaTag-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getLine1Number-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getSubscriberId-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/IPhoneSubInfo$Stub$Proxy;-getVoiceMailNumber-()" : "READ_PHONE_STATE", "Landroid/telephony/PhoneStateListener;-LISTEN_CALL_FORWARDING_INDICATOR-I" : "READ_PHONE_STATE", "Landroid/telephony/PhoneStateListener;-LISTEN_CALL_STATE-I" : "READ_PHONE_STATE", "Landroid/telephony/PhoneStateListener;-LISTEN_DATA_ACTIVITY-I" : "READ_PHONE_STATE", "Landroid/telephony/PhoneStateListener;-LISTEN_MESSAGE_WAITING_INDICATOR-I" : "READ_PHONE_STATE", "Landroid/telephony/PhoneStateListener;-LISTEN_SIGNAL_STRENGTH-I" : "READ_PHONE_STATE", "Landroid/accounts/AccountManagerService$SimWatcher;-onReceive-(Landroid/content/Context; Landroid/content/Intent;)" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/CallerInfo;-markAsVoiceMail-()" : "READ_PHONE_STATE", "Landroid/os/Build/VERSION_CODES;-DONUT-I" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-ACTION_PHONE_STATE_CHANGED-Ljava/lang/String;" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getDeviceId-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getDeviceSoftwareVersion-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getLine1Number-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getSimSerialNumber-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getSubscriberId-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getVoiceMailNumber-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getDeviceId-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getDeviceSoftwareVersion-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getLine1AlphaTag-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getLine1Number-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getSimSerialNumber-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getSubscriberId-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getVoiceMailAlphaTag-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-getVoiceMailNumber-()" : "READ_PHONE_STATE", "Landroid/telephony/TelephonyManager;-listen-(Landroid/telephony/PhoneStateListener; I)" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-listen-(Ljava/lang/String; Lcom/android/internal/telephony/IPhoneStateListener; I B)" : "READ_PHONE_STATE", "Landroid/telephony/PhoneNumberUtils;-isVoiceMailNumber-(Ljava/lang/String;)" : "READ_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-isSimPinEnabled-()" : "READ_PHONE_STATE", "Landroid/media/RingtoneManager;-setActualDefaultRingtoneUri-(Landroid/content/Context; I Landroid/net/Uri;)" : "WRITE_SETTINGS", "Landroid/os/IPowerManager$Stub$Proxy;-setStayOnSetting-(I)" : "WRITE_SETTINGS", "Landroid/server/BluetoothService;-persistBluetoothOnSetting-(B)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Secure;-putFloat-(Landroid/content/ContentResolver; Ljava/lang/String; F)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Secure;-putInt-(Landroid/content/ContentResolver; Ljava/lang/String; I)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Secure;-putLong-(Landroid/content/ContentResolver; Ljava/lang/String; J)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Secure;-putString-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Secure;-setLocationProviderEnabled-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Bookmarks;-add-(Landroid/content/ContentResolver; Landroid/content/Intent; Ljava/lang/String; Ljava/lang/String; C I)" : "WRITE_SETTINGS", "Landroid/provider/Settings$Bookmarks;-getIntentForShortcut-(Landroid/content/ContentResolver; C)" : "WRITE_SETTINGS", "Landroid/os/IMountService$Stub$Proxy;-setAutoStartUm-()" : "WRITE_SETTINGS", "Landroid/os/IMountService$Stub$Proxy;-setPlayNotificationSound-()" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-putConfiguration-(Landroid/content/ContentResolver; Landroid/content/res/Configuration;)" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-putFloat-(Landroid/content/ContentResolver; Ljava/lang/String; F)" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-putInt-(Landroid/content/ContentResolver; Ljava/lang/String; I)" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-putLong-(Landroid/content/ContentResolver; Ljava/lang/String; J)" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-putString-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_SETTINGS", "Landroid/provider/Settings$System;-setShowGTalkServiceStatus-(Landroid/content/ContentResolver; B)" : "WRITE_SETTINGS", "Landroid/service/wallpaper/WallpaperService;-SERVICE_INTERFACE-Ljava/lang/String;" : "BIND_WALLPAPER", "Lcom/android/server/WallpaperManagerService;-bindWallpaperComponentLocked-(Landroid/content/ComponentName;)" : "BIND_WALLPAPER", "Landroid/content/ContentService;-dump-(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Strin;)" : "DUMP", "Landroid/view/IWindowManager$Stub$Proxy;-isViewServerRunning-()" : "DUMP", "Landroid/view/IWindowManager$Stub$Proxy;-startViewServer-(I)" : "DUMP", "Landroid/view/IWindowManager$Stub$Proxy;-stopViewServer-()" : "DUMP", "Landroid/os/Debug;-dumpService-(Ljava/lang/String; Ljava/io/FileDescriptor; [Ljava/lang/String;)" : "DUMP", "Landroid/os/IBinder;-DUMP_TRANSACTION-I" : "DUMP", "Lcom/android/server/WallpaperManagerService;-dump-(Ljava/io/FileDescriptor; Ljava/io/PrintWriter; [L[Ljava/lang/Stri;)" : "DUMP", "Landroid/accounts/AccountManager;-blockingGetAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback<android/os/Bundle>; Landroid/os/Handler;)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-invalidateAuthToken-(Ljava/lang/String; Ljava/lang/String;)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-blockingGetAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; Landroid/app/Activity; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManager;-getAuthToken-(Landroid/accounts/Account; Ljava/lang/String; B Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "USE_CREDENTIALS", "Landroid/accounts/AccountManagerService;-getAuthToken-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)" : "USE_CREDENTIALS", "Landroid/accounts/IAccountManager$Stub$Proxy;-getAuthToken-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; Ljava/lang/String; B B Landroid/os/Bundle;)" : "USE_CREDENTIALS", "Lcom/android/internal/app/IUsageStats$Stub$Proxy;-notePauseComponent-(LComponentName;)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IUsageStats$Stub$Proxy;-noteResumeComponent-(LComponentName;)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteFullWifiLockAcquired-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteFullWifiLockReleased-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteInputEvent-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneDataConnectionState-(I B)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneOff-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneOn-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneSignalStrength-(LSignalStrength;)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-notePhoneState-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScanWifiLockAcquired-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScanWifiLockReleased-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenBrightness-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenOff-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteScreenOn-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartGps-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartSensor-(I I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStartWakelock-(I Ljava/lang/String; I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopGps-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopSensor-(I I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteStopWakelock-(I Ljava/lang/String; I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteUserActivity-(I I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiMulticastDisabled-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiMulticastEnabled-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiOff-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiOn-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiRunning-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-noteWifiStopped-()" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-recordCurrentLevel-(I)" : "UPDATE_DEVICE_STATS", "Lcom/android/internal/app/IBatteryStats$Stub$Proxy;-setOnBattery-(B I)" : "UPDATE_DEVICE_STATS", "Landroid/telephony/gsm/SmsManager;-getDefault-()" : "SEND_SMS", "Landroid/telephony/gsm/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/gsm/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/gsm/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/gsm/SmsManager;-sendMultipartTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)" : "SEND_SMS", "Landroid/telephony/gsm/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/SmsManager;-getDefault-()" : "SEND_SMS", "Landroid/telephony/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/SmsManager;-sendDataMessage-(Ljava/lang/String; Ljava/lang/String; S [L; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/telephony/SmsManager;-sendMultipartTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/util/ArrayList; Ljava/util/ArrayList; Ljava/util/ArrayList;)" : "SEND_SMS", "Landroid/telephony/SmsManager;-sendTextMessage-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendData-(Ljava/lang/String; Ljava/lang/String; I [B Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendMultipartText-(Ljava/lang/String; Ljava/lang/String; Ljava/util/List; Ljava/util/List; Ljava/util/List;)" : "SEND_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-sendText-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/app/PendingIntent; Landroid/app/PendingIntent;)" : "SEND_SMS", "Landroid/provider/UserDictionary$Words;-addWord-(Landroid/content/Context; Ljava/lang/String; I I)" : "WRITE_USER_DICTIONARY", "Landroid/telephony/TelephonyManager;-getCellLocation-()" : "ACCESS_COARSE_LOCATION", "Landroid/telephony/PhoneStateListener;-LISTEN_CELL_LOCATION-I" : "ACCESS_COARSE_LOCATION", "Landroid/location/LocationManager;-NETWORK_PROVIDER-Ljava/lang/String;" : "ACCESS_COARSE_LOCATION", "Landroid/os/storage/IMountService$Stub$Proxy;-renameSecureContainer-(Ljava/lang/String; Ljava/lang/String;)" : "ASEC_RENAME", "Landroid/view/IWindowSession$Stub$Proxy;-add-(Landroid/view/IWindow; Landroid/view/WindowManager$LayoutParams; I Landroid/graphics/Rect;)" : "SYSTEM_ALERT_WINDOW", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-acquireMulticastLock-(Landroid/os/IBinder; Ljava/lang/String;)" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-initializeMulticastFiltering-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-releaseMulticastLock-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/WifiManager$MulticastLock;-acquire-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/WifiManager$MulticastLock;-finalize-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/WifiManager$MulticastLock;-release-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/net/wifi/WifiManager;-initializeMulticastFiltering-()" : "CHANGE_WIFI_MULTICAST_STATE", "Landroid/content/Intent;-ACTION_BOOT_COMPLETED-Ljava/lang/String;" : "RECEIVE_BOOT_COMPLETED", "Landroid/provider/AlarmClock;-ACTION_SET_ALARM-Ljava/lang/String;" : "SET_ALARM", "Landroid/provider/AlarmClock;-EXTRA_HOUR-Ljava/lang/String;" : "SET_ALARM", "Landroid/provider/AlarmClock;-EXTRA_MESSAGE-Ljava/lang/String;" : "SET_ALARM", "Landroid/provider/AlarmClock;-EXTRA_MINUTES-Ljava/lang/String;" : "SET_ALARM", "Landroid/provider/AlarmClock;-EXTRA_SKIP_UI-Ljava/lang/String;" : "SET_ALARM", "Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-updateAdnRecordsInEfByIndex-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS", "Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-updateAdnRecordsInEfBySearch-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS", "Landroid/provider/Contacts$People;-addToGroup-(Landroid/content/ContentResolver; J J)" : "WRITE_CONTACTS", "Landroid/provider/ContactsContract$Contacts;-markAsContacted-(Landroid/content/ContentResolver; J)" : "WRITE_CONTACTS", "Landroid/provider/Contacts$Settings;-setSetting-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS", "Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-updateAdnRecordsInEfByIndex-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS", "Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-updateAdnRecordsInEfBySearch-(I Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "WRITE_CONTACTS", "Landroid/provider/CallLog$Calls;-removeExpiredEntries-(Landroid/content/Context;)" : "WRITE_CONTACTS", "Landroid/pim/vcard/VCardEntryCommitter;-onEntryCreated-(Landroid/pim/vcard/VCardEntry;)" : "WRITE_CONTACTS", "Landroid/pim/vcard/VCardEntryHandler;-onEntryCreated-(Landroid/pim/vcard/VCardEntry;)" : "WRITE_CONTACTS", "Landroid/pim/vcard/VCardEntry;-pushIntoContentResolver-(Landroid/content/ContentResolver;)" : "WRITE_CONTACTS", "Landroid/content/Intent;-ACTION_NEW_OUTGOING_CALL-Ljava/lang/String;" : "PROCESS_OUTGOING_CALLS", "Landroid/app/StatusBarManager;-collapse-()" : "EXPAND_STATUS_BAR", "Landroid/app/StatusBarManager;-expand-()" : "EXPAND_STATUS_BAR", "Landroid/app/StatusBarManager;-toggle-()" : "EXPAND_STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-activate-()" : "EXPAND_STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-deactivate-()" : "EXPAND_STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-toggle-()" : "EXPAND_STATUS_BAR", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-answerRingingCall-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-cancelMissedCallsNotification-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableApnType-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-disableDataConnectivity-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableApnType-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-enableDataConnectivity-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-handlePinMmi-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-setRadio-(B)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-silenceRinger-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-supplyPin-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephony$Stub$Proxy;-toggleRadioOnOff-()" : "MODIFY_PHONE_STATE", "Landroid/net/MobileDataStateTracker;-reconnect-()" : "MODIFY_PHONE_STATE", "Landroid/net/MobileDataStateTracker;-setRadio-(B)" : "MODIFY_PHONE_STATE", "Landroid/net/MobileDataStateTracker;-teardown-()" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCallForwardingChanged-(B)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCallState-(I Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyCellLocation-(Landroid/os/Bundle;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataActivity-(I)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataConnection-(I B Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Ljava/lang/String; I)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyDataConnectionFailed-(Ljava/lang/String;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyMessageWaitingChanged-(B)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifyServiceState-(Landroid/telephony/ServiceState;)" : "MODIFY_PHONE_STATE", "Lcom/android/internal/telephony/ITelephonyRegistry$Stub$Proxy;-notifySignalStrength-(Landroid/telephony/SignalStrength;)" : "MODIFY_PHONE_STATE", "Landroid/os/IMountService$Stub$Proxy;-formatMedi-()" : "MOUNT_FORMAT_FILESYSTEMS", "Landroid/os/storage/IMountService$Stub$Proxy;-formatVolume-(Ljava/lang/String;)" : "MOUNT_FORMAT_FILESYSTEMS", "Landroid/net/Downloads$DownloadBase;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ByUri;-getCurrentOtaDownloads-(Landroid/content/Context; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ByUri;-getProgressCursor-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ByUri;-getStatus-(Landroid/content/Context; Ljava/lang/String; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ByUri;-removeAllDownloadsByPackage-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ByUri;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-deleteDownload-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-getMimeTypeForId-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-getStatus-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-openDownload-(Landroid/content/Context; J Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-openDownloadStream-(Landroid/content/Context; J)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/net/Downloads$ById;-startDownloadByUri-(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; B I B B Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "ACCESS_DOWNLOAD_MANAGER", "Landroid/view/IWindowManager$Stub$Proxy;-getDPadKeycodeState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getDPadScancodeState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getKeycodeState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getKeycodeStateForDevice-(I I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getScancodeState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getScancodeStateForDevice-(I I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getSwitchState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getSwitchStateForDevice-(I I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getTrackballKeycodeState-(I)" : "READ_INPUT_STATE", "Landroid/view/IWindowManager$Stub$Proxy;-getTrackballScancodeState-(I)" : "READ_INPUT_STATE", "Landroid/app/ContextImpl$ApplicationContentResolver;-getCurrentSync-()" : "READ_SYNC_STATS", "Landroid/app/ContextImpl$ApplicationContentResolver;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/app/ContextImpl$ApplicationContentResolver;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/app/ContextImpl$ApplicationContentResolver;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentService;-getCurrentSync-()" : "READ_SYNC_STATS", "Landroid/content/ContentService;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentService;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentService;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentResolver;-getCurrentSync-()" : "READ_SYNC_STATS", "Landroid/content/ContentResolver;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentResolver;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/ContentResolver;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/IContentService$Stub$Proxy;-getCurrentSync-()" : "READ_SYNC_STATS", "Landroid/content/IContentService$Stub$Proxy;-getSyncStatus-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/IContentService$Stub$Proxy;-isSyncActive-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/content/IContentService$Stub$Proxy;-isSyncPending-(Landroid/accounts/Account; Ljava/lang/String;)" : "READ_SYNC_STATS", "Landroid/app/AlarmManager;-setTime-(J)" : "SET_TIME", "Landroid/app/AlarmManager;-setTimeZone-(Ljava/lang/String;)" : "SET_TIME", "Landroid/app/AlarmManager;-setTime-(J)" : "SET_TIME", "Landroid/app/IAlarmManager$Stub$Proxy;-setTime-(J)" : "SET_TIME", "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-setWimaxEnable-()" : "CHANGE_WIMAX_STATE", "Landroid/os/IMountService$Stub$Proxy;-mountMedi-()" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/IMountService$Stub$Proxy;-unmountMedi-()" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/IMountService$Stub$Proxy;-getStorageUsers-(Ljava/lang/String;)" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/IMountService$Stub$Proxy;-mountVolume-(Ljava/lang/String;)" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/IMountService$Stub$Proxy;-setUsbMassStorageEnabled-(B)" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/IMountService$Stub$Proxy;-unmountVolume-(Ljava/lang/String; B)" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/StorageManager;-disableUsbMassStorage-()" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/os/storage/StorageManager;-enableUsbMassStorage-()" : "MOUNT_UNMOUNT_FILESYSTEMS", "Landroid/app/ContextImpl$ApplicationPackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE", "Landroid/app/ContextImpl$ApplicationPackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE", "Landroid/content/pm/PackageManager;-movePackage-(Ljava/lang/String; LIPackageMoveObserver; I)" : "MOVE_PACKAGE", "Landroid/content/pm/IPackageManager$Stub$Proxy;-movePackage-(Ljava/lang/String; Landroid/content/pm/IPackageMoveObserver; I)" : "MOVE_PACKAGE", "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-getConnectionInf-()" : "ACCESS_WIMAX_STATE", "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-getWimaxStat-()" : "ACCESS_WIMAX_STATE", "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-isBackoffStat-()" : "ACCESS_WIMAX_STATE", "Lcom/htc/net/wimax/WimaxController$Stub$Proxy;-isWimaxEnable-()" : "ACCESS_WIMAX_STATE", "Landroid/net/sip/SipAudioCall;-startAudio-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getConfiguredNetworks-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getConnectionInfo-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getDhcpInfo-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getNumAllowedChannels-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getScanResults-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getValidChannelCounts-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getWifiApEnabledState-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-getWifiEnabledState-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/IWifiManager$Stub$Proxy;-isMulticastEnabled-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getConfiguredNetworks-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getConnectionInfo-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getDhcpInfo-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getNumAllowedChannels-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getScanResults-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getValidChannelCounts-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getWifiApState-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-getWifiState-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-isMulticastEnabled-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-isWifiApEnabled-()" : "ACCESS_WIFI_STATE", "Landroid/net/wifi/WifiManager;-isWifiEnabled-()" : "ACCESS_WIFI_STATE", "Landroid/webkit/WebIconDatabase;-bulkRequestIconForPageUrl-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-BOOKMARKS_URI-Landroid/net/Uri;" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-SEARCHES_URI-Landroid/net/Uri;" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-canClearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getAllBookmarks-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getAllVisitedUrls-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-requestAllIcons-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase/IconListener;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-canClearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-clearHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-deleteFromHistory-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-deleteHistoryTimeFrame-(Landroid/content/ContentResolver; J J)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-deleteHistoryWhere-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getAllBookmarks-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getAllVisitedUrls-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getVisitedHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-getVisitedLike-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-requestAllIcons-(Landroid/content/ContentResolver; Ljava/lang/String; Landroid/webkit/WebIconDatabase$IconListener;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "READ_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "READ_HISTORY_BOOKMARKS", "Landroid/os/storage/IMountService$Stub$Proxy;-destroySecureContainer-(Ljava/lang/String; B)" : "ASEC_DESTROY", "Landroid/net/ThrottleManager;-getByteCount-(Ljava/lang/String; I I I)" : "ACCESS_NETWORK_STATE", "Landroid/net/ThrottleManager;-getCliffLevel-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE", "Landroid/net/ThrottleManager;-getCliffThreshold-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE", "Landroid/net/ThrottleManager;-getHelpUri-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ThrottleManager;-getPeriodStartTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/ThrottleManager;-getResetTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/NetworkInfo;-isConnectedOrConnecting-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getDnsForwarders-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceRxCounter-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceRxThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceTxCounter-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getInterfaceTxThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-getIpForwardingEnabled-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-isTetheringStarted-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-isUsbRNDISStarted-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-listInterfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-listTetheredInterfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-listTtys-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getActiveNetworkInfo-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getAllNetworkInfo-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getLastTetherError-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getMobileDataEnabled-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getNetworkInfo-(I)" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getNetworkPreference-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableUsbRegexs-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getTetherableWifiRegexs-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getTetheredIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-getTetheringErroredIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-isTetheringSupported-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-startUsingNetworkFeature-(I Ljava/lang/String; Landroid/os/IBinder;)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getByteCount-(Ljava/lang/String; I I I)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getCliffLevel-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getCliffThreshold-(Ljava/lang/String; I)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getHelpUri-()" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getPeriodStartTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getResetTime-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/IThrottleManager$Stub$Proxy;-getThrottle-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getActiveNetworkInfo-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getAllNetworkInfo-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getLastTetherError-(Ljava/lang/String;)" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getMobileDataEnabled-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getNetworkInfo-(I)" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getNetworkPreference-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getTetherableIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getTetherableUsbRegexs-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getTetherableWifiRegexs-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getTetheredIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-getTetheringErroredIfaces-()" : "ACCESS_NETWORK_STATE", "Landroid/net/ConnectivityManager;-isTetheringSupported-()" : "ACCESS_NETWORK_STATE", "Landroid/net/http/RequestQueue;-enablePlatformNotifications-()" : "ACCESS_NETWORK_STATE", "Landroid/net/http/RequestQueue;-setProxyConfig-()" : "ACCESS_NETWORK_STATE", "Landroid/app/IActivityManager$Stub$Proxy;-getRecentTasks-(I I)" : "GET_TASKS", "Landroid/app/IActivityManager$Stub$Proxy;-getTasks-(I I Landroid/app/IThumbnailReceiver;)" : "GET_TASKS", "Landroid/app/ActivityManagerNative;-getRecentTasks-(I I)" : "GET_TASKS", "Landroid/app/ActivityManagerNative;-getRunningTasks-(I)" : "GET_TASKS", "Landroid/app/ActivityManager;-getRecentTasks-(I I)" : "GET_TASKS", "Landroid/app/ActivityManager;-getRunningTasks-(I)" : "GET_TASKS", "Landroid/app/ActivityManager;-getRecentTasks-(I I)" : "GET_TASKS", "Landroid/app/ActivityManager;-getRunningTasks-(I)" : "GET_TASKS", "Landroid/view/View/OnSystemUiVisibilityChangeListener;-onSystemUiVisibilityChange-(I)" : "STATUS_BAR", "Landroid/view/View;-STATUS_BAR_HIDDEN-I" : "STATUS_BAR", "Landroid/view/View;-STATUS_BAR_VISIBLE-I" : "STATUS_BAR", "Landroid/app/StatusBarManager;-addIcon-(Ljava/lang/String; I I)" : "STATUS_BAR", "Landroid/app/StatusBarManager;-disable-(I)" : "STATUS_BAR", "Landroid/app/StatusBarManager;-removeIcon-(Landroid/os/IBinder;)" : "STATUS_BAR", "Landroid/app/StatusBarManager;-updateIcon-(Landroid/os/IBinder; Ljava/lang/String; I I)" : "STATUS_BAR", "Landroid/view/WindowManager/LayoutParams;-TYPE_STATUS_BAR-I" : "STATUS_BAR", "Landroid/view/WindowManager/LayoutParams;-TYPE_STATUS_BAR_PANEL-I" : "STATUS_BAR", "Landroid/view/WindowManager/LayoutParams;-systemUiVisibility-I" : "STATUS_BAR", "Landroid/view/WindowManager/LayoutParams;-type-I" : "STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-addIcon-(Ljava/lang/String; Ljava/lang/String; I I)" : "STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-disable-(I Landroid/os/IBinder; Ljava/lang/String;)" : "STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-removeIcon-(Landroid/os/IBinder;)" : "STATUS_BAR", "Landroid/app/IStatusBar$Stub$Proxy;-updateIcon-(Landroid/os/IBinder; Ljava/lang/String; Ljava/lang/String; I I)" : "STATUS_BAR", "Landroid/app/IActivityManager$Stub$Proxy;-shutdown-(I)" : "SHUTDOWN", "Landroid/os/IMountService$Stub$Proxy;-shutdow-()" : "SHUTDOWN", "Landroid/os/storage/IMountService$Stub$Proxy;-shutdown-(Landroid/os/storage/IMountShutdownObserver;)" : "SHUTDOWN", "Landroid/os/INetworkManagementService$Stub$Proxy;-shutdown-()" : "SHUTDOWN", "Landroid/os/DropBoxManager;-ACTION_DROPBOX_ENTRY_ADDED-Ljava/lang/String;" : "READ_LOGS", "Landroid/os/DropBoxManager;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS", "Landroid/os/DropBoxManager;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS", "Lcom/android/internal/os/IDropBoxManagerService$Stub$Proxy;-getNextEntry-(Ljava/lang/String; J)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-(Ljava/lang/String;)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-([Ljava/lang/String;)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-([Ljava/lang/String; [Ljava/lang/String;)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-([Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-(Ljava/lang/String; [Ljava/lang/String;)" : "READ_LOGS", "Ljava/lang/Runtime;-exec-(Ljava/lang/String; [Ljava/lang/String; Ljava/io/File;)" : "READ_LOGS", "Landroid/os/Process;-BLUETOOTH_GID-I" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-ACTION_PLAYING_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getConnectedDevices-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-isA2dpPlaying-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getConnectedSinks-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getNonDisconnectedSinks-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothA2dp;-isSinkConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/media/AudioManager;-ROUTE_BLUETOOTH-I" : "BLUETOOTH", "Landroid/media/AudioManager;-ROUTE_BLUETOOTH_A2DP-I" : "BLUETOOTH", "Landroid/media/AudioManager;-ROUTE_BLUETOOTH_SCO-I" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getConnectedSinks-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getNonDisconnectedSinks-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothSocket;-connect-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothPbap;-getClient-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothPbap;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothPbap;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/provider/Settings/System;-AIRPLANE_MODE_RADIOS-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings/System;-BLUETOOTH_DISCOVERABILITY-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings/System;-BLUETOOTH_DISCOVERABILITY_TIMEOUT-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings/System;-BLUETOOTH_ON-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings/System;-RADIO_BLUETOOTH-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings/System;-VOLUME_BLUETOOTH_SCO-Ljava/lang/String;" : "BLUETOOTH", "Landroid/provider/Settings;-ACTION_BLUETOOTH_SETTINGS-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-addRfcommServiceRecord-(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-fetchRemoteUuids-(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getAddress-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getBluetoothState-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getBondState-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getDiscoverableTimeout-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getName-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteClass-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteName-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteServiceChannel-(Ljava/lang/String; Landroid/os/ParcelUuid;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getRemoteUuids-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getScanMode-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-getTrustState-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-isDiscovering-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-isEnabled-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-listBonds-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetooth$Stub$Proxy;-removeServiceRecord-(I)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_DISCOVERY_FINISHED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_DISCOVERY_STARTED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_LOCAL_NAME_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_REQUEST_DISCOVERABLE-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_REQUEST_ENABLE-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_SCAN_MODE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-ACTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-cancelDiscovery-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-disable-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-enable-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getAddress-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getBondedDevices-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getName-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getScanMode-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-isDiscovering-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-isEnabled-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-listenUsingInsecureRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-listenUsingRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-setName-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-startDiscovery-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getAddress-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getBondedDevices-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getDiscoverableTimeout-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getName-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getScanMode-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-isDiscovering-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-isEnabled-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAdapter;-listenUsingRfcommWithServiceRecord-(Ljava/lang/String; Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothProfile;-getConnectedDevices-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothProfile;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothProfile;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-ACTION_AUDIO_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-ACTION_CONNECTION_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-ACTION_VENDOR_SPECIFIC_HEADSET_EVENT-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getConnectedDevices-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getConnectionState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getDevicesMatchingConnectionStates-([I)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-isAudioConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-startVoiceRecognition-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-stopVoiceRecognition-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getBatteryUsageHint-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getCurrentHeadset-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-startVoiceRecognition-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothHeadset;-stopVoiceRecognition-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getBatteryUsageHint-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getCurrentHeadset-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-startVoiceRecognition-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-stopVoiceRecognition-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_CONNECTED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_DISCONNECTED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_ACL_DISCONNECT_REQUESTED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_BOND_STATE_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_CLASS_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_FOUND-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-ACTION_NAME_CHANGED-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-createInsecureRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-createRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getBluetoothClass-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getBondState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getName-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-createRfcommSocketToServiceRecord-(Ljava/util/UUID;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-fetchUuidsWithSdp-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getBondState-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getName-()" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getServiceChannel-(Landroid/os/ParcelUuid;)" : "BLUETOOTH", "Landroid/bluetooth/BluetoothDevice;-getUuids-()" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-<init>-(Landroid/content/Context; Landroid/server/BluetoothService;)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-addAudioSink-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-getConnectedSinks-()" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-getNonDisconnectedSinks-()" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-getSinkPriority-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-getSinkState-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-isSinkDevice-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-lookupSinksMatchingStates-([I)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-onConnectSinkResult-(Ljava/lang/String; B)" : "BLUETOOTH", "Landroid/server/BluetoothA2dpService;-onSinkPropertyChanged-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "BLUETOOTH", "Landroid/provider/Settings/Secure;-BLUETOOTH_ON-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-getClient-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-getState-()" : "BLUETOOTH", "Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-isConnected-(Landroid/bluetooth/BluetoothDevice;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-addRemoteDeviceProperties-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-addRfcommServiceRecord-(Ljava/lang/String; Landroid/os/ParcelUuid; I Landroid/os/IBinder;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-fetchRemoteUuids-(Ljava/lang/String; Landroid/os/ParcelUuid; Landroid/bluetooth/IBluetoothCallback;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getAddress-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getAddressFromObjectPath-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getAllProperties-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getBluetoothState-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getBondState-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getDiscoverableTimeout-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getName-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getObjectPathFromAddress-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getProperty-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getPropertyInternal-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getRemoteClass-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getRemoteName-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getRemoteServiceChannel-(Ljava/lang/String; Landroid/os/ParcelUuid;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getRemoteUuids-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-getScanMode-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-getTrustState-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-isDiscovering-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-isEnabled-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-listBonds-()" : "BLUETOOTH", "Landroid/server/BluetoothService;-removeServiceRecord-(I)" : "BLUETOOTH", "Landroid/server/BluetoothService;-sendUuidIntent-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-setLinkTimeout-(Ljava/lang/String; I)" : "BLUETOOTH", "Landroid/server/BluetoothService;-setPropertyBoolean-(Ljava/lang/String; B)" : "BLUETOOTH", "Landroid/server/BluetoothService;-setPropertyInteger-(Ljava/lang/String; I)" : "BLUETOOTH", "Landroid/server/BluetoothService;-setPropertyString-(Ljava/lang/String; Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-updateDeviceServiceChannelCache-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/server/BluetoothService;-updateRemoteDevicePropertiesCache-(Ljava/lang/String;)" : "BLUETOOTH", "Landroid/content/pm/PackageManager;-FEATURE_BLUETOOTH-Ljava/lang/String;" : "BLUETOOTH", "Landroid/bluetooth/BluetoothAssignedNumbers;-BLUETOOTH_SIG-I" : "BLUETOOTH", "Landroid/app/ActivityManagerNative;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/app/ContextImpl$ApplicationPackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/app/ContextImpl$ApplicationPackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/app/ActivityManager;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/app/IActivityManager$Stub$Proxy;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/content/pm/PackageManager;-clearApplicationUserData-(Ljava/lang/String; LIPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/content/pm/IPackageManager$Stub$Proxy;-clearApplicationUserData-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "CLEAR_APP_USER_DATA", "Landroid/provider/Telephony$Sms;-addMessageToUri-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B J)" : "WRITE_SMS", "Landroid/provider/Telephony$Sms;-addMessageToUri-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B B)" : "WRITE_SMS", "Landroid/provider/Telephony$Sms;-moveMessageToFolder-(Landroid/content/Context; Landroid/net/Uri; I I)" : "WRITE_SMS", "Landroid/provider/Telephony$Sms$Outbox;-addMessage-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/Long; B J)" : "WRITE_SMS", "Landroid/provider/Telephony$Sms$Draft;-saveMessage-(Landroid/content/ContentResolver; Landroid/net/Uri; Ljava/lang/String;)" : "WRITE_SMS", "Landroid/app/IActivityManager$Stub$Proxy;-setProcessForeground-(Landroid/os/IBinder; I B)" : "SET_PROCESS_LIMIT", "Landroid/app/IActivityManager$Stub$Proxy;-setProcessLimit-(I)" : "SET_PROCESS_LIMIT", "Landroid/os/PowerManager;-goToSleep-(J)" : "DEVICE_POWER", "Landroid/os/PowerManager;-setBacklightBrightness-(I)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-clearUserActivityTimeout-(J J)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-goToSleep-(J)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-goToSleepWithReason-(J I)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-preventScreenOn-(B)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-setAttentionLight-(B I)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-setBacklightBrightness-(I)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-setPokeLock-(I Landroid/os/IBinder; Ljava/lang/String;)" : "DEVICE_POWER", "Landroid/os/IPowerManager$Stub$Proxy;-userActivityWithForce-(J B B)" : "DEVICE_POWER", "Landroid/app/ExpandableListActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/accounts/GrantCredentialsPermissionActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/app/Activity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/app/ListActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/app/AliasActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/accounts/AccountAuthenticatorActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/app/IActivityManager$Stub$Proxy;-setPersistent-(Landroid/os/IBinder; B)" : "PERSISTENT_ACTIVITY", "Landroid/app/TabActivity;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/app/ActivityGroup;-setPersistent-(B)" : "PERSISTENT_ACTIVITY", "Landroid/view/IWindowManager$Stub$Proxy;-addAppToken-(I Landroid/view/IApplicationToken; I I B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-addWindowToken-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-executeAppTransition-()" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-moveAppToken-(I Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-moveAppTokensToBottom-(Ljava/util/List;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-moveAppTokensToTop-(Ljava/util/List;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-pauseKeyDispatching-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-prepareAppTransition-(I)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-removeAppToken-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-removeWindowToken-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-resumeKeyDispatching-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setAppGroupId-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setAppOrientation-(Landroid/view/IApplicationToken; I)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setAppStartingWindow-(Landroid/os/IBinder; Ljava/lang/String; I Ljava/lang/CharSequence; I I Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setAppVisibility-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setAppWillBeHidden-(Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setEventDispatching-(B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setFocusedApp-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-setNewConfiguration-(Landroid/content/res/Configuration;)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-startAppFreezingScreen-(Landroid/os/IBinder; I)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-stopAppFreezingScreen-(Landroid/os/IBinder; B)" : "MANAGE_APP_TOKENS", "Landroid/view/IWindowManager$Stub$Proxy;-updateOrientationFromAppTokens-(Landroid/content/res/Configuration; Landroid/os/IBinder;)" : "MANAGE_APP_TOKENS", "Landroid/provider/Browser;-BOOKMARKS_URI-Landroid/net/Uri;" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-SEARCHES_URI-Landroid/net/Uri;" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-addSearchUrl-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-clearHistory-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-clearSearches-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-deleteFromHistory-(Landroid/content/ContentResolver; Ljava/lang/String;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-deleteHistoryTimeFrame-(Landroid/content/ContentResolver; J J)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-truncateHistory-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-updateVisitedHistory-(Landroid/content/ContentResolver; Ljava/lang/String; B)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/provider/Browser;-clearSearches-(Landroid/content/ContentResolver;)" : "WRITE_HISTORY_BOOKMARKS", "Landroid/app/IActivityManager$Stub$Proxy;-unhandledBack-(I)" : "FORCE_BACK", "Landroid/net/IConnectivityManager$Stub$Proxy;-requestRouteToHost-(I I)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-setMobileDataEnabled-(B)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-setNetworkPreference-(I)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-setRadio-(I B)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-setRadios-(B)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-stopUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-tether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/IConnectivityManager$Stub$Proxy;-untether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-requestRouteToHost-(I I)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-setMobileDataEnabled-(B)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-setNetworkPreference-(I)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-setRadio-(I B)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-setRadios-(B)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-startUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-stopUsingNetworkFeature-(I Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-tether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/net/ConnectivityManager;-untether-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-attachPppd-(Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-detachPppd-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-disableNat-(Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-enableNat-(Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-setAccessPoint-(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-setInterfaceThrottle-(Ljava/lang/String; I I)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-setIpForwardingEnabled-(B)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-startAccessPoint-(Landroid/net/wifi/WifiConfiguration; Ljava/lang/String; Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-startUsbRNDIS-()" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-stopAccessPoint-()" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-stopTethering-()" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-stopUsbRNDIS-()" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-tetherInterface-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-unregisterObserver-(Landroid/net/INetworkManagementEventObserver;)" : "CHANGE_NETWORK_STATE", "Landroid/os/INetworkManagementService$Stub$Proxy;-untetherInterface-(Ljava/lang/String;)" : "CHANGE_NETWORK_STATE", "Landroid/app/ContextImpl$ApplicationContentResolver;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS", "Landroid/app/ContextImpl$ApplicationContentResolver;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentService;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentService;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentService;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentService;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentService;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentResolver;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentResolver;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentResolver;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentResolver;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/ContentResolver;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-addPeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle; J)" : "WRITE_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-removePeriodicSync-(Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "WRITE_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-setIsSyncable-(Landroid/accounts/Account; Ljava/lang/String; I)" : "WRITE_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-setMasterSyncAutomatically-(B)" : "WRITE_SYNC_SETTINGS", "Landroid/content/IContentService$Stub$Proxy;-setSyncAutomatically-(Landroid/accounts/Account; Ljava/lang/String; B)" : "WRITE_SYNC_SETTINGS", "Landroid/accounts/AccountManager;-KEY_ACCOUNT_MANAGER_RESPONSE-Ljava/lang/String;" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-checkBinderPermission-()" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER", "Landroid/accounts/AbstractAccountAuthenticator$Transport;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-addAccount-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-confirmCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-editProperties-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAccountRemovalAllowed-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAuthToken-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-getAuthTokenLabel-(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-hasFeatures-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "ACCOUNT_MANAGER", "Landroid/accounts/IAccountAuthenticator$Stub$Proxy;-updateCredentials-(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)" : "ACCOUNT_MANAGER", "Landroid/view/IWindowManager$Stub$Proxy;-setAnimationScale-(I F)" : "SET_ANIMATION_SCALE", "Landroid/view/IWindowManager$Stub$Proxy;-setAnimationScales-([L;)" : "SET_ANIMATION_SCALE", "Landroid/accounts/AccountManager;-getAccounts-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAccountsByType-(Ljava/lang/String;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAccountsByTypeAndFeatures-(Ljava/lang/String; [Ljava/lang/String; [Landroid/accounts/AccountManagerCallback<android/accounts/Account[; Landroid/os/Handler;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-hasFeatures-(Landroid/accounts/Account; [Ljava/lang/String; Landroid/accounts/AccountManagerCallback<java/lang/Boolean>; Landroid/os/Handler;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-addOnAccountsUpdatedListener-(Landroid/accounts/OnAccountsUpdateListener; Landroid/os/Handler; B)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAccounts-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAccountsByType-(Ljava/lang/String;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAccountsByTypeAndFeatures-(Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-getAuthTokenByFeatures-(Ljava/lang/String; Ljava/lang/String; [L[Ljava/lang/Strin; Landroid/app/Activity; Landroid/os/Bundle; Landroid/os/Bundle; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager;-hasFeatures-(Landroid/accounts/Account; [L[Ljava/lang/Strin; Landroid/accounts/AccountManagerCallback; Landroid/os/Handler;)" : "GET_ACCOUNTS", "Landroid/content/ContentService;-<init>-(Landroid/content/Context; B)" : "GET_ACCOUNTS", "Landroid/content/ContentService;-main-(Landroid/content/Context; B)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;-doWork-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;-start-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager$AmsTask;-doWork-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManager$AmsTask;-start-()" : "GET_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-getAccounts-(Ljava/lang/String;)" : "GET_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-getAccountsByFeatures-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS", "Landroid/accounts/IAccountManager$Stub$Proxy;-hasFeatures-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManagerService;-checkReadAccountsPermission-()" : "GET_ACCOUNTS", "Landroid/accounts/AccountManagerService;-getAccounts-(Ljava/lang/String;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManagerService;-getAccountsByFeatures-(Landroid/accounts/IAccountManagerResponse; Ljava/lang/String; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS", "Landroid/accounts/AccountManagerService;-hasFeatures-(Landroid/accounts/IAccountManagerResponse; Landroid/accounts/Account; [L[Ljava/lang/Strin;)" : "GET_ACCOUNTS", "Landroid/telephony/gsm/SmsManager;-copyMessageToSim-([L; [L; I)" : "RECEIVE_SMS", "Landroid/telephony/gsm/SmsManager;-deleteMessageFromSim-(I)" : "RECEIVE_SMS", "Landroid/telephony/gsm/SmsManager;-getAllMessagesFromSim-()" : "RECEIVE_SMS", "Landroid/telephony/gsm/SmsManager;-updateMessageOnSim-(I I [L;)" : "RECEIVE_SMS", "Landroid/telephony/SmsManager;-copyMessageToIcc-([L; [L; I)" : "RECEIVE_SMS", "Landroid/telephony/SmsManager;-deleteMessageFromIcc-(I)" : "RECEIVE_SMS", "Landroid/telephony/SmsManager;-getAllMessagesFromIcc-()" : "RECEIVE_SMS", "Landroid/telephony/SmsManager;-updateMessageOnIcc-(I I [L;)" : "RECEIVE_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-copyMessageToIccEf-(I [B [B)" : "RECEIVE_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-getAllMessagesFromIccEf-()" : "RECEIVE_SMS", "Lcom/android/internal/telephony/ISms$Stub$Proxy;-updateMessageOnIccEf-(I I [B)" : "RECEIVE_SMS", "Landroid/app/IActivityManager$Stub$Proxy;-resumeAppSwitches-()" : "STOP_APP_SWITCHES", "Landroid/app/IActivityManager$Stub$Proxy;-stopAppSwitches-()" : "STOP_APP_SWITCHES", "Landroid/app/ContextImpl$ApplicationPackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; LIPackageDataObserver;)" : "DELETE_CACHE_FILES", "Landroid/app/ContextImpl$ApplicationPackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES", "Landroid/content/pm/PackageManager;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES", "Landroid/content/pm/IPackageManager$Stub$Proxy;-deleteApplicationCacheFiles-(Ljava/lang/String; Landroid/content/pm/IPackageDataObserver;)" : "DELETE_CACHE_FILES", "Landroid/os/Build/VERSION_CODES;-DONUT-I" : "WRITE_EXTERNAL_STORAGE", "Landroid/app/DownloadManager/Request;-setDestinationUri-(Landroid/net/Uri;)" : "WRITE_EXTERNAL_STORAGE", "Landroid/os/RecoverySystem;-installPackage-(Landroid/content/Context; Ljava/io/File;)" : "REBOOT", "Landroid/os/RecoverySystem;-rebootWipeUserData-(Landroid/content/Context;)" : "REBOOT", "Landroid/os/RecoverySystem;-bootCommand-(Landroid/content/Context; Ljava/lang/String;)" : "REBOOT", "Landroid/os/RecoverySystem;-installPackage-(Landroid/content/Context; Ljava/io/File;)" : "REBOOT", "Landroid/os/RecoverySystem;-rebootWipeUserData-(Landroid/content/Context;)" : "REBOOT", "Landroid/content/Intent;-IntentResolution-Ljava/lang/String;" : "REBOOT", "Landroid/content/Intent;-ACTION_REBOOT-Ljava/lang/String;" : "REBOOT", "Landroid/os/PowerManager;-reboot-(Ljava/lang/String;)" : "REBOOT", "Landroid/os/PowerManager;-reboot-(Ljava/lang/String;)" : "REBOOT", "Landroid/os/IPowerManager$Stub$Proxy;-crash-(Ljava/lang/String;)" : "REBOOT", "Landroid/os/IPowerManager$Stub$Proxy;-reboot-(Ljava/lang/String;)" : "REBOOT", "Landroid/app/ContextImpl$ApplicationPackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES", "Landroid/app/ContextImpl$ApplicationPackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES", "Landroid/content/pm/PackageManager;-installPackage-(Landroid/net/Uri; LIPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES", "Landroid/content/pm/IPackageManager$Stub$Proxy;-installPackage-(Landroid/net/Uri; Landroid/content/pm/IPackageInstallObserver; I Ljava/lang/String;)" : "INSTALL_PACKAGES", "Landroid/app/IActivityManager$Stub$Proxy;-setDebugApp-(Ljava/lang/String; B B)" : "SET_DEBUG_APP", "Landroid/location/ILocationManager$Stub$Proxy;-reportLocation-(Landroid/location/Location; B)" : "INSTALL_LOCATION_PROVIDER", "Landroid/app/WallpaperManager;-suggestDesiredDimensions-(I I)" : "SET_WALLPAPER_HINTS", "Landroid/app/IWallpaperManager$Stub$Proxy;-setDimensionHints-(I I)" : "SET_WALLPAPER_HINTS", "Landroid/app/ContextImpl$ApplicationContentResolver;-openFileDescriptor-(Landroid/net/Uri; Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/app/ContextImpl$ApplicationContentResolver;-openInputStream-(Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/app/ContextImpl$ApplicationContentResolver;-openOutputStream-(Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/app/ContextImpl$ApplicationContentResolver;-query-(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CONTACTS", "Lcom/android/internal/telephony/IccPhoneBookInterfaceManager$Stub$Proxy;-getAdnRecordsInEf-(I)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-addToGroup-(Landroid/content/ContentResolver; J Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-addToMyContactsGroup-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-createPersonInMyContactsGroup-(Landroid/content/ContentResolver; Landroid/content/ContentValues;)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-loadContactPhoto-(Landroid/content/Context; Landroid/net/Uri; I Landroid/graphics/BitmapFactory$Options;)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-markAsContacted-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-openContactPhotoInputStream-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-queryGroups-(Landroid/content/ContentResolver; J)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-setPhotoData-(Landroid/content/ContentResolver; Landroid/net/Uri; [L;)" : "READ_CONTACTS", "Landroid/provider/Contacts$People;-tryGetMyContactsGroupId-(Landroid/content/ContentResolver;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$Data;-getContactLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$Contacts;-getLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$Contacts;-lookupContact-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$Contacts;-openContactPhotoInputStream-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer;-createOneEntry-()" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer;-createOneEntry-(Ljava/lang/reflect/Method;)" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer;-createOneEntryInternal-(Ljava/lang/String; Ljava/lang/reflect/Method;)" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer;-init-()" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer;-init-(Ljava/lang/String; [L[Ljava/lang/Strin;)" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer$OneEntryHandler;-onInit-(Landroid/content/Context;)" : "READ_CONTACTS", "Lcom/android/internal/telephony/CallerInfo;-getCallerId-(Landroid/content/Context; Ljava/lang/String;)" : "READ_CONTACTS", "Lcom/android/internal/telephony/CallerInfo;-getCallerInfo-(Landroid/content/Context; Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/provider/Contacts$Settings;-getSetting-(Landroid/content/ContentResolver; Ljava/lang/String; Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$RawContacts;-getContactLookupUri-(Landroid/content/ContentResolver; Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/provider/CallLog$Calls;-addCall-(Lcom/android/internal/telephony/CallerInfo; Landroid/content/Context; Ljava/lang/String; I I J I)" : "READ_CONTACTS", "Landroid/provider/CallLog$Calls;-getLastOutgoingCall-(Landroid/content/Context;)" : "READ_CONTACTS", "Lcom/android/internal/telephony/IIccPhoneBook$Stub$Proxy;-getAdnRecordsInEf-(I)" : "READ_CONTACTS", "Landroid/pim/vcard/VCardComposer$HandlerForOutputStream;-onInit-(Landroid/content/Context;)" : "READ_CONTACTS", "Landroid/provider/ContactsContract$CommonDataKinds$Phone;-CONTENT_URI-Landroid/net/Uri;" : "READ_CONTACTS", "Landroid/widget/QuickContactBadge;-assignContactFromEmail-(Ljava/lang/String; B)" : "READ_CONTACTS", "Landroid/widget/QuickContactBadge;-assignContactFromPhone-(Ljava/lang/String; B)" : "READ_CONTACTS", "Landroid/widget/QuickContactBadge;-trigger-(Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/content/ContentResolver;-openFileDescriptor-(Landroid/net/Uri; Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/content/ContentResolver;-openInputStream-(Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/content/ContentResolver;-openOutputStream-(Landroid/net/Uri;)" : "READ_CONTACTS", "Landroid/content/ContentResolver;-query-(Landroid/net/Uri; [L[Ljava/lang/Strin; Ljava/lang/String; [L[Ljava/lang/Strin; Ljava/lang/String;)" : "READ_CONTACTS", "Landroid/app/backup/IBackupManager$Stub$Proxy;-backupNow-()" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-beginRestoreSession-(Ljava/lang/String;)" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-clearBackupData-(Ljava/lang/String;)" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-dataChanged-(Ljava/lang/String;)" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-getCurrentTransport-()" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-isBackupEnabled-()" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-listAllTransports-()" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-selectBackupTransport-(Ljava/lang/String;)" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-setAutoRestore-(B)" : "BACKUP", "Landroid/app/backup/IBackupManager$Stub$Proxy;-setBackupEnabled-(B)" : "BACKUP", "Landroid/app/IActivityManager$Stub$Proxy;-bindBackupAgent-(Landroid/content/pm/ApplicationInfo; I)" : "BACKUP", "Landroid/app/backup/BackupManager;-beginRestoreSession-()" : "BACKUP", "Landroid/app/backup/BackupManager;-dataChanged-(Ljava/lang/String;)" : "BACKUP", "Landroid/app/backup/BackupManager;-requestRestore-(Landroid/app/backup/RestoreObserver;)" : "BACKUP", }
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from androguard.core import bytecode from androguard.core.bytecode import SV, SVs, object_to_str from androguard.core.bytecode import FormatClassToPython, FormatNameToPython, FormatDescriptorToPython import sys, re from collections import namedtuple from struct import pack, unpack, calcsize from androguard.core.androconf import CONF import logging log_andro = logging.getLogger("andro") #log_andro.setLevel(logging.DEBUG) ######################################################## DEX FORMAT ######################################################## DEX_FILE_MAGIC = 'dex\n035\x00' HEADER_NAMEDTUPLE = namedtuple( "HEADER_NAMEDTUPLE", "magic checksum signature file_size header_size endian_tag link_size link_off " \ "map_off string_ids_size string_ids_off type_ids_size type_ids_off proto_ids_size " \ "proto_ids_off field_ids_size field_ids_off method_ids_size method_ids_off "\ "class_defs_size class_defs_off data_size data_off" ) HEADER = [ '=QL20sLLLLLLLLLLLLLLLLLLLL', HEADER_NAMEDTUPLE ] MAP_ITEM_NAMEDTUPLE = namedtuple("MAP_ITEM_NAMEDTUPLE", "type unused size offset") MAP_ITEM = [ '=HHLL', MAP_ITEM_NAMEDTUPLE ] PROTO_ID_ITEM_NAMEDTUPLE = namedtuple("PROTO_ID_ITEM_NAMEDTUPLE", "shorty_idx return_type_idx parameters_off" ) PROTO_ID_ITEM = [ '=LLL', PROTO_ID_ITEM_NAMEDTUPLE ] METHOD_ID_ITEM_NAMEDTUPLE = namedtuple("METHOD_ID_ITEM_NAMEDTUPLE", "class_idx proto_idx name_idx" ) METHOD_ID_ITEM = [ '=HHL', METHOD_ID_ITEM_NAMEDTUPLE ] FIELD_ID_ITEM_NAMEDTUPLE = namedtuple("FIELD_ID_ITEM_NAMEDTUPLE", "class_idx type_idx name_idx") FIELD_ID_ITEM = [ '=HHL', FIELD_ID_ITEM_NAMEDTUPLE ] CLASS_DEF_ITEM_NAMEDTUPLE = namedtuple("CLASS_DEF_ITEM_NAMEDTUPLE", "class_idx access_flags superclass_idx interfaces_off source_file_idx annotations_off class_data_off static_values_off") CLASS_DEF_ITEM = [ '=LLLLLLLL', CLASS_DEF_ITEM_NAMEDTUPLE ] TRY_ITEM_NAMEDTUPLE = namedtuple("TRY_ITEM_NAMEDTUPLE", "start_addr insn_count handler_off" ) TRY_ITEM = [ '=LHH', TRY_ITEM_NAMEDTUPLE ] ANNOTATIONS_DIRECTORY_ITEM_NAMEDTUPLE = namedtuple("ANNOTATIONS_DIRECTORY_ITEM_NAMEDTUPLE", "class_annotations_off fields_size annotated_methods_size annotated_parameters_size") ANNOTATIONS_DIRECTORY_ITEM = [ '=LLLL', ANNOTATIONS_DIRECTORY_ITEM_NAMEDTUPLE ] TYPE_MAP_ITEM = { 0x0 : "TYPE_HEADER_ITEM", 0x1 : "TYPE_STRING_ID_ITEM", 0x2 : "TYPE_TYPE_ID_ITEM", 0x3 : "TYPE_PROTO_ID_ITEM", 0x4 : "TYPE_FIELD_ID_ITEM", 0x5 : "TYPE_METHOD_ID_ITEM", 0x6 : "TYPE_CLASS_DEF_ITEM", 0x1000 : "TYPE_MAP_LIST", 0x1001 : "TYPE_TYPE_LIST", 0x1002 : "TYPE_ANNOTATION_SET_REF_LIST", 0x1003 : "TYPE_ANNOTATION_SET_ITEM", 0x2000 : "TYPE_CLASS_DATA_ITEM", 0x2001 : "TYPE_CODE_ITEM", 0x2002 : "TYPE_STRING_DATA_ITEM", 0x2003 : "TYPE_DEBUG_INFO_ITEM", 0x2004 : "TYPE_ANNOTATION_ITEM", 0x2005 : "TYPE_ENCODED_ARRAY_ITEM", 0x2006 : "TYPE_ANNOTATIONS_DIRECTORY_ITEM", } ACCESS_FLAGS_METHODS = [ (0x1 , 'public'), (0x2 , 'private'), (0x4 , 'protected'), (0x8 , 'static'), (0x10 , 'final'), (0x20 , 'synchronized'), (0x40 , 'bridge'), (0x80 , 'varargs'), (0x100 , 'native'), (0x200 , 'interface'), (0x400 , 'abstract'), (0x800 , 'strict'), (0x1000 , 'synthetic'), (0x4000 , 'enum'), (0x8000 , 'unused'), (0x10000, 'constructors'), (0x20000, 'synchronized'), ] TYPE_DESCRIPTOR = { 'V': 'void', 'Z': 'boolean', 'B': 'byte', 'S': 'short', 'C': 'char', 'I': 'int', 'J': 'long', 'F': 'float', 'D': 'double', 'STR': 'String', 'StringBuilder': 'String' } def get_type(atype, size=None): ''' Retrieve the type of a descriptor (e.g : I) ''' if atype.startswith('java.lang'): atype = atype.replace('java.lang.', '') res = TYPE_DESCRIPTOR.get(atype.lstrip('java.lang')) if res is None: if atype[0] == 'L': res = atype[1:-1].replace('/', '.') elif atype[0] == '[': if size is None: res = '%s[]' % get_type(atype[1:]) else: res = '%s[%s]' % (get_type(atype[1:]), size) else: res = atype return res SPARSE_SWITCH_NAMEDTUPLE = namedtuple("SPARSE_SWITCH_NAMEDTUPLE", "ident size") SPARSE_SWITCH = [ '=HH', SPARSE_SWITCH_NAMEDTUPLE ] PACKED_SWITCH_NAMEDTUPLE = namedtuple("PACKED_SWITCH_NAMEDTUPLE", "ident size first_key") PACKED_SWITCH = [ '=HHL', PACKED_SWITCH_NAMEDTUPLE ] FILL_ARRAY_DATA_NAMEDTUPLE = namedtuple("FILL_ARRAY_DATA_NAMEDTUPLE", "ident element_width size") FILL_ARRAY_DATA = [ '=HHL', FILL_ARRAY_DATA_NAMEDTUPLE ] NORMAL_DVM_INS = 0 SPECIFIC_DVM_INS = 1 class FillArrayData : def __init__(self, buff) : self.format = SVs( FILL_ARRAY_DATA[0], FILL_ARRAY_DATA[1], buff[ 0 : calcsize(FILL_ARRAY_DATA[0]) ] ) general_format = self.format.get_value() self.data = buff[ calcsize(FILL_ARRAY_DATA[0]) : calcsize(FILL_ARRAY_DATA[0]) + (general_format.size * general_format.element_width ) ] def get_op_value(self) : return -1 def get_raw(self) : return self.format.get_value_buff() + self.data def get_data(self) : return self.data def get_output(self) : return self.get_operands() def get_operands(self) : return self.data def get_name(self) : return "fill-array-data-payload" def show_buff(self, pos) : buff = self.get_name() + " " for i in range(0, len(self.data)) : buff += "\\x%02x" % ord( self.data[i] ) return buff def show(self, pos) : print self.show_buff(pos), def get_length(self) : general_format = self.format.get_value() return ((general_format.size * general_format.element_width + 1) / 2 + 4) * 2 class SparseSwitch : def __init__(self, buff) : self.format = SVs( SPARSE_SWITCH[0], SPARSE_SWITCH[1], buff[ 0 : calcsize(SPARSE_SWITCH[0]) ] ) self.keys = [] self.targets = [] idx = calcsize(SPARSE_SWITCH[0]) for i in range(0, self.format.get_value().size) : self.keys.append( unpack('=L', buff[idx:idx+4])[0] ) idx += 4 for i in range(0, self.format.get_value().size) : self.targets.append( unpack('=L', buff[idx:idx+4])[0] ) idx += 4 def get_op_value(self) : return -1 # FIXME : return correct raw def get_raw(self) : return self.format.get_value_buff() + ''.join(pack("=L", i) for i in self.keys) + ''.join(pack("=L", i) for i in self.targets) def get_keys(self) : return self.keys def get_targets(self) : return self.targets def get_operands(self) : return [ self.keys, self.targets ] def get_output(self) : return self.get_operands() def get_name(self) : return "sparse-switch-payload" def show_buff(self, pos) : buff = self.get_name() + " " for i in range(0, len(self.keys)) : buff += "%x:%x " % (self.keys[i], self.targets[i]) return buff def show(self, pos) : print self.show_buff( pos ), def get_length(self) : return calcsize(SPARSE_SWITCH[0]) + (self.format.get_value().size * calcsize('<L')) * 2 class PackedSwitch : def __init__(self, buff) : self.format = SVs( PACKED_SWITCH[0], PACKED_SWITCH[1], buff[ 0 : calcsize(PACKED_SWITCH[0]) ] ) self.targets = [] idx = calcsize(PACKED_SWITCH[0]) max_size = min(self.format.get_value().size, len(buff) - idx - 8) for i in range(0, max_size) : self.targets.append( unpack('=L', buff[idx:idx+4])[0] ) idx += 4 def get_op_value(self) : return -1 def get_raw(self) : return self.format.get_value_buff() + ''.join(pack("=L", i) for i in self.targets) def get_operands(self) : return [ self.format.get_value().first_key, self.targets ] def get_output(self) : return self.get_operands() def get_targets(self) : return self.targets def get_name(self) : return "packed-switch-payload" def show_buff(self, pos) : buff = self.get_name() + " " buff += "%x:" % self.format.get_value().first_key for i in self.targets : buff += " %x" % i return buff def show(self, pos) : print self.show_buff( pos ), def get_length(self) : return calcsize(PACKED_SWITCH[0]) + (self.format.get_value().size * calcsize('<L')) MATH_DVM_OPCODES = { "add." : '+', "div." : '/', "mul." : '*', "or." : '|', "sub." : '-', "and." : '&', "xor." : '^', "shl." : "<<", "shr." : ">>", } INVOKE_DVM_OPCODES = [ "invoke." ] FIELD_READ_DVM_OPCODES = [ ".get" ] FIELD_WRITE_DVM_OPCODES = [ ".put" ] BREAK_DVM_OPCODES = [ "invoke.", "move.", ".put", "if." ] BRANCH_DVM_OPCODES = [ "if.", "goto", "goto.", "return", "return.", "packed.", "sparse." ] def clean_name_instruction( instruction ) : op_value = instruction.get_op_value() # goto range if op_value >= 0x28 and op_value <= 0x2a : return "goto" return instruction.get_name() def static_operand_instruction( instruction ) : buff = "" if isinstance(instruction, Instruction) : # get instructions without registers for val in instruction.get_literals() : buff += "%s" % val op_value = instruction.get_op_value() if op_value == 0x1a or op_value == 0x1b : buff += instruction.get_string() return buff def dot_buff(ins, idx) : if ins.get_op_value() == 0x1a or ins.get_op_value() == 0x1b : return ins.show_buff(idx).replace('"', '\\"') return ins.show_buff(idx) def readuleb128(buff) : result = ord( buff.read(1) ) if result > 0x7f : cur = ord( buff.read(1) ) result = (result & 0x7f) | ((cur & 0x7f) << 7) if cur > 0x7f : cur = ord( buff.read(1) ) result |= (cur & 0x7f) << 14 if cur > 0x7f : cur = ord( buff.read(1) ) result |= (cur & 0x7f) << 21 if cur > 0x7f : cur = ord( buff.read(1) ) result |= cur << 28 return result def readsleb128(buff) : result = unpack( '=b', buff.read(1) )[0] if result <= 0x7f : result = (result << 25) if result > 0x7fffffff : result = (0x7fffffff & result) - 0x80000000 result = result >> 25 else : cur = unpack( '=b', buff.read(1) )[0] result = (result & 0x7f) | ((cur & 0x7f) << 7) if cur <= 0x7f : result = (result << 18) >> 18 else : cur = unpack( '=b', buff.read(1) )[0] result |= (cur & 0x7f) << 14 if cur <= 0x7f : result = (result << 11) >> 11 else : cur = unpack( '=b', buff.read(1) )[0] result |= (cur & 0x7f) << 21 if cur <= 0x7f : result = (result << 4) >> 4 else : cur = unpack( '=b', buff.read(1) )[0] result |= cur << 28 return result def writeuleb128(value) : remaining = value >> 7 buff = "" while remaining > 0 : buff += pack( "=B", ((value & 0x7f) | 0x80) ) value = remaining remaining >>= 7 buff += pack( "=B", value & 0x7f ) return buff def writesleb128(value) : remaining = value >> 7 hasMore = True end = 0 buff = "" if (value & (-sys.maxint - 1)) == 0 : end = 0 else : end = -1 while hasMore : hasMore = (remaining != end) or ((remaining & 1) != ((value >> 6) & 1)) tmp = 0 if hasMore : tmp = 0x80 buff += pack( "=B", (value & 0x7f) | (tmp) ) value = remaining remaining >>= 7 return buff def determineNext(i, end, m) : op_value = i.get_op_value() # return* if op_value >= 0x0e and op_value <= 0x11 : return [ -1 ] # goto elif op_value >= 0x28 and op_value <= 0x2a : off = i.get_ref_off() * 2 return [ off + end ] # if elif op_value >= 0x32 and op_value <= 0x3d : off = i.get_ref_off() * 2 return [ end + i.get_length(), off + (end) ] # sparse/packed elif op_value == 0x2b or op_value == 0x2c : x = [] x.append( end + i.get_length() ) code = m.get_code().get_bc() off = i.get_ref_off() * 2 data = code.get_ins_off( off + end ) if data != None : for target in data.get_targets() : x.append( target*2 + end ) return x return [] def determineException(vm, m) : # no exceptions ! if m.get_code().get_tries_size() <= 0 : return [] h_off = {} handler_catch_list = m.get_code().get_handlers() for try_item in m.get_code().get_tries() : # print m.get_name(), try_item, (value.start_addr * 2) + (value.insn_count * 2)# - 1m.get_code().get_bc().get_next_addr( value.start_addr * 2, value.insn_count ) h_off[ try_item.get_handler_off() + handler_catch_list.get_offset() ] = [ try_item ] #print m.get_name(), "\t HANDLER_CATCH_LIST SIZE", handler_catch_list.size, handler_catch_list.get_offset() for handler_catch in handler_catch_list.get_list() : # print m.get_name(), "\t\t HANDLER_CATCH SIZE ", handler_catch.size, handler_catch.get_offset() if handler_catch.get_offset() not in h_off : continue h_off[ handler_catch.get_offset() ].append( handler_catch ) # if handler_catch.size <= 0 : # print m.get_name(), handler_catch.catch_all_addr # for handler in handler_catch.handlers : # print m.get_name(), "\t\t\t HANDLER", handler.type_idx, vm.get_class_manager().get_type( handler.type_idx ), handler.addr exceptions = [] #print m.get_name(), h_off for i in h_off : value = h_off[ i ][0] z = [ value.get_start_addr() * 2, (value.get_start_addr() * 2) + (value.get_insn_count() * 2) - 1 ] handler_catch = h_off[ i ][1] if handler_catch.get_size() <= 0 : z.append( [ "any", handler_catch.get_catch_all_addr() * 2 ] ) for handler in handler_catch.get_handlers() : z.append( [ vm.get_cm_type( handler.get_type_idx() ), handler.get_addr() * 2 ] ) exceptions.append( z ) #print m.get_name(), exceptions return exceptions def DVM_TOSTRING() : return { "O" : MATH_DVM_OPCODES.keys(), "I" : INVOKE_DVM_OPCODES, "G" : FIELD_READ_DVM_OPCODES, "P" : FIELD_WRITE_DVM_OPCODES, } class HeaderItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( HEADER[0], HEADER[1], buff.read( calcsize(HEADER[0]) ) ) def reload(self) : pass def get_obj(self) : return [] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] def get_value(self) : return self.format.get_value() def show(self) : bytecode._Print("HEADER", self.format) def get_off(self) : return self.__offset.off class AnnotationOffItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.annotation_off = SV( '=L', buff.read( 4 ) ) def show(self) : print "ANNOTATION_OFF_ITEM annotation_off=0x%x" % self.annotation_off.get_value() def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.annotation_off.get_value_buff() ) class AnnotationSetItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.annotation_off_item = [] self.size = SV( '=L', buff.read( 4 ) ) for i in range(0, self.size) : self.annotation_off_item.append( AnnotationOffItem(buff, cm) ) def reload(self) : pass def get_annotation_off_item(self) : return self.annotation_off_item def show(self) : print "ANNOTATION_SET_ITEM" nb = 0 for i in self.annotation_off_item : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.annotation_off_item ] def get_raw(self) : return [ bytecode.Buff(self.__offset.off, self.size.get_value_buff()) ] + [ i.get_raw() for i in self.annotation_off_item ] def get_off(self) : return self.__offset.off class AnnotationSetRefItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.annotations_off = SV( '=L', buff.read( 4 ) ) def show(self) : print "ANNOTATION_SET_REF_ITEM annotations_off=0x%x" % self.annotations_off.get_value() def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.annotations_off.get_value_buff() ) class AnnotationSetRefList : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.list = [] self.size = SV( '=L', buff.read( 4 ) ) for i in range(0, self.size) : self.list.append( AnnotationSetRefItem(buff, cm) ) def reload(self) : pass def show(self) : print "ANNOTATION_SET_REF_LIST" nb = 0 for i in self.list : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.list ] def get_raw(self) : return [ bytecode.Buff(self.__offset.off, self.size.get_value_buff()) ] + [ i.get_raw() for i in self.list ] def get_off(self) : return self.__offset.off class FieldAnnotation : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.field_idx = SV('=L', buff.read( 4 ) ) self.annotations_off = SV('=L', buff.read( 4 ) ) def show(self) : print "FIELD_ANNOTATION field_idx=0x%x annotations_off=0x%x" % (self.field_idx.get_value(), self.annotations_off.get_value()) def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff(self.__offset.off, self.field_idx.get_value_buff() + self.annotations_off.get_value_buff()) class MethodAnnotation : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.method_idx = SV('=L', buff.read( 4 ) ) self.annotations_off = SV('=L', buff.read( 4 ) ) def show(self) : print "METHOD_ANNOTATION method_idx=0x%x annotations_off=0x%x" % ( self.method_idx.get_value(), self.annotations_off.get_value()) def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff(self.__offset.off, self.method_idx.get_value_buff() + self.annotations_off.get_value_buff()) class ParameterAnnotation : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.method_idx = SV('=L', buff.read( 4 ) ) self.annotations_off = SV('=L', buff.read( 4 ) ) def show(self) : print "PARAMETER_ANNOTATION method_idx=0x%x annotations_off=0x%x" % (self.method_idx.get_value(), self.annotations_off.get_value()) def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff(self.__offset.off, self.method_idx.get_value_buff() + self.annotations_off.get_value_buff()) class AnnotationsDirectoryItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( ANNOTATIONS_DIRECTORY_ITEM[0], ANNOTATIONS_DIRECTORY_ITEM[1], buff.read( calcsize(ANNOTATIONS_DIRECTORY_ITEM[0]) ) ) self.field_annotations = [] for i in range(0, self.format.get_value().fields_size) : self.field_annotations.append( FieldAnnotation( buff, cm ) ) self.method_annotations = [] for i in range(0, self.format.get_value().annotated_methods_size) : self.method_annotations.append( MethodAnnotation( buff, cm ) ) self.parameter_annotations = [] for i in range(0, self.format.get_value().annotated_parameters_size) : self.parameter_annotations.append( ParameterAnnotation( buff, cm ) ) def reload(self) : pass def show(self) : print "ANNOTATIONS_DIRECTORY_ITEM", self.format.get_value() for i in self.field_annotations : i.show() for i in self.method_annotations : i.show() for i in self.parameter_annotations : i.show() def get_obj(self) : return [ i for i in self.field_annotations ] + \ [ i for i in self.method_annotations ] + \ [ i for i in self.parameter_annotations ] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] + \ [ i.get_raw() for i in self.field_annotations ] + \ [ i.get_raw() for i in self.method_annotations ] + \ [ i.get_raw() for i in self.parameter_annotations ] def get_off(self) : return self.__offset.off class TypeLItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.type_idx = SV( '=H', buff.read( 2 ) ) def show(self) : print "TYPE_LITEM", self.type_idx.get_value() def get_string(self) : return self.__CM.get_type( self.type_idx.get_value() ) def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff(self.__offset.off, self.type_idx.get_value_buff()) class TypeList : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) offset = buff.get_idx() self.pad = "" if offset % 4 != 0 : self.pad = buff.read( offset % 4 ) self.len_pad = len(self.pad) self.size = SV( '=L', buff.read( 4 ) ) self.list = [] for i in range(0, self.size) : self.list.append( TypeLItem( buff, cm ) ) def reload(self) : pass def get_type_list_off(self) : return self.__offset.off + self.len_pad def get_string(self) : return ' '.join(i.get_string() for i in self.list) def show(self) : print "TYPE_LIST" nb = 0 for i in self.list : print nb, self.__offset.off + self.len_pad, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.list ] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.pad + self.size.get_value_buff() ) ] + [ i.get_raw() for i in self.list ] def get_off(self) : return self.__offset.off DBG_END_SEQUENCE = 0x00 # (none) terminates a debug info sequence for a code_item DBG_ADVANCE_PC = 0x01 # uleb128 addr_diff addr_diff: amount to add to address register advances the address register without emitting a positions entry DBG_ADVANCE_LINE = 0x02 # sleb128 line_diff line_diff: amount to change line register by advances the line register without emitting a positions entry DBG_START_LOCAL = 0x03 # uleb128 register_num # uleb128p1 name_idx # uleb128p1 type_idx # register_num: register that will contain local name_idx: string index of the name # type_idx: type index of the type introduces a local variable at the current address. Either name_idx or type_idx may be NO_INDEX to indicate that that value is unknown. DBG_START_LOCAL_EXTENDED = 0x04 # uleb128 register_num uleb128p1 name_idx uleb128p1 type_idx uleb128p1 sig_idx # register_num: register that will contain local # name_idx: string index of the name # type_idx: type index of the type # sig_idx: string index of the type signature # introduces a local with a type signature at the current address. Any of name_idx, type_idx, or sig_idx may be NO_INDEX to indicate that that value is unknown. ( # If sig_idx is -1, though, the same data could be represented more efficiently using the opcode DBG_START_LOCAL.) # Note: See the discussion under "dalvik.annotation.Signature" below for caveats about handling signatures. DBG_END_LOCAL = 0x05 # uleb128 register_num # register_num: register that contained local # marks a currently-live local variable as out of scope at the current address DBG_RESTART_LOCAL = 0x06 # uleb128 register_num # register_num: register to restart re-introduces a local variable at the current address. # The name and type are the same as the last local that was live in the specified register. DBG_SET_PROLOGUE_END = 0x07 # (none) sets the prologue_end state machine register, indicating that the next position entry that is added should be considered the end of a # method prologue (an appropriate place for a method breakpoint). The prologue_end register is cleared by any special (>= 0x0a) opcode. DBG_SET_EPILOGUE_BEGIN = 0x08 # (none) sets the epilogue_begin state machine register, indicating that the next position entry that is added should be considered the beginning # of a method epilogue (an appropriate place to suspend execution before method exit). The epilogue_begin register is cleared by any special (>= 0x0a) opcode. DBG_SET_FILE = 0x09 # uleb128p1 name_idx # name_idx: string index of source file name; NO_INDEX if unknown indicates that all subsequent line number entries make reference to this source file name, # instead of the default name specified in code_item DBG_Special_Opcodes_BEGIN = 0x0a # (none) advances the line and address registers, emits a position entry, and clears prologue_end and epilogue_begin. See below for description. DBG_Special_Opcodes_END = 0xff class DBGBytecode : def __init__(self, op_value) : self.__op_value = op_value self.__format = [] def get_op_value(self) : return self.__op_value def add(self, value, ttype) : self.__format.append( (value, ttype) ) def show(self) : return [ i[0] for i in self.__format ] def get_obj(self) : return [] def get_raw(self) : buff = self.__op_value.get_value_buff() for i in self.__format : if i[1] == "u" : buff += writeuleb128( i[0] ) elif i[1] == "s" : buff += writesleb128( i[0] ) return buff class DebugInfoItem2 : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.__buff = buff self.__raw = "" def reload(self) : offset = self.__offset.off n = self.__CM.get_next_offset_item( offset ) s_idx = self.__buff.get_idx() self.__buff.set_idx( offset ) self.__raw = self.__buff.read( n - offset ) self.__buff.set_idx( s_idx ) def show(self) : pass def get_obj(self) : return [] def get_raw(self) : return [ bytecode.Buff(self.__offset.off, self.__raw) ] def get_off(self) : return self.__offset.off class DebugInfoItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.__line_start = readuleb128( buff ) self.__parameters_size = readuleb128( buff ) self.__parameter_names = [] for i in range(0, self.__parameters_size) : self.__parameter_names.append( readuleb128( buff ) ) self.__bytecodes = [] bcode = DBGBytecode( SV( '=B', buff.read(1) ) ) self.__bytecodes.append( bcode ) while bcode.get_op_value().get_value() != DBG_END_SEQUENCE : bcode_value = bcode.get_op_value().get_value() # print "0x%x" % bcode_value if bcode_value == DBG_SET_PROLOGUE_END : pass elif bcode_value >= DBG_Special_Opcodes_BEGIN and bcode_value <= DBG_Special_Opcodes_END : pass elif bcode_value == DBG_ADVANCE_PC : bcode.add( readuleb128( buff ), "u" ) elif bcode_value == DBG_ADVANCE_LINE : bcode.add( readsleb128( buff ), "s" ) elif bcode_value == DBG_START_LOCAL : bcode.add( readuleb128( buff ), "u" ) bcode.add( readuleb128( buff ), "u" ) bcode.add( readuleb128( buff ), "u" ) elif bcode_value == DBG_START_LOCAL_EXTENDED : bcode.add( readuleb128( buff ), "u" ) bcode.add( readuleb128( buff ), "u" ) bcode.add( readuleb128( buff ), "u" ) bcode.add( readuleb128( buff ), "u" ) elif bcode_value == DBG_END_LOCAL : bcode.add( readuleb128( buff ), "u" ) elif bcode_value == DBG_RESTART_LOCAL : bcode.add( readuleb128( buff ), "u" ) else : bytecode.Exit( "unknown or not yet supported DBG bytecode 0x%x" % bcode_value ) bcode = DBGBytecode( SV( '=B', buff.read(1) ) ) self.__bytecodes.append( bcode ) def reload(self) : pass def show(self) : print self.__line_start print self.__parameters_size print self.__parameter_names def get_raw(self) : return [ bytecode.Buff( self.__offset, writeuleb128( self.__line_start ) + \ writeuleb128( self.__parameters_size ) + \ ''.join(writeuleb128(i) for i in self.__parameter_names) + \ ''.join(i.get_raw() for i in self.__bytecodes) ) ] def get_off(self) : return self.__offset.off VALUE_BYTE = 0x00 # (none; must be 0) ubyte[1] signed one-byte integer value VALUE_SHORT = 0x02 # size - 1 (0..1) ubyte[size] signed two-byte integer value, sign-extended VALUE_CHAR = 0x03 # size - 1 (0..1) ubyte[size] unsigned two-byte integer value, zero-extended VALUE_INT = 0x04 # size - 1 (0..3) ubyte[size] signed four-byte integer value, sign-extended VALUE_LONG = 0x06 # size - 1 (0..7) ubyte[size] signed eight-byte integer value, sign-extended VALUE_FLOAT = 0x10 # size - 1 (0..3) ubyte[size] four-byte bit pattern, zero-extended to the right, and interpreted as an IEEE754 32-bit floating point value VALUE_DOUBLE = 0x11 # size - 1 (0..7) ubyte[size] eight-byte bit pattern, zero-extended to the right, and interpreted as an IEEE754 64-bit floating point value VALUE_STRING = 0x17 # size - 1 (0..3) ubyte[size] unsigned (zero-extended) four-byte integer value, interpreted as an index into the string_ids section and representing a string value VALUE_TYPE = 0x18 # size - 1 (0..3) ubyte[size] unsigned (zero-extended) four-byte integer value, interpreted as an index into the type_ids section and representing a reflective type/class value VALUE_FIELD = 0x19 # size - 1 (0..3) ubyte[size] unsigned (zero-extended) four-byte integer value, interpreted as an index into the field_ids section and representing a reflective field value VALUE_METHOD = 0x1a # size - 1 (0..3) ubyte[size] unsigned (zero-extended) four-byte integer value, interpreted as an index into the method_ids section and representing a reflective method value VALUE_ENUM = 0x1b # size - 1 (0..3) ubyte[size] unsigned (zero-extended) four-byte integer value, interpreted as an index into the field_ids section and representing the value of an enumerated type constant VALUE_ARRAY = 0x1c # (none; must be 0) encoded_array an array of values, in the format specified by "encoded_array Format" below. The size of the value is implicit in the encoding. VALUE_ANNOTATION = 0x1d # (none; must be 0) encoded_annotation a sub-annotation, in the format specified by "encoded_annotation Format" below. The size of the value is implicit in the encoding. VALUE_NULL = 0x1e # (none; must be 0) (none) null reference value VALUE_BOOLEAN = 0x1f # boolean (0..1) (none) one-bit value; 0 for false and 1 for true. The bit is represented in the value_arg. class EncodedArray : def __init__(self, buff, cm) : self.__CM = cm self.size = readuleb128( buff ) self.values = [] for i in range(0, self.size) : self.values.append( EncodedValue(buff, cm) ) def show(self) : print "ENCODED_ARRAY" for i in self.values : i.show() def get_values(self) : return self.values def get_obj(self) : return [ i for i in self.values ] def get_raw(self) : return writeuleb128( self.size ) + ''.join(i.get_raw() for i in self.values) class EncodedValue : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.val = SV('=B', buff.read( 1 ) ) self.__value_arg = self.val.get_value() >> 5 self.__value_type = self.val.get_value() & 0x1f self.raw_value = None self.value = "" # TODO: parse floats/doubles correctly if self.__value_type >= VALUE_SHORT and self.__value_type < VALUE_STRING : self.value, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) elif self.__value_type == VALUE_STRING : id, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) self.value = cm.get_raw_string(id) elif self.__value_type == VALUE_TYPE : id, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) self.value = cm.get_type(id) elif self.__value_type == VALUE_FIELD : id, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) self.value = cm.get_field(id) elif self.__value_type == VALUE_METHOD : id, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) self.value = cm.get_method(id) elif self.__value_type == VALUE_ENUM : id, self.raw_value = self._getintvalue(buff.read( self.__value_arg + 1 )) self.value = cm.get_field(id) elif self.__value_type == VALUE_ARRAY : self.value = EncodedArray( buff, cm ) elif self.__value_type == VALUE_ANNOTATION : self.value = EncodedAnnotation( buff, cm ) elif self.__value_type == VALUE_BYTE : self.value = buff.read( 1 ) elif self.__value_type == VALUE_NULL : self.value = None elif self.__value_type == VALUE_BOOLEAN : if self.__value_arg: self.value = True else: self.value = False else : bytecode.Exit( "Unknown value 0x%x" % self.__value_type ) def _getintvalue(self, buf): ret = 0 shift = 0 for b in buf: ret |= ord(b) << shift shift += 8 return ret, buf def show(self) : print "ENCODED_VALUE", self.val, self.__value_arg, self.__value_type def get_obj(self) : if isinstance(self.value, str) == False : return [ self.value ] return [] def get_raw(self) : if self.raw_value == None : return self.val.get_value_buff() + object_to_str( self.value ) else : return self.val.get_value_buff() + object_to_str( self.raw_value ) class AnnotationElement : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.name_idx = readuleb128( buff ) self.value = EncodedValue( buff, cm ) def show(self) : print "ANNOTATION_ELEMENT", self.name_idx self.value.show() def get_obj(self) : return [ self.value ] def get_raw(self) : return [ bytecode.Buff(self.__offset.off, writeuleb128(self.name_idx) + self.value.get_raw()) ] class EncodedAnnotation : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.type_idx = readuleb128( buff ) self.size = readuleb128( buff ) self.elements = [] for i in range(0, self.size) : self.elements.append( AnnotationElement( buff, cm ) ) def show(self) : print "ENCODED_ANNOTATION", self.type_idx, self.size for i in self.elements : i.show() def get_obj(self) : return [ i for i in self.elements ] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, writeuleb128(self.type_idx) + writeuleb128(self.size) ) ] + \ [ i.get_raw() for i in self.elements ] class AnnotationItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.visibility = SV( '=B', buff.read( 1 ) ) self.annotation = EncodedAnnotation(buff, cm) def reload(self) : pass def show(self) : print "ANNOATATION_ITEM", self.visibility.get_value() self.annotation.show() def get_obj(self) : return [ self.annotation ] def get_raw(self) : return [ bytecode.Buff(self.__offset.off, self.visibility.get_value_buff()) ] + self.annotation.get_raw() def get_off(self) : return self.__offset.off class EncodedArrayItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.value = EncodedArray( buff, cm ) def reload(self) : pass def show(self) : print "ENCODED_ARRAY_ITEM" self.value.show() def get_obj(self) : return [ self.value ] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.value.get_raw() ) def get_off(self) : return self.__offset.off class StringDataItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.utf16_size = readuleb128( buff ) self.data = buff.read( self.utf16_size + 1 ) if self.data[-1] != '\x00' : i = buff.read( 1 ) self.utf16_size += 1 self.data += i while i != '\x00' : i = buff.read( 1 ) self.utf16_size += 1 self.data += i def reload(self) : pass def get(self) : return self.data[:-1] def show(self) : print "STRING_DATA_ITEM", "%d %s" % ( self.utf16_size, repr( self.data ) ) def get_obj(self) : return [] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, writeuleb128( self.utf16_size ) + self.data ) ] def get_off(self) : return self.__offset.off class StringIdItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.string_data_off = SV( '=L', buff.read( 4 ) ) def reload(self) : pass def get_data_off(self) : return self.string_data_off.get_value() def get_obj(self) : return [] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.string_data_off.get_value_buff() ) ] def show(self) : print "STRING_ID_ITEM", self.string_data_off.get_value() def get_off(self) : return self.__offset.off class IdItem(object) : def __init__(self, size, buff, cm, TClass) : self.elem = [] for i in range(0, size) : self.elem.append( TClass(buff, cm) ) def gets(self) : return self.elem def get(self, idx) : return self.elem[ idx ] def reload(self) : for i in self.elem : i.reload() def show(self) : nb = 0 for i in self.elem : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.elem ] def get_raw(self) : return [ i.get_raw() for i in self.elem ] class TypeItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SV( '=L', buff.read( 4 ) ) self._name = None def reload(self) : self._name = self.__CM.get_string( self.format.get_value() ) def show(self) : print "TYPE_ITEM", self.format.get_value(), self._name def get_value(self) : return self.format.get_value() def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) class TypeIdItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.type = [] for i in range(0, size) : self.type.append( TypeItem( buff, cm ) ) def reload(self) : for i in self.type : i.reload() def get(self, idx) : if idx > len(self.type) : return self.type[-1].get_value() return self.type[ idx ].get_value() def show(self) : print "TYPE_ID_ITEM" nb = 0 for i in self.type : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.type ] def get_raw(self) : return [ i.get_raw() for i in self.type ] def get_off(self) : return self.__offset.off class ProtoItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( PROTO_ID_ITEM[0], PROTO_ID_ITEM[1], buff.read( calcsize(PROTO_ID_ITEM[0]) ) ) self._shorty = None self._return = None self._params = None def reload(self) : self._shorty = self.__CM.get_string( self.format.get_value().shorty_idx ) self._return = self.__CM.get_type( self.format.get_value().return_type_idx ) self._params = self.__CM.get_type_list( self.format.get_value().parameters_off ) def get_params(self) : return self._params def get_shorty(self) : return self._shorty def get_return_type(self) : return self._return def show(self) : print "PROTO_ITEM", self._shorty, self._return, self.format.get_value() def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) class ProtoIdItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.proto = [] for i in range(0, size) : self.proto.append( ProtoItem(buff, cm) ) def get(self, idx) : return self.proto[ idx ] def reload(self) : for i in self.proto : i.reload() def show(self) : print "PROTO_ID_ITEM" nb = 0 for i in self.proto : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.proto ] def get_raw(self) : return [ i.get_raw() for i in self.proto ] def get_off(self) : return self.__offset.off class FieldItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( FIELD_ID_ITEM[0], FIELD_ID_ITEM[1], buff.read( calcsize(FIELD_ID_ITEM[0]) ) ) self._class = None self._type = None self._name = None def reload(self) : general_format = self.format.get_value() self._class = self.__CM.get_type( general_format.class_idx ) self._type = self.__CM.get_type( general_format.type_idx ) self._name = self.__CM.get_string( general_format.name_idx ) def get_class_name(self) : return self._class def get_class(self) : return self._class def get_type(self) : return self._type def get_descriptor(self) : return self._type def get_name(self) : return self._name def get_list(self) : return [ self.get_class(), self.get_type(), self.get_name() ] def show(self) : print "FIELD_ITEM", self._class, self._type, self._name, self.format.get_value() def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) def get_off(self) : return self.__offset.off class FieldIdItem(IdItem) : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) super(FieldIdItem, self).__init__(size, buff, cm, FieldItem) def get_off(self) : return self.__offset.off class MethodItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( METHOD_ID_ITEM[0], METHOD_ID_ITEM[1], buff.read( calcsize(METHOD_ID_ITEM[0]) ) ) self._class = None self._proto = None self._name = None def reload(self) : general_format = self.format.get_value() self._class = self.__CM.get_type( general_format.class_idx ) self._proto = self.__CM.get_proto( general_format.proto_idx ) self._name = self.__CM.get_string( general_format.name_idx ) def get_type(self) : return self.format.get_value().proto_idx def show(self) : print "METHOD_ITEM", self._name, self._proto, self._class, self.format.get_value() def get_class(self) : return self._class def get_proto(self) : return self._proto def get_name(self) : return self._name def get_list(self) : return [ self.get_class(), self.get_name(), self.get_proto() ] def get_obj(self) : return [] def get_raw(self) : return bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) class MethodIdItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.methods = [] for i in range(0, size) : self.methods.append( MethodItem(buff, cm) ) def get(self, idx) : return self.methods[ idx ] def reload(self) : for i in self.methods : i.reload() def show(self) : print "METHOD_ID_ITEM" nb = 0 for i in self.methods : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.methods ] def get_raw(self) : return [ i.get_raw() for i in self.methods ] def get_off(self) : return self.__offset.off class EncodedField : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.field_idx_diff = readuleb128( buff ) self.access_flags = readuleb128( buff ) self.__field_idx = 0 self._name = None self._proto = None self._class_name = None self.static_init_value = None def reload(self) : name = self.__CM.get_field( self.__field_idx ) self._class_name = name[0] self._name = name[2] self._proto = ''.join(i for i in name[1]) def set_init_value(self, value) : self.static_init_value = value def get_access_flags(self) : return self.access_flags def get_access(self) : return self.get_access_flags() def get_class_name(self) : return self._class_name def get_descriptor(self) : return self._proto def get_name(self) : return self._name def adjust_idx(self, val) : self.__field_idx = self.field_idx_diff + val def get_idx(self) : return self.__field_idx def get_obj(self) : return [] def get_raw(self) : return writeuleb128( self.field_idx_diff ) + writeuleb128( self.access_flags ) def show(self) : print "\tENCODED_FIELD access_flags=%d (%s,%s,%s)" % (self.access_flags, self._class_name, self._name, self._proto) if self.static_init_value != None : print "\tvalue:", self.static_init_value.value self.show_dref() def show_dref(self) : try : for i in self.DREFr.items : print "R:", i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), [ "%x" % j.get_offset() for j in i[1] ] for i in self.DREFw.items : print "W:", i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), [ "%x" % j.get_offset() for j in i[1] ] except AttributeError: pass class EncodedMethod : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.method_idx_diff = readuleb128( buff ) self.access_flags = readuleb128( buff ) self.code_off = readuleb128( buff ) self.__method_idx = 0 self._name = None self._proto = None self._class_name = None self._code = None self.access_flags_string = None self.notes = [] def reload(self) : v = self.__CM.get_method( self.__method_idx ) self._class_name = v[0] self._name = v[1] self._proto = ''.join(i for i in v[2]) self._code = self.__CM.get_code( self.code_off ) def set_name(self, value) : self.__CM.set_hook_method_name( self.__method_idx, value ) self.reload() def set_class_name(self, value) : self.__CM.set_hook_method_class_name( self.__method_idx, value ) self.reload() def get_locals(self) : ret = self._proto.split(')') params = ret[0][1:].split() return self._code.registers_size.get_value()-len(params) - 1 def each_params_by_register(self, nb, proto) : bytecode._PrintSubBanner("Params") ret = proto.split(')') params = ret[0][1:].split() if params : print "- local registers: v%d...v%d" % (0, nb-len(params)-1) j = 0 for i in range(nb - len(params), nb) : print "- v%d:%s" % (i, get_type(params[j])) j += 1 else : print "local registers: v%d...v%d" % (0, nb-1) print "- return:%s" % get_type(ret[1]) bytecode._PrintSubBanner() def build_access_flags(self) : if self.access_flags_string == None : self.access_flags_string = "" for i in ACCESS_FLAGS_METHODS : if (i[0] & self.access_flags) == i[0] : self.access_flags_string += i[1] + " " if self.access_flags_string == "" : self.access_flags_string = "0x%x" % self.access_flags else : self.access_flags_string = self.access_flags_string[:-1] def show_info(self) : self.build_access_flags() bytecode._PrintSubBanner("Method Information") print "%s->%s%s [access_flags=%s]" % (self._class_name, self._name, self._proto, self.access_flags_string) def show(self) : colors = bytecode.disable_print_colors() self.pretty_show() bytecode.enable_print_colors(colors) def pretty_show(self) : self.show_info() self.show_notes() if self._code != None : self.each_params_by_register( self._code.registers_size.get_value(), self._proto ) if self.__CM.get_vmanalysis() == None : self._code.show() else : self._code.pretty_show( self.__CM.get_vmanalysis().hmethods[ self ] ) self.show_xref() def show_xref(self) : try : bytecode._PrintSubBanner("XREF") for i in self.XREFfrom.items : print "F:", i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), [ "%x" % j.get_offset() for j in i[1] ] for i in self.XREFto.items : print "T:", i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), [ "%x" % j.get_offset() for j in i[1] ] bytecode._PrintSubBanner() except AttributeError: pass def show_notes(self) : if self.notes != [] : bytecode._PrintSubBanner("Notes") for i in self.notes : bytecode._PrintNote(i) bytecode._PrintSubBanner() def source(self) : self.__CM.decompiler_ob.display_source( self.get_class_name(), self.get_name(), self.get_descriptor() ) def get_access_flags(self) : return self.access_flags def get_access(self) : return self.get_access_flags() def get_length(self) : if self._code != None : return self._code.get_length() return 0 def get_code(self) : return self._code def get_instructions(self) : if self._code == None : return [] return self._code.get_bc().get() def get_instruction(self, idx, off=None) : if self._code != None : return self._code.get_instruction(idx, off) return None def get_descriptor(self) : return self._proto def get_class_name(self) : return self._class_name def get_name(self) : return self._name def adjust_idx(self, val) : self.__method_idx = self.method_idx_diff + val def get_idx(self) : return self.__method_idx def get_obj(self) : return [] def get_raw(self) : return writeuleb128( self.method_idx_diff ) + writeuleb128( self.access_flags ) + writeuleb128( self.code_off ) def add_inote(self, msg, idx, off=None) : if self._code != None : self._code.add_inote(msg, idx, off) def add_note(self, msg) : self.notes.append( msg ) class ClassDataItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.static_fields_size = readuleb128( buff ) self.instance_fields_size = readuleb128( buff ) self.direct_methods_size = readuleb128( buff ) self.virtual_methods_size = readuleb128( buff ) self.static_fields = [] self.instance_fields = [] self.direct_methods = [] self.virtual_methods = [] self.load_field( self.static_fields_size, self.static_fields, EncodedField, buff, cm ) self.load_field( self.instance_fields_size, self.instance_fields, EncodedField, buff, cm ) self.load_field( self.direct_methods_size, self.direct_methods, EncodedMethod, buff, cm ) self.load_field( self.virtual_methods_size, self.virtual_methods, EncodedMethod, buff, cm ) def set_static_fields(self, values) : if values != None : if len(values.values) <= len(self.static_fields) : for i in range(0, len(values.values)) : self.static_fields[i].set_init_value( values.values[i] ) def load_field(self, size, l, Type, buff, cm) : prev = 0 for i in range(0, size) : el = Type(buff, cm) el.adjust_idx( prev ) prev = el.get_idx() l.append( el ) def reload(self) : for i in self.static_fields : i.reload() for i in self.instance_fields : i.reload() for i in self.direct_methods : i.reload() for i in self.virtual_methods : i.reload() def show(self) : print "CLASS_DATA_ITEM static_fields_size=%d instance_fields_size=%d direct_methods_size=%d virtual_methods_size=%d" % \ (self.static_fields_size, self.instance_fields_size, self.direct_methods_size, self.virtual_methods_size) print "SF" for i in self.static_fields : i.show() print "IF" for i in self.instance_fields : i.show() print "DM" for i in self.direct_methods : i.show() print "VM" for i in self.virtual_methods : i.show() def pretty_show(self) : print "CLASS_DATA_ITEM static_fields_size=%d instance_fields_size=%d direct_methods_size=%d virtual_methods_size=%d" % \ (self.static_fields_size, self.instance_fields_size, self.direct_methods_size, self.virtual_methods_size) print "SF" for i in self.static_fields : i.show() print "IF" for i in self.instance_fields : i.show() print "DM" for i in self.direct_methods : i.pretty_show() print "VM" for i in self.virtual_methods : i.pretty_show() def get_methods(self) : return [ x for x in self.direct_methods ] + [ x for x in self.virtual_methods ] def get_fields(self) : return [ x for x in self.static_fields ] + [ x for x in self.instance_fields ] def get_off(self) : return self.__offset.off def get_obj(self) : return [ i for i in self.static_fields ] + \ [ i for i in self.instance_fields ] + \ [ i for i in self.direct_methods ] + \ [ i for i in self.virtual_methods ] def get_raw(self) : buff = writeuleb128( self.static_fields_size ) + \ writeuleb128( self.instance_fields_size ) + \ writeuleb128( self.direct_methods_size ) + \ writeuleb128( self.virtual_methods_size ) + \ ''.join(i.get_raw() for i in self.static_fields) + \ ''.join(i.get_raw() for i in self.instance_fields) + \ ''.join(i.get_raw() for i in self.direct_methods) + \ ''.join(i.get_raw() for i in self.virtual_methods) return [ bytecode.Buff(self.__offset.off, buff) ] class ClassItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( CLASS_DEF_ITEM[0], CLASS_DEF_ITEM[1], buff.read( calcsize(CLASS_DEF_ITEM[0]) ) ) self._interfaces = None self._class_data_item = None self._static_values = None self._name = None self._sname = None def reload(self) : general_format = self.format.get_value() self._name = self.__CM.get_type( general_format.class_idx ) self._sname = self.__CM.get_type( general_format.superclass_idx ) if general_format.interfaces_off != 0 : self._interfaces = self.__CM.get_type_list( general_format.interfaces_off ) if general_format.class_data_off != 0 : self._class_data_item = self.__CM.get_class_data_item( general_format.class_data_off ) self._class_data_item.reload() if general_format.static_values_off != 0 : self._static_values = self.__CM.get_encoded_array_item ( general_format.static_values_off ) if self._class_data_item != None : self._class_data_item.set_static_fields( self._static_values.value ) #for i in self._static_values.value.values : # print i, i.value def show(self) : print "CLASS_ITEM", self._name, self._sname, self._interfaces, self.format.get_value() def source(self) : self.__CM.decompiler_ob.display_all( self.get_name() ) def set_name(self, value) : self.__CM.set_hook_class_name( self.format.get_value().class_idx, value ) self.reload() def get_class_data(self) : return self._class_data_item def get_name(self) : return self._name def get_superclassname(self) : return self._sname def get_info(self) : return "%s:%s" % (self._name, self._sname) def get_methods(self) : if self._class_data_item != None : return self._class_data_item.get_methods() return [] def get_fields(self) : if self._class_data_item != None : return self._class_data_item.get_fields() return [] def get_obj(self) : return [] def get_class_idx(self) : return self.format.get_value().class_idx def get_access_flags(self) : return self.format.get_value().access_flags def get_superclass_idx(self) : return self.format.get_value().superclass_idx def get_interfaces_off(self) : return self.format.get_value().interfaces_off def get_source_file_idx(self) : return self.format.get_value().source_file_idx def get_annotations_off(self): return self.format.get_value().annotations_off def get_class_data_off(self) : return self.format.get_value().class_data_off def get_static_values_off(self) : return self.format.get_value().static_values_off def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] class ClassDefItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.class_def = [] for i in range(0, size) : idx = buff.get_idx() class_def = ClassItem( buff, cm ) self.class_def.append( class_def ) buff.set_idx( idx + calcsize(CLASS_DEF_ITEM[0]) ) def get_method(self, name_class, name_method) : l = [] for i in self.class_def : if i.get_name() == name_class : for j in i.get_methods() : if j.get_name() == name_method : l.append(j) return l def get_names(self) : return [ x.get_name() for x in self.class_def ] def reload(self) : for i in self.class_def : i.reload() def show(self) : print "CLASS_DEF_ITEM" nb = 0 for i in self.class_def : print nb, i.show() nb = nb + 1 def get_obj(self) : return [ i for i in self.class_def ] def get_raw(self) : return [ i.get_raw() for i in self.class_def ] def get_off(self) : return self.__offset.off class EncodedTypeAddrPair : def __init__(self, buff) : self.type_idx = readuleb128( buff ) self.addr = readuleb128( buff ) def get_obj(self) : return [] def show(self) : print "ENCODED_TYPE_ADDR_PAIR", self.type_idx, self.addr def get_raw(self) : return writeuleb128( self.type_idx ) + writeuleb128( self.addr ) def get_type_idx(self) : return self.type_idx def get_addr(self) : return self.addr class EncodedCatchHandler : def __init__(self, buff, cm) : self.__offset = cm.add_offset( buff.get_idx(), self ) self.size = readsleb128( buff ) self.handlers = [] for i in range(0, abs(self.size)) : self.handlers.append( EncodedTypeAddrPair(buff) ) if self.size <= 0 : self.catch_all_addr = readuleb128( buff ) def show(self) : print "ENCODED_CATCH_HANDLER size=0x%x" % self.size for i in self.handlers : i.show() def get_obj(self) : return [ i for i in self.handlers ] def get_raw(self) : buff = writesleb128( self.size ) + ''.join(i.get_raw() for i in self.handlers) if self.size <= 0 : buff += writeuleb128( self.catch_all_addr ) return buff def get_handlers(self) : return self.handlers def get_offset(self) : return self.__offset.off def get_size(self) : return self.size def get_catch_all_addr(self) : return self.catch_all_addr class EncodedCatchHandlerList : def __init__(self, buff, cm) : self.__offset = cm.add_offset( buff.get_idx(), self ) self.size = readuleb128( buff ) self.list = [] for i in range(0, self.size) : self.list.append( EncodedCatchHandler(buff, cm) ) def show(self) : print "ENCODED_CATCH_HANDLER_LIST size=0x%x" % self.size for i in self.list : i.show() def get_obj(self) : return [ i for i in self.list ] def get_raw(self) : return writeuleb128( self.size ) + ''.join(i.get_raw() for i in self.list) def get_offset(self) : return self.__offset.off def get_list(self) : return self.list # 0x12 : [ "11n", "const/4", "vA, #+B", "B|A|op" ], # if self.op_value == 0x12 : # self.formatted_operands.append( ("#l", self.operands[1][1]) ) # 0x13 : [ "21s", "const/16", "vAA, #+BBBB", "AA|op BBBB" ], # elif self.op_value == 0x13 : # self.formatted_operands.append( ("#l", self.operands[1][1]) ) # 0x14 : [ "31i", "const", "vAA, #+BBBBBBBB", "AA|op BBBB BBBB" ], # const instruction, convert value into float # elif self.op_value == 0x14 : # x = (0xFFFF & self.operands[1][1]) | ((0xFFFF & self.operands[2][1] ) << 16) # self.formatted_operands.append( ("#f", unpack("=f", pack("=L", x))[0] ) ) # 0x15 : [ "21h", "const/high16", "vAA, #+BBBB0000", "AA|op BBBB0000" ], # elif self.op_value == 0x15 : # self.formatted_operands.append( ("#f", unpack( '=f', '\x00\x00' + pack('=h', self.operands[1][1]))[0] ) ) # 0x16 : [ "21s", "const-wide/16", "vAA, #+BBBB", "AA|op BBBB" ], # elif self.op_value == 0x16 : # self.formatted_operands.append( ("#l", self.operands[1][1]) ) # 0x17 : [ "31i", "const-wide/32", "vAA, #+BBBBBBBB", "AA|op BBBB BBBB" ], # elif self.op_value == 0x17 : # x = ((0xFFFF & self.operands[2][1]) << 16) | (0xFFFF & self.operands[1][1]) # self.formatted_operands.append( ("#l", unpack( '=d', pack('=d', x))[0] ) ) # 0x18 : [ "51l", "const-wide", "vAA, #+BBBBBBBBBBBBBBBB", "AA|op BBBB BBBB BBBB BBBB" ], # convert value to double # elif self.op_value == 0x18 : # x = (0xFFFF & self.operands[1][1]) | ((0xFFFF & self.operands[2][1]) << 16) | ((0xFFFF & self.operands[3][1]) << 32) | ((0xFFFF & self.operands[4][1]) << 48) # self.formatted_operands.append( ("#d", unpack( '=d', pack('=Q', x ) )[0]) ) # 0x19 : [ "21h", "const-wide/high16", "vAA, #+BBBB000000000000", "AA|op BBBB000000000000" ], # convert value to double # elif self.op_value == 0x19 : # self.formatted_operands.append( ("#d", unpack( '=d', '\x00\x00\x00\x00\x00\x00' + pack('=h', self.operands[1][1]))[0]) ) # return self.formatted_operands DALVIK_OPCODES_PAYLOAD = { 0x0100 : [PackedSwitch], 0x0200 : [SparseSwitch], 0x0300 : [FillArrayData], } DALVIK_OPCODES_EXPANDED = { 0x00ff : [], 0x01ff : [], 0x02ff : [], 0x03ff : [], 0x04ff : [], 0x05ff : [], 0x06ff : [], 0x07ff : [], 0x08ff : [], 0x09ff : [], 0x10ff : [], 0x11ff : [], 0x12ff : [], 0x13ff : [], 0x14ff : [], 0x15ff : [], 0x16ff : [], 0x17ff : [], 0x18ff : [], 0x19ff : [], 0x20ff : [], 0x21ff : [], 0x22ff : [], 0x23ff : [], 0x24ff : [], 0x25ff : [], 0x26ff : [], } def get_kind(cm, kind, value) : if kind == KIND_METH : method = cm.get_method_ref(value) class_name = method.get_class() name = method.get_name() proto = method.get_proto() proto = proto[0] + proto[1] return "%s->%s%s" % (class_name, name, proto) elif kind == KIND_STRING : return "\"" + cm.get_string(value) + "\"" elif kind == KIND_FIELD : return cm.get_field(value) elif kind == KIND_TYPE : return cm.get_type(value) return None class Instruction(object) : def __init__(self) : self.notes = [] def get_name(self) : return self.name def get_op_value(self) : return self.OP def get_literals(self) : return [] def show(self, nb) : print self.name + " " + self.get_output(), def show_buff(self, nb) : return self.get_output() def get_translated_kind(self) : return get_kind(self.cm, self.kind, self.get_ref_kind()) def add_note(self, msg) : self.notes.append( msg ) def get_notes(self) : return self.notes # def get_raw(self) : # return "" class Instruction35c(Instruction) : def __init__(self, cm, buff, args) : super(Instruction35c, self).__init__() self.name = args[0][0] self.kind = args[0][1] self.cm = cm i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.G = (i16 >> 8) & 0xf self.A = (i16 >> 12) & 0xf self.BBBB = unpack("=H", buff[2:4])[0] i16 = unpack("=H", buff[4:6])[0] self.C = i16 & 0xf self.D = (i16 >> 4) & 0xf self.E = (i16 >> 8) & 0xf self.F = (i16 >> 12) & 0xf log_andro.debug("OP:%x %s G:%x A:%x BBBB:%x C:%x D:%x E:%x F:%x" % (self.OP, args[0], self.G, self.A, self.BBBB, self.C, self.D, self.E, self.F)) def get_output(self) : buff = "" kind = get_kind(self.cm, self.kind, self.BBBB) if self.A == 0 : buff += "%s" % (kind) elif self.A == 1 : buff += "v%d, %s" % (self.C, kind) elif self.A == 2 : buff += "v%d, v%d, %s" % (self.C, self.D, kind) elif self.A == 3 : buff += "v%d, v%d, v%d, %s" % (self.C, self.D, self.E, kind) elif self.A == 4 : buff += "v%d, v%d, v%d, v%d, %s" % (self.C, self.D, self.E, self.F, kind) elif self.A == 5 : buff += "v%d, v%d, v%d, v%d, v%d, %s" % (self.C, self.D, self.E, self.F, self.G, kind) return buff def get_length(self) : return 6 def get_ref_kind(self) : return self.BBBB def get_raw(self) : return pack("=HHH", (self.A << 12) | (self.G << 8) | self.OP, self.BBBB, (self.F << 12) | (self.E << 8) | (self.D << 4) | self.C) class Instruction10x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction10x, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff log_andro.debug("OP:%x %s" % (self.OP, args[0])) def get_output(self) : buff = "" return buff def get_length(self) : return 2 def get_raw(self) : return pack("=H", self.OP) class Instruction21h(Instruction) : def __init__(self, cm, buff, args) : super(Instruction21h, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s AA:%x BBBBB:%x" % (self.OP, args[0], self.AA, self.BBBB)) self.formatted_operands = [] if self.OP == 0x15 : self.formatted_operands.append( unpack( '=f', '\x00\x00' + pack('=h', self.BBBB ) )[0] ) elif self.OP == 0x19: self.formatted_operands.append( unpack( '=d', '\x00\x00\x00\x00\x00\x00' + pack('=h', self.BBBB) )[0] ) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, #+%d" % (self.AA, self.BBBB) if self.formatted_operands != [] : buff += " // %s" % (str(self.formatted_operands)) return buff def show(self, nb) : print self.get_output(), def get_literals(self) : return [ self.BBBB ] def get_raw(self) : return pack("=Hh", (self.AA << 8) | self.OP, self.BBBB) class Instruction11n(Instruction) : def __init__(self, cm, buff, args) : super(Instruction11n, self).__init__() self.name = args[0][0] i16 = unpack("=h", buff[0:2])[0] self.OP = i16 & 0xff self.A = (i16 >> 8) & 0xf self.B = (i16 >> 12) & 0xf log_andro.debug("OP:%x %s A:%x B:%x" % (self.OP, args[0], self.A, self.B)) def get_length(self) : return 2 def get_output(self) : buff = "" buff += "v%d, #+%d" % (self.A, self.B) return buff def get_literals(self) : return [ self.B ] def get_raw(self) : return pack("=h", (self.B << 12) | (self.A << 8) | self.OP) class Instruction21c(Instruction) : def __init__(self, cm, buff, args) : super(Instruction21c, self).__init__() self.name = args[0][0] self.kind = args[0][1] self.cm = cm i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s AA:%x BBBBB:%x" % (self.OP, args[0], self.AA, self.BBBB)) def get_length(self) : return 4 def get_output(self) : buff = "" kind = get_kind(self.cm, self.kind, self.BBBB) buff += "v%d, %s" % (self.AA, kind) return buff def get_ref_kind(self) : return self.BBBB def get_string(self) : return get_kind(self.cm, self.kind, self.BBBB) def get_raw(self) : return pack("=Hh", (self.AA << 8) | self.OP, self.BBBB) class Instruction21s(Instruction) : def __init__(self, cm, buff, args) : super(Instruction21s, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=h", buff[2:4])[0] self.formatted_operands = [] if self.OP == 0x16 : self.formatted_operands.append( unpack( '=d', pack('=d', self.BBBB))[0] ) log_andro.debug("OP:%x %s AA:%x BBBBB:%x" % (self.OP, args[0], self.AA, self.BBBB)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, #+%d" % (self.AA, self.BBBB) if self.formatted_operands != [] : buff += " // %s" % str(self.formatted_operands) return buff def get_literals(self) : return [ self.BBBB ] def get_raw(self) : return pack("=Hh", (self.AA << 8) | self.OP, self.BBBB) class Instruction22c(Instruction) : def __init__(self, cm, buff, args) : super(Instruction22c, self).__init__() self.name = args[0][0] self.kind = args[0][1] self.cm = cm i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.A = (i16 >> 8) & 0xf self.B = (i16 >> 12) & 0xf self.CCCC = unpack("=H", buff[2:4])[0] log_andro.debug("OP:%x %s A:%x B:%x CCCC:%x" % (self.OP, args[0], self.A, self.B, self.CCCC)) def get_length(self) : return 4 def get_output(self) : buff = "" kind = get_kind(self.cm, self.kind, self.CCCC) buff += "v%d, v%d, %s" % (self.A, self.B, kind) return buff def get_ref_kind(self) : return self.CCCC def get_raw(self) : return pack("=HH", (self.B << 12) | (self.A << 8) | (self.OP), self.CCCC) class Instruction31t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction31t, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBBBBBB = unpack("=i", buff[2:6])[0] log_andro.debug("OP:%x %s AA:%x BBBBBBBBB:%x" % (self.OP, args[0], self.AA, self.BBBBBBBB)) def get_length(self) : return 6 def get_output(self) : buff = "" buff += "v%d, +%d" % (self.AA, self.BBBBBBBB) return buff def get_ref_off(self) : return self.BBBBBBBB def get_raw(self) : return pack("=Hi", (self.AA << 8) | self.OP, self.BBBBBBBB) class Instruction31c(Instruction) : def __init__(self, cm, buff, args) : super(Instruction31c, self).__init__() self.name = args[0][0] self.kind = args[0][1] self.cm = cm i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBBBBBB = unpack("=i", buff[2:6])[0] log_andro.debug("OP:%x %s AA:%x BBBBBBBBB:%x" % (self.OP, args[0], self.AA, self.BBBBBBBB)) def get_length(self) : return 6 def get_output(self) : buff = "" kind = get_kind(self.cm, self.kind, self.BBBBBBBB) buff += "v%d, %s" % (self.AA, kind) return buff def get_ref_kind(self) : return self.BBBBBBBB def get_string(self) : return get_kind(self.cm, self.kind, self.BBBBBBBB) def get_raw(self) : return pack("=Hi", (self.AA << 8) | self.OP, self.BBBBBBBB) class Instruction12x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction12x, self).__init__() self.name = args[0][0] i16 = unpack("=h", buff[0:2])[0] self.OP = i16 & 0xff self.A = (i16 >> 8) & 0xf self.B = (i16 >> 12) & 0xf log_andro.debug("OP:%x %s A:%x B:%x" % (self.OP, args[0], self.A, self.B)) def get_length(self) : return 2 def get_output(self) : buff = "" buff += "v%d, v%d" % (self.A, self.B) return buff def get_raw(self) : return pack("=H", (self.B << 12) | (self.A << 8) | (self.OP)) class Instruction11x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction11x, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff log_andro.debug("OP:%x %s AA:%x" % (self.OP, args[0], self.AA)) def get_length(self) : return 2 def get_output(self) : buff = "" buff += "v%d" % (self.AA) return buff def get_raw(self) : return pack("=H", (self.AA << 8) | self.OP) class Instruction51l(Instruction) : def __init__(self, cm, buff, args) : super(Instruction51l, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBBBBBBBBBBBBBB = unpack("=q", buff[2:10])[0] self.formatted_operands = [] if self.OP == 0x18 : self.formatted_operands.append( unpack( '=d', pack('=q', self.BBBBBBBBBBBBBBBB ) )[0] ) log_andro.debug("OP:%x %s AA:%x BBBBBBBBBBBBBBBB:%x" % (self.OP, args[0], self.AA, self.BBBBBBBBBBBBBBBB)) def get_length(self) : return 10 def get_output(self) : buff = "" buff += "v%d, #+%d" % (self.AA, self.BBBBBBBBBBBBBBBB) if self.formatted_operands != [] : buff += " // %s" % str(self.formatted_operands) return buff def get_literals(self) : return [ self.BBBBBBBBBBBBBBBB ] def get_raw(self) : return pack("=Hq", (self.AA << 8) | self.OP, self.BBBBBBBBBBBBBBBB) class Instruction31i(Instruction) : def __init__(self, cm, buff, args) : super(Instruction31i, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBBBBBB = unpack("=i", buff[2:6])[0] self.formatted_operands = [] if self.OP == 0x14 : self.formatted_operands.append( unpack("=f", pack("=i", self.BBBBBBBB))[0] ) elif self.OP == 0x17 : self.formatted_operands.append( unpack( '=d', pack('=d', self.BBBBBBBB))[0] ) log_andro.debug("OP:%x %s AA:%x BBBBBBBBB:%x" % (self.OP, args[0], self.AA, self.BBBBBBBB)) def get_length(self) : return 6 def get_output(self) : buff = "" buff += "v%d, #+%d" % (self.AA, self.BBBBBBBB) if self.formatted_operands != [] : buff += " // %s" % str(self.formatted_operands) return buff def get_literals(self) : return [ self.BBBBBBBB ] def get_raw(self) : return pack("=Hi", (self.AA << 8) | self.OP, self.BBBBBBBB) class Instruction22x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction22x, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=H", buff[2:4])[0] log_andro.debug("OP:%x %s AA:%x BBBBB:%x" % (self.OP, args[0], self.AA, self.BBBB)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, v%d" % (self.AA, self.BBBB) return buff def get_raw(self) : return pack("=HH", (self.AA << 8) | self.OP, self.BBBB) class Instruction23x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction23x, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff i16 = unpack("=H", buff[2:4])[0] self.BB = i16 & 0xff self.CC = (i16 >> 8) & 0xff log_andro.debug("OP:%x %s AA:%x BB:%x CC:%x" % (self.OP, args[0], self.AA, self.BB, self.CC)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, v%d, v%d" % (self.AA, self.BB, self.CC) return buff def get_raw(self) : return pack("=HH", (self.AA << 8) | self.OP, (self.CC << 8) | self.BB) class Instruction20t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction20t, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AAAA = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s AAAA:%x" % (self.OP, args[0], self.AAAA)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "%d" % (self.AAAA) return buff def get_ref_off(self) : return self.AAAA def get_raw(self) : return pack("=Hh", self.OP, self.AAAA) class Instruction21t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction21t, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s AA:%x BBBBB:%x" % (self.OP, args[0], self.AA, self.BBBB)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, +%d" % (self.AA, self.BBBB) return buff def get_ref_off(self) : return self.BBBB def get_raw(self) : return pack("=Hh", (self.AA << 8) | self.OP, self.BBBB) class Instruction10t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction10t, self).__init__() self.name = args[0][0] self.OP = unpack("=B", buff[0:1])[0] self.AA = unpack("=b", buff[1:2])[0] log_andro.debug("OP:%x %s AA:%x" % (self.OP, args[0], self.AA)) def get_length(self) : return 2 def get_output(self) : buff = "" buff += "%d" % (self.AA) return buff def show(self, nb) : print self.get_output(), def get_ref_off(self) : return self.AA def get_raw(self) : return pack("=Bb", self.OP, self.AA) class Instruction22t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction22t, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.A = (i16 >> 8) & 0xf self.B = (i16 >> 12) & 0xf self.CCCC = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s A:%x B:%x CCCC:%x" % (self.OP, args[0], self.A, self.B, self.CCCC)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, v%d, +%d" % (self.A, self.B, self.CCCC) return buff def get_ref_off(self) : return self.CCCC def get_raw(self) : return pack("=Hh", (self.B << 12) | (self.A << 8) | self.OP, self.CCCC) class Instruction22s(Instruction) : def __init__(self, cm, buff, args) : super(Instruction22s, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.A = (i16 >> 8) & 0xf self.B = (i16 >> 12) & 0xf self.CCCC = unpack("=h", buff[2:4])[0] log_andro.debug("OP:%x %s A:%x B:%x CCCC:%x" % (self.OP, args[0], self.A, self.B, self.CCCC)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, v%d, #+%d" % (self.A, self.B, self.CCCC) return buff def get_literals(self) : return [ self.CCCC ] def get_raw(self) : return pack("=Hh", (self.B << 12) | (self.A << 8) | self.OP, self.CCCC) class Instruction22b(Instruction) : def __init__(self, cm, buff, args) : super(Instruction22b, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BB = unpack("=B", buff[2:3])[0] self.CC = unpack("=b", buff[3:4])[0] log_andro.debug("OP:%x %s AA:%x BB:%x CC:%x" % (self.OP, args[0], self.AA, self.BB, self.CC)) def get_length(self) : return 4 def get_output(self) : buff = "" buff += "v%d, v%d, #+%d" % (self.AA, self.BB, self.CC) return buff def get_literals(self) : return [ self.CC ] def get_raw(self) : return pack("=Hh", (self.AA << 8) | self.OP, (self.CC << 8) | self.BB) class Instruction30t(Instruction) : def __init__(self, cm, buff, args) : super(Instruction30t, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AAAAAAAA = unpack("=i", buff[2:6])[0] log_andro.debug("OP:%x %s AAAAAAAA:%x" % (self.OP, args[0], self.AAAAAAAA)) def get_length(self) : return 6 def get_output(self) : buff = "" buff += "%d" % (self.AAAAAAAA) return buff def get_ref_off(self) : return self.AAAAAAAA def get_raw(self) : return pack("=Hi", self.OP, self.AAAAAAAA) class Instruction3rc(Instruction) : def __init__(self, cm, buff, args) : self.name = args[0][0] super(Instruction3rc, self).__init__() self.kind = args[0][1] self.cm = cm i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AA = (i16 >> 8) & 0xff self.BBBB = unpack("=H", buff[2:4])[0] self.CCCC = unpack("=H", buff[4:6])[0] self.NNNN = self.CCCC + self.AA - 1 log_andro.debug("OP:%x %s AA:%x BBBB:%x CCCC:%x NNNN:%d" % (self.OP, args[0], self.AA, self.BBBB, self.CCCC, self.NNNN)) def get_length(self) : return 6 def get_output(self) : buff = "" kind = get_kind(self.cm, self.kind, self.BBBB) if self.CCCC == self.NNNN : buff += "v%d, %s" % (self.CCCC, kind) else : buff += "v%d ... v%d, %s" % (self.CCCC, self.NNNN, kind) return buff def get_ref_kind(self) : return self.BBBB def get_raw(self) : return pack("=HHH", (self.AA << 8) | self.OP, self.BBBB, self.CCCC) class Instruction32x(Instruction) : def __init__(self, cm, buff, args) : super(Instruction32x, self).__init__() self.name = args[0][0] i16 = unpack("=H", buff[0:2])[0] self.OP = i16 & 0xff self.AAAA = unpack("=H", buff[2:4])[0] self.BBBB = unpack("=H", buff[4:6])[0] log_andro.debug("OP:%x %s AAAAA:%x BBBBB:%x" % (self.OP, args[0], self.AAAA, self.BBBB)) def get_length(self) : return 6 def get_output(self) : buff = "" buff += "v%d, v%d" % (self.AAAA, self.BBBBB) return buff def get_raw(self) : return pack("=HHH", self.OP, self.AAAA, self.BBBB) KIND_METH = 0 KIND_STRING = 1 KIND_FIELD = 2 KIND_TYPE = 3 DALVIK_OPCODES_FORMAT = { 0x00 : [Instruction10x, [ "nop" ] ], 0x01 : [Instruction12x, [ "move" ] ], 0x02 : [Instruction22x, [ "move/from16" ] ], 0x03 : [Instruction32x, [ "move/16" ] ], 0x04 : [Instruction12x, [ "move-wide" ] ], 0x05 : [Instruction22x, [ "move-wide/from16" ] ], 0x06 : [Instruction32x, [ "move-wide/16" ] ], 0x07 : [Instruction12x, [ "move-object" ] ], 0x08 : [Instruction22x, [ "move-object/from16" ] ], 0x09 : [Instruction32x, [ "move-object/16" ] ], 0x0a : [Instruction11x, [ "move-result" ] ], 0x0b : [Instruction11x, [ "move-result-wide" ] ], 0x0c : [Instruction11x, [ "move-result-object" ] ], 0x0d : [Instruction11x, [ "move-exception" ] ], 0x0e : [Instruction10x, [ "return-void" ] ], 0x0f : [Instruction11x, [ "return" ] ], 0x10 : [Instruction11x, [ "return-wide" ] ], 0x11 : [Instruction11x, [ "return-object" ] ], 0x12 : [Instruction11n, [ "const/4" ] ], 0x13 : [Instruction21s, [ "const/16" ] ], 0x14 : [Instruction31i, [ "const" ] ], 0x15 : [Instruction21h, [ "const/high16" ] ], 0x16 : [Instruction21s, [ "const-wide/16" ] ], 0x17 : [Instruction31i, [ "const-wide/32" ] ], 0x18 : [Instruction51l, [ "const-wide" ] ], 0x19 : [Instruction21h, [ "const-wide/high16" ] ], 0x1a : [Instruction21c, [ "const-string", KIND_STRING ] ], 0x1b : [Instruction31c, [ "const-string/jumbo", KIND_STRING ] ], 0x1c : [Instruction21c, [ "const-class", KIND_TYPE ] ], 0x1d : [Instruction11x, [ "monitor-enter" ] ], 0x1e : [Instruction11x, [ "monitor-exit" ] ], 0x1f : [Instruction21c, [ "check-cast", KIND_TYPE ] ], 0x20 : [Instruction22c, [ "instance-of", KIND_TYPE ] ], 0x21 : [Instruction12x, [ "array-length", KIND_TYPE ] ], 0x22 : [Instruction21c, [ "new-instance", KIND_TYPE ] ], 0x23 : [Instruction22c, [ "new-array", KIND_TYPE ] ], 0x24 : [Instruction35c, [ "filled-new-array", KIND_TYPE ] ], 0x25 : [Instruction3rc, [ "filled-new-array/range", KIND_TYPE ] ], 0x26 : [Instruction31t, [ "fill-array-data" ] ], 0x27 : [Instruction11x, [ "throw" ] ], 0x28 : [Instruction10t, [ "goto" ] ], 0x29 : [Instruction20t, [ "goto/16" ] ], 0x2a : [Instruction30t, [ "goto/32" ] ], 0x2b : [Instruction31t, [ "packed-switch" ] ], 0x2c : [Instruction31t, [ "sparse-switch" ] ], 0x2d : [Instruction23x, [ "cmpl-float" ] ], 0x2e : [Instruction23x, [ "cmpg-float" ] ], 0x2f : [Instruction23x, [ "cmpl-double" ] ], 0x30 : [Instruction23x, [ "cmpg-double" ] ], 0x31 : [Instruction23x, [ "cmp-long" ] ], 0x32 : [Instruction22t, [ "if-eq" ] ], 0x33 : [Instruction22t, [ "if-ne" ] ], 0x34 : [Instruction22t, [ "if-lt" ] ], 0x35 : [Instruction22t, [ "if-ge" ] ], 0x36 : [Instruction22t, [ "if-gt" ] ], 0x37 : [Instruction22t, [ "if-le" ] ], 0x38 : [Instruction21t, [ "if-eqz" ] ], 0x39 : [Instruction21t, [ "if-nez" ] ], 0x3a : [Instruction21t, [ "if-ltz" ] ], 0x3b : [Instruction21t, [ "if-gez" ] ], 0x3c : [Instruction21t, [ "if-gtz" ] ], 0x3d : [Instruction21t, [ "if-lez" ] ], #unused 0x3e : [Instruction10x, [ "nop" ] ], 0x3f : [Instruction10x, [ "nop" ] ], 0x40 : [Instruction10x, [ "nop" ] ], 0x41 : [Instruction10x, [ "nop" ] ], 0x42 : [Instruction10x, [ "nop" ] ], 0x43 : [Instruction10x, [ "nop" ] ], 0x44 : [Instruction23x, [ "aget" ] ], 0x45 : [Instruction23x, [ "aget-wide" ] ], 0x46 : [Instruction23x, [ "aget-object" ] ], 0x47 : [Instruction23x, [ "aget-boolean" ] ], 0x48 : [Instruction23x, [ "aget-byte" ] ], 0x49 : [Instruction23x, [ "aget-char" ] ], 0x4a : [Instruction23x, [ "aget-short" ] ], 0x4b : [Instruction23x, [ "aput" ] ], 0x4c : [Instruction23x, [ "aput-wide" ] ], 0x4d : [Instruction23x, [ "aput-object" ] ], 0x4e : [Instruction23x, [ "aput-boolean" ] ], 0x4f : [Instruction23x, [ "aput-byte" ] ], 0x50 : [Instruction23x, [ "aput-char" ] ], 0x51 : [Instruction23x, [ "aput-short" ] ], 0x52 : [Instruction22c, [ "iget", KIND_FIELD ] ], 0x53 : [Instruction22c, [ "iget-wide", KIND_FIELD ] ], 0x54 : [Instruction22c, [ "iget-object", KIND_FIELD ] ], 0x55 : [Instruction22c, [ "iget-boolean", KIND_FIELD ] ], 0x56 : [Instruction22c, [ "iget-byte", KIND_FIELD ] ], 0x57 : [Instruction22c, [ "iget-char", KIND_FIELD ] ], 0x58 : [Instruction22c, [ "iget-short", KIND_FIELD ] ], 0x59 : [Instruction22c, [ "iput", KIND_FIELD ] ], 0x5a : [Instruction22c, [ "iput-wide", KIND_FIELD ] ], 0x5b : [Instruction22c, [ "iput-object", KIND_FIELD ] ], 0x5c : [Instruction22c, [ "iput-boolean", KIND_FIELD ] ], 0x5d : [Instruction22c, [ "iput-byte", KIND_FIELD ] ], 0x5e : [Instruction22c, [ "iput-char", KIND_FIELD ] ], 0x5f : [Instruction22c, [ "iput-short", KIND_FIELD ] ], 0x60 : [Instruction21c, [ "sget", KIND_FIELD ] ], 0x61 : [Instruction21c, [ "sget-wide", KIND_FIELD ] ], 0x62 : [Instruction21c, [ "sget-object", KIND_FIELD ] ], 0x63 : [Instruction21c, [ "sget-boolean", KIND_FIELD ] ], 0x64 : [Instruction21c, [ "sget-byte", KIND_FIELD ] ], 0x65 : [Instruction21c, [ "sget-char", KIND_FIELD ] ], 0x66 : [Instruction21c, [ "sget-short", KIND_FIELD ] ], 0x67 : [Instruction21c, [ "sput", KIND_FIELD ] ], 0x68 : [Instruction21c, [ "sput-wide", KIND_FIELD ] ], 0x69 : [Instruction21c, [ "sput-object", KIND_FIELD ] ], 0x6a : [Instruction21c, [ "sput-boolean", KIND_FIELD ] ], 0x6b : [Instruction21c, [ "sput-byte", KIND_FIELD ] ], 0x6c : [Instruction21c, [ "sput-char", KIND_FIELD ] ], 0x6d : [Instruction21c, [ "sput-short", KIND_FIELD ] ], 0x6e : [Instruction35c, [ "invoke-virtual", KIND_METH ] ], 0x6f : [Instruction35c, [ "invoke-super", KIND_METH ] ], 0x70 : [Instruction35c, [ "invoke-direct", KIND_METH ] ], 0x71 : [Instruction35c, [ "invoke-static", KIND_METH ] ], 0x72 : [Instruction35c, [ "invoke-interface", KIND_METH ] ], # unused 0x73 : [Instruction10x, [ "nop" ] ], 0x74 : [Instruction3rc, [ "invoke-virtual/range", KIND_METH ] ], 0x75 : [Instruction3rc, [ "invoke-super/range", KIND_METH ] ], 0x76 : [Instruction3rc, [ "invoke-direct/range", KIND_METH ] ], 0x77 : [Instruction3rc, [ "invoke-static/range", KIND_METH ] ], 0x78 : [Instruction3rc, [ "invoke-interface/range", KIND_METH ] ], # unused 0x79 : [Instruction10x, [ "nop" ] ], 0x7a : [Instruction10x, [ "nop" ] ], 0x7b : [Instruction12x, [ "neg-int" ] ], 0x7c : [Instruction12x, [ "not-int" ] ], 0x7d : [Instruction12x, [ "neg-long" ] ], 0x7e : [Instruction12x, [ "not-long" ] ], 0x7f : [Instruction12x, [ "neg-float" ] ], 0x80 : [Instruction12x, [ "neg-double" ] ], 0x81 : [Instruction12x, [ "int-to-long" ] ], 0x82 : [Instruction12x, [ "int-to-float" ] ], 0x83 : [Instruction12x, [ "int-to-double" ] ], 0x84 : [Instruction12x, [ "long-to-int" ] ], 0x85 : [Instruction12x, [ "long-to-float" ] ], 0x86 : [Instruction12x, [ "long-to-double" ] ], 0x87 : [Instruction12x, [ "float-to-int" ] ], 0x88 : [Instruction12x, [ "float-to-long" ] ], 0x89 : [Instruction12x, [ "float-to-double" ] ], 0x8a : [Instruction12x, [ "double-to-int" ] ], 0x8b : [Instruction12x, [ "double-to-long" ] ], 0x8c : [Instruction12x, [ "double-to-float" ] ], 0x8d : [Instruction12x, [ "int-to-byte" ] ], 0x8e : [Instruction12x, [ "int-to-char" ] ], 0x8f : [Instruction12x, [ "int-to-short" ] ], 0x90 : [Instruction23x, [ "add-int" ] ], 0x91 : [Instruction23x, [ "sub-int" ] ], 0x92 : [Instruction23x, [ "mul-int" ] ], 0x93 : [Instruction23x, [ "div-int" ] ], 0x94 : [Instruction23x, [ "rem-int" ] ], 0x95 : [Instruction23x, [ "and-int" ] ], 0x96 : [Instruction23x, [ "or-int" ] ], 0x97 : [Instruction23x, [ "xor-int" ] ], 0x98 : [Instruction23x, [ "shl-int" ] ], 0x99 : [Instruction23x, [ "shr-int" ] ], 0x9a : [Instruction23x, [ "ushr-int" ] ], 0x9b : [Instruction23x, [ "add-long" ] ], 0x9c : [Instruction23x, [ "sub-long" ] ], 0x9d : [Instruction23x, [ "mul-long" ] ], 0x9e : [Instruction23x, [ "div-long" ] ], 0x9f : [Instruction23x, [ "rem-long" ] ], 0xa0 : [Instruction23x, [ "and-long" ] ], 0xa1 : [Instruction23x, [ "or-long" ] ], 0xa2 : [Instruction23x, [ "xor-long" ] ], 0xa3 : [Instruction23x, [ "shl-long" ] ], 0xa4 : [Instruction23x, [ "shr-long" ] ], 0xa5 : [Instruction23x, [ "ushr-long" ] ], 0xa6 : [Instruction23x, [ "add-float" ] ], 0xa7 : [Instruction23x, [ "sub-float" ] ], 0xa8 : [Instruction23x, [ "mul-float" ] ], 0xa9 : [Instruction23x, [ "div-float" ] ], 0xaa : [Instruction23x, [ "rem-float" ] ], 0xab : [Instruction23x, [ "add-double" ] ], 0xac : [Instruction23x, [ "sub-double" ] ], 0xad : [Instruction23x, [ "mul-double" ] ], 0xae : [Instruction23x, [ "div-double" ] ], 0xaf : [Instruction23x, [ "rem-double" ] ], 0xb0 : [Instruction12x, [ "add-int/2addr" ] ], 0xb1 : [Instruction12x, [ "sub-int/2addr" ] ], 0xb2 : [Instruction12x, [ "mul-int/2addr" ] ], 0xb3 : [Instruction12x, [ "div-int/2addr" ] ], 0xb4 : [Instruction12x, [ "rem-int/2addr" ] ], 0xb5 : [Instruction12x, [ "and-int/2addr" ] ], 0xb6 : [Instruction12x, [ "or-int/2addr" ] ], 0xb7 : [Instruction12x, [ "xor-int/2addr" ] ], 0xb8 : [Instruction12x, [ "shl-int/2addr" ] ], 0xb9 : [Instruction12x, [ "shr-int/2addr" ] ], 0xba : [Instruction12x, [ "ushr-int/2addr" ] ], 0xbb : [Instruction12x, [ "add-long/2addr" ] ], 0xbc : [Instruction12x, [ "sub-long/2addr" ] ], 0xbd : [Instruction12x, [ "mul-long/2addr" ] ], 0xbe : [Instruction12x, [ "div-long/2addr" ] ], 0xbf : [Instruction12x, [ "rem-long/2addr" ] ], 0xc0 : [Instruction12x, [ "and-long/2addr" ] ], 0xc1 : [Instruction12x, [ "or-long/2addr" ] ], 0xc2 : [Instruction12x, [ "xor-long/2addr" ] ], 0xc3 : [Instruction12x, [ "shl-long/2addr" ] ], 0xc4 : [Instruction12x, [ "shr-long/2addr" ] ], 0xc5 : [Instruction12x, [ "ushr-long/2addr" ] ], 0xc6 : [Instruction12x, [ "add-float/2addr" ] ], 0xc7 : [Instruction12x, [ "sub-float/2addr" ] ], 0xc8 : [Instruction12x, [ "mul-float/2addr" ] ], 0xc9 : [Instruction12x, [ "div-float/2addr" ] ], 0xca : [Instruction12x, [ "rem-float/2addr" ] ], 0xcb : [Instruction12x, [ "add-double/2addr" ] ], 0xcc : [Instruction12x, [ "sub-double/2addr" ] ], 0xcd : [Instruction12x, [ "mul-double/2addr" ] ], 0xce : [Instruction12x, [ "div-double/2addr" ] ], 0xcf : [Instruction12x, [ "rem-double/2addr" ] ], 0xd0 : [Instruction22s, [ "add-int/lit16" ] ], 0xd1 : [Instruction22s, [ "rsub-int" ] ], 0xd2 : [Instruction22s, [ "mul-int/lit16" ] ], 0xd3 : [Instruction22s, [ "div-int/lit16" ] ], 0xd4 : [Instruction22s, [ "rem-int/lit16" ] ], 0xd5 : [Instruction22s, [ "and-int/lit16" ] ], 0xd6 : [Instruction22s, [ "or-int/lit16" ] ], 0xd7 : [Instruction22s, [ "xor-int/lit16" ] ], 0xd8 : [Instruction22b, [ "add-int/lit8" ] ], 0xd9 : [Instruction22b, [ "rsub-int/lit8" ] ], 0xda : [Instruction22b, [ "mul-int/lit8" ] ], 0xdb : [Instruction22b, [ "div-int/lit8" ] ], 0xdc : [Instruction22b, [ "rem-int/lit8" ] ], 0xdd : [Instruction22b, [ "and-int/lit8" ] ], 0xde : [Instruction22b, [ "or-int/lit8" ] ], 0xdf : [Instruction22b, [ "xor-int/lit8" ] ], 0xe0 : [Instruction22b, [ "shl-int/lit8" ] ], 0xe1 : [Instruction22b, [ "shr-int/lit8" ] ], 0xe2 : [Instruction22b, [ "ushr-int/lit8" ] ], # unused 0xe3 : [Instruction10x, [ "nop" ] ], 0xe4 : [Instruction10x, [ "nop" ] ], 0xe5 : [Instruction10x, [ "nop" ] ], 0xe6 : [Instruction10x, [ "nop" ] ], 0xe7 : [Instruction10x, [ "nop" ] ], 0xe8 : [Instruction10x, [ "nop" ] ], 0xe9 : [Instruction10x, [ "nop" ] ], 0xea : [Instruction10x, [ "nop" ] ], 0xeb : [Instruction10x, [ "nop" ] ], 0xec : [Instruction10x, [ "nop" ] ], 0xed : [Instruction10x, [ "nop" ] ], 0xee : [Instruction10x, [ "nop" ] ], 0xef : [Instruction10x, [ "nop" ] ], 0xf0 : [Instruction10x, [ "nop" ] ], 0xf1 : [Instruction10x, [ "nop" ] ], 0xf2 : [Instruction10x, [ "nop" ] ], 0xf3 : [Instruction10x, [ "nop" ] ], 0xf4 : [Instruction10x, [ "nop" ] ], 0xf5 : [Instruction10x, [ "nop" ] ], 0xf6 : [Instruction10x, [ "nop" ] ], 0xf7 : [Instruction10x, [ "nop" ] ], 0xf8 : [Instruction10x, [ "nop" ] ], 0xf9 : [Instruction10x, [ "nop" ] ], 0xfa : [Instruction10x, [ "nop" ] ], 0xfb : [Instruction10x, [ "nop" ] ], 0xfc : [Instruction10x, [ "nop" ] ], 0xfd : [Instruction10x, [ "nop" ] ], 0xfe : [Instruction10x, [ "nop" ] ], } def get_instruction(cm, op_value, buff) : #print "Parsing instruction %x" % op_value return DALVIK_OPCODES_FORMAT[ op_value ][0]( cm, buff, DALVIK_OPCODES_FORMAT[ op_value ][1:] ) def get_instruction_payload(op_value, buff) : #print "Parsing instruction payload %x" % op_value return DALVIK_OPCODES_PAYLOAD[ op_value ][0]( buff ) class DCode : def __init__(self, class_manager, size, buff) : self.__CM = class_manager self.__insn = buff self.bytecodes = [] #print "New method ....", size * calcsize( '<H' ) # Get instructions idx = 0 while idx < (size * calcsize( '<H' )) : obj = None #print "idx = %x" % idx op_value = unpack( '=B', self.__insn[idx] )[0] #print "First %x" % op_value if op_value in DALVIK_OPCODES_FORMAT : if op_value == 0x00 or op_value == 0xff: op_value = unpack( '=H', self.__insn[idx:idx+2] )[0] #print "Second %x" % op_value if op_value in DALVIK_OPCODES_PAYLOAD : obj = get_instruction_payload( op_value, self.__insn[idx:] ) elif op_value in DALVIK_OPCODES_EXPANDED : raise("ooo") else : op_value = unpack( '=B', self.__insn[idx] )[0] obj = get_instruction( self.__CM, op_value, self.__insn[idx:] ) else : op_value = unpack( '=B', self.__insn[idx] )[0] obj = get_instruction( self.__CM, op_value, self.__insn[idx:] ) self.bytecodes.append( obj ) idx = idx + obj.get_length() def reload(self) : pass def get(self) : return self.bytecodes def add_inote(self, msg, idx, off=None) : if off != None : idx = self.off_to_pos(off) self.bytecodes[ idx ].add_note(msg) def get_instruction(self, idx, off=None) : if off != None : idx = self.off_to_pos(off) return self.bytecodes[idx] def off_to_pos(self, off) : idx = 0 nb = 0 for i in self.bytecodes : if idx == off : return nb nb += 1 idx += i.get_length() return -1 def get_ins_off(self, off) : idx = 0 for i in self.bytecodes : if idx == off : return i idx += i.get_length() return None def show(self) : nb = 0 idx = 0 for i in self.bytecodes : print nb, "0x%x" % idx, i.show(nb) print idx += i.get_length() nb += 1 def pretty_show(self, m_a) : bytecode.PrettyShow( m_a.basic_blocks.gets() ) bytecode.PrettyShowEx( m_a.exceptions.gets() ) def get_raw(self) : return ''.join(i.get_raw() for i in self.bytecodes) class TryItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.item = SVs( TRY_ITEM[0], TRY_ITEM[1], buff.read( calcsize(TRY_ITEM[0]) ) ) def get_start_addr(self) : return self.item.get_value().start_addr def get_insn_count(self) : return self.item.get_value().insn_count def get_handler_off(self) : return self.item.get_value().handler_off def get_off(self) : return self.__offset.off def get_raw(self) : return self.item.get_value_buff() class DalvikCode : def __init__(self, buff, cm) : self.__CM = cm off = buff.get_idx() while off % 4 != 0 : off += 1 buff.set_idx( off ) self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.__off = buff.get_idx() self.registers_size = SV( '=H', buff.read( 2 ) ) self.ins_size = SV( '=H', buff.read( 2 ) ) self.outs_size = SV( '=H', buff.read( 2 ) ) self.tries_size = SV( '=H', buff.read( 2 ) ) self.debug_info_off = SV( '=L', buff.read( 4 ) ) self.insns_size = SV( '=L', buff.read( 4 ) ) ushort = calcsize( '=H' ) self.code = DCode( self.__CM, self.insns_size.get_value(), buff.read( self.insns_size.get_value() * ushort ) ) if (self.insns_size.get_value() % 2 == 1) : self.__padding = SV( '=H', buff.read( 2 ) ) self.tries = [] self.handlers = None if self.tries_size.get_value() > 0 : for i in range(0, self.tries_size.get_value()) : self.tries.append( TryItem( buff, self.__CM ) ) self.handlers = EncodedCatchHandlerList( buff, self.__CM ) def reload(self) : self.code.reload() def get_length(self) : return self.insns_size.get_value() def get_bc(self) : return self.code def get_off(self) : return self.__off def _begin_show(self) : bytecode._PrintBanner() def show(self) : self._begin_show() self.code.show() self._end_show() def _end_show(self) : bytecode._PrintBanner() def pretty_show(self, m_a) : self._begin_show() self.code.pretty_show(m_a) self._end_show() def get_obj(self) : return [ i for i in self.__handlers ] def get_raw(self) : buff = self.registers_size.get_value_buff() + \ self.ins_size.get_value_buff() + \ self.outs_size.get_value_buff() + \ self.tries_size.get_value_buff() + \ self.debug_info_off.get_value_buff() + \ self.insns_size.get_value_buff() + \ self.code.get_raw() if (self.insns_size.get_value() % 2 == 1) : buff += self.__padding.get_value_buff() if self.tries_size.get_value() > 0 : buff += ''.join(i.get_raw() for i in self.tries) buff += self.handlers.get_raw() return bytecode.Buff( self.__offset.off, buff ) def get_tries_size(self) : return self.tries_size.get_value() def get_handlers(self) : return self.handlers def get_tries(self) : return self.tries def add_inote(self, msg, idx, off=None) : if self.code : return self.code.add_inote(msg, idx, off) def get_instruction(self, idx, off=None) : if self.code : return self.code.get_instruction(idx, off) class CodeItem : def __init__(self, size, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.code = [] self.__code_off = {} for i in range(0, size) : x = DalvikCode( buff, cm ) self.code.append( x ) self.__code_off[ x.get_off() ] = x def get_code(self, off) : try : return self.__code_off[off] except KeyError : return None def reload(self) : for i in self.code : i.reload() def show(self) : print "CODE_ITEM" for i in self.code : i.show() def get_obj(self) : return [ i for i in self.code ] def get_raw(self) : return [ i.get_raw() for i in self.code ] def get_off(self) : return self.__offset.off class MapItem : def __init__(self, buff, cm) : self.__CM = cm self.__offset = self.__CM.add_offset( buff.get_idx(), self ) self.format = SVs( MAP_ITEM[0], MAP_ITEM[1], buff.read( calcsize( MAP_ITEM[0] ) ) ) self.item = None general_format = self.format.get_value() buff.set_idx( general_format.offset ) # print TYPE_MAP_ITEM[ general_format.type ], "@ 0x%x(%d) %d %d" % (buff.get_idx(), buff.get_idx(), general_format.size, general_format.offset) if TYPE_MAP_ITEM[ general_format.type ] == "TYPE_STRING_ID_ITEM" : self.item = [ StringIdItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_CODE_ITEM" : self.item = CodeItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_TYPE_ID_ITEM" : self.item = TypeIdItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_PROTO_ID_ITEM" : self.item = ProtoIdItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_FIELD_ID_ITEM" : self.item = FieldIdItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_METHOD_ID_ITEM" : self.item = MethodIdItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_CLASS_DEF_ITEM" : self.item = ClassDefItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_HEADER_ITEM" : self.item = HeaderItem( general_format.size, buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_ANNOTATION_ITEM" : self.item = [ AnnotationItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_ANNOTATION_SET_ITEM" : self.item = [ AnnotationSetItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_ANNOTATIONS_DIRECTORY_ITEM" : self.item = [ AnnotationsDirectoryItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_ANNOTATION_SET_REF_LIST" : self.item = [ AnnotationSetRefList( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_TYPE_LIST" : self.item = [ TypeList( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_STRING_DATA_ITEM" : self.item = [ StringDataItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_DEBUG_INFO_ITEM" : # FIXME : strange bug with sleb128 .... # self.item = [ DebugInfoItem( buff, cm ) for i in range(0, general_format.size) ] self.item = DebugInfoItem2( buff, cm ) elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_ENCODED_ARRAY_ITEM" : self.item = [ EncodedArrayItem( buff, cm ) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_CLASS_DATA_ITEM" : self.item = [ ClassDataItem(buff, cm) for i in range(0, general_format.size) ] elif TYPE_MAP_ITEM[ general_format.type ] == "TYPE_MAP_LIST" : pass # It's me I think !!! else : bytecode.Exit( "Map item %d @ 0x%x(%d) is unknown" % (general_format.type, buff.get_idx(), buff.get_idx()) ) def reload(self) : if self.item != None : if isinstance( self.item, list ): for i in self.item : i.reload() else : self.item.reload() def show(self) : bytecode._Print( "MAP_ITEM", self.format ) bytecode._Print( "\tTYPE_ITEM", TYPE_MAP_ITEM[ self.format.get_value().type ]) if self.item != None : if isinstance( self.item, list ): for i in self.item : i.show() else : if isinstance(self.item, CodeItem) == False : self.item.show() def pretty_show(self) : bytecode._Print( "MAP_ITEM", self.format ) bytecode._Print( "\tTYPE_ITEM", TYPE_MAP_ITEM[ self.format.get_value().type ]) if self.item != None : if isinstance( self.item, list ): for i in self.item : if isinstance(i, ClassDataItem) : i.pretty_show() elif isinstance(self.item, CodeItem) == False : i.show() else : if isinstance(self.item, ClassDataItem) : self.item.pretty_show() elif isinstance(self.item, CodeItem) == False : self.item.show() def get_obj(self) : if self.item == None : return [] if isinstance( self.item, list ) : return [ i for i in self.item ] return [ self.item ] def get_raw(self) : if self.item == None : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] else : if isinstance( self.item, list ) : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] + [ i.get_raw() for i in self.item ] else : return [ bytecode.Buff( self.__offset.off, self.format.get_value_buff() ) ] + self.item.get_raw() def get_length(self) : return calcsize( MAP_ITEM[0] ) def get_type(self) : return self.format.get_value().type def get_item(self) : return self.item class OffObj : def __init__(self, o) : self.off = o class ClassManager : def __init__(self) : self.decompiler_ob = None self.vmanalysis_ob = None self.gvmanalysis_ob = None self.__manage_item = {} self.__manage_item_off = [] self.__offsets = {} self.__strings_off = {} self.__cached_type_list = {} self.__cached_proto = {} self.recode_ascii_string = CONF["RECODE_ASCII_STRING"] self.recode_ascii_string_meth = CONF["RECODE_ASCII_STRING_METH"] self.hook_strings = {} self.engine = [] if CONF["ENGINE"] == "automatic" : try : from androguard.core.bytecodes.libdvm import dvmnative self.engine.append("native") self.engine.append( dvmnative.DalvikBytecode() ) except ImportError : self.engine.append("python") else : self.engine.append("python") def get_vmanalysis(self) : return self.vmanalysis_ob def set_vmanalysis(self, vmanalysis) : self.vmanalysis_ob = vmanalysis def get_gvmanalysis(self) : return self.gvmanalysis_ob def set_gvmanalysis(self, gvmanalysis) : self.gvmanalysis_ob = gvmanalysis def set_decompiler(self, decompiler) : self.decompiler_ob = decompiler def get_engine(self) : return self.engine[0] def get_all_engine(self) : return self.engine def add_offset(self, off, obj) : #print "%x" % off, obj x = OffObj( off ) self.__offsets[ obj ] = x return x def add_type_item(self, type_item, item) : self.__manage_item[ type_item ] = item sdi = False if type_item == "TYPE_STRING_DATA_ITEM" : sdi = True if item != None : if isinstance(item, list) : for i in item : goff = i.get_off() self.__manage_item_off.append( goff ) if sdi == True : self.__strings_off[ goff ] = i else : self.__manage_item_off.append( item.get_off() ) def get_code(self, idx) : try : return self.__manage_item[ "TYPE_CODE_ITEM" ].get_code( idx ) except KeyError : return None def get_class_data_item(self, off) : for i in self.__manage_item[ "TYPE_CLASS_DATA_ITEM" ] : if i.get_off() == off : return i bytecode.Exit( "unknown class data item @ 0x%x" % off ) def get_encoded_array_item(self, off) : for i in self.__manage_item["TYPE_ENCODED_ARRAY_ITEM" ] : if i.get_off() == off : return i def get_string(self, idx) : if idx in self.hook_strings : return self.hook_strings[ idx ] off = self.__manage_item[ "TYPE_STRING_ID_ITEM" ][idx].get_data_off() try : if self.recode_ascii_string : return self.recode_ascii_string_meth( self.__strings_off[off].get() ) return self.__strings_off[off].get() except KeyError : bytecode.Warning( "unknown string item @ 0x%x(%d)" % (off,idx) ) return "" def get_raw_string(self, idx) : off = self.__manage_item[ "TYPE_STRING_ID_ITEM" ][idx].get_data_off() try : return self.__strings_off[off].get() except KeyError : bytecode.Warning( "unknown string item @ 0x%x(%d)" % (off,idx) ) return "" def get_type_list(self, off) : if off == 0 : return "()" if off in self.__cached_type_list : return self.__cached_type_list[ off ] for i in self.__manage_item[ "TYPE_TYPE_LIST" ] : if i.get_type_list_off() == off : ret = "(" + i.get_string() + ")" self.__cached_type_list[ off ] = ret return ret return None def get_type(self, idx) : _type = self.__manage_item[ "TYPE_TYPE_ID_ITEM" ].get( idx ) return self.get_string( _type ) def get_type_ref(self, idx) : return self.__manage_item[ "TYPE_TYPE_ID_ITEM" ].get( idx ) def get_proto(self, idx) : try : proto = self.__cached_proto[ idx ] except KeyError : proto = self.__manage_item[ "TYPE_PROTO_ID_ITEM" ].get( idx ) self.__cached_proto[ idx ] = proto return [ proto.get_params(), proto.get_return_type() ] def get_field(self, idx) : field = self.__manage_item[ "TYPE_FIELD_ID_ITEM"].get( idx ) return [ field.get_class(), field.get_type(), field.get_name() ] def get_field_ref(self, idx) : return self.__manage_item[ "TYPE_FIELD_ID_ITEM"].get( idx ) def get_method(self, idx) : method = self.__manage_item[ "TYPE_METHOD_ID_ITEM" ].get( idx ) return method.get_list() def get_method_ref(self, idx) : return self.__manage_item[ "TYPE_METHOD_ID_ITEM" ].get( idx ) def set_hook_method_class_name(self, idx, value) : method = self.__manage_item[ "TYPE_METHOD_ID_ITEM" ].get( idx ) _type = self.__manage_item[ "TYPE_TYPE_ID_ITEM" ].get( method.format.get_value().class_idx ) self.set_hook_string( _type, value ) method.reload() def set_hook_method_name(self, idx, value) : method = self.__manage_item[ "TYPE_METHOD_ID_ITEM" ].get( idx ) self.set_hook_string( method.format.get_value().name_idx, value ) method.reload() def set_hook_string(self, idx, value) : self.hook_strings[ idx ] = value def get_next_offset_item(self, idx) : for i in self.__manage_item_off : if i > idx : return i return idx class MapList : def __init__(self, cm, off, buff) : self.CM = cm buff.set_idx( off ) self.__offset = self.CM.add_offset( buff.get_idx(), self ) self.size = SV( '=L', buff.read( 4 ) ) self.map_item = [] for i in range(0, self.size) : idx = buff.get_idx() mi = MapItem( buff, self.CM ) self.map_item.append( mi ) buff.set_idx( idx + mi.get_length() ) self.CM.add_type_item( TYPE_MAP_ITEM[ mi.get_type() ], mi.get_item() ) for i in self.map_item : i.reload() def get_item_type(self, ttype) : for i in self.map_item : if TYPE_MAP_ITEM[ i.get_type() ] == ttype : return i.get_item() def show(self) : bytecode._Print("MAP_LIST SIZE", self.size.get_value()) for i in self.map_item : i.show() def pretty_show(self) : bytecode._Print("MAP_LIST SIZE", self.size.get_value()) for i in self.map_item : i.pretty_show() def get_obj(self) : return [ x for x in self.map_item ] def get_raw(self) : return [ bytecode.Buff( self.__offset.off, self.size.get_value_buff()) ] + \ [ x.get_raw() for x in self.map_item ] def get_class_manager(self) : return self.CM class DalvikVMFormat(bytecode._Bytecode) : def __init__(self, buff, decompiler=None) : super(DalvikVMFormat, self).__init__( buff ) self.CM = ClassManager() self.CM.set_decompiler( decompiler ) self.__header = HeaderItem( 0, self, ClassManager() ) if self.__header.get_value().map_off == 0 : bytecode.Warning( "no map list ..." ) else : self.map_list = MapList( self.CM, self.__header.get_value().map_off, self ) self.classes = self.map_list.get_item_type( "TYPE_CLASS_DEF_ITEM" ) self.methods = self.map_list.get_item_type( "TYPE_METHOD_ID_ITEM" ) self.fields = self.map_list.get_item_type( "TYPE_FIELD_ID_ITEM" ) self.codes = self.map_list.get_item_type( "TYPE_CODE_ITEM" ) self.strings = self.map_list.get_item_type( "TYPE_STRING_DATA_ITEM" ) self.classes_names = None self.__cache_methods = None def get_class_manager(self) : return self.CM def show(self) : """Show the .class format into a human readable format""" self.map_list.show() def save(self) : """ Return the dex (with the modifications) into raw format @rtype: string """ l = self.map_list.get_raw() result = list(self._iterFlatten( l )) result = sorted(result, key=lambda x: x.offset) idx = 0 buff = "" for i in result : # print idx, i.offset, "--->", i.offset + i.size if idx == i.offset : buff += i.buff else : # print "PATCH @ 0x%x %d" % (idx, (i.offset - idx)) buff += '\x00' * (i.offset - idx) buff += i.buff idx += (i.offset - idx) idx += i.size return self.fix_checksums(buff) def fix_checksums(self, buff) : import zlib, hashlib checksum = zlib.adler32(buff[12:]) buff = buff[:8] + pack("=i", checksum) + buff[12:] signature = hashlib.sha1(buff[32:]).digest() buff = buff[:12] + signature + buff[32:] return buff def dotbuff(self, ins, idx) : return dot_buff(ins, idx) def pretty_show(self) : self.map_list.pretty_show() def _iterFlatten(self, root): if isinstance(root, (list, tuple)): for element in root : for e in self._iterFlatten(element) : yield e else: yield root def _Exp(self, x) : l = [] for i in x : l.append(i) l.append( self._Exp( i.get_obj() ) ) return l def get_cm_field(self, idx) : return self.CM.get_field(idx) def get_cm_method(self, idx) : return self.CM.get_method(idx) def get_cm_string(self, idx) : return self.CM.get_raw_string( idx ) def get_cm_type(self, idx) : return self.CM.get_type( idx ) def get_classes_names(self) : """ Return the names of classes """ if self.classes_names == None : self.classes_names = [ i.get_name() for i in self.classes.class_def ] return self.classes_names def get_classes(self) : return self.classes.class_def def get_method(self, name) : """Return into a list all methods which corresponds to the regexp @param name : the name of the method (a regexp) """ prog = re.compile(name) l = [] for i in self.classes.class_def : for j in i.get_methods() : if prog.match( j.get_name() ) : l.append( j ) return l def get_field(self, name) : """Return into a list all fields which corresponds to the regexp @param name : the name of the field (a regexp) """ prog = re.compile(name) l = [] for i in self.classes.class_def : for j in i.get_fields() : if prog.match( j.get_name() ) : l.append( j ) return l def get_all_fields(self) : try : return self.fields.gets() except AttributeError : return [] def get_fields(self) : """Return all objects fields""" l = [] for i in self.classes.class_def : for j in i.get_fields() : l.append( j ) return l def get_methods(self) : """Return all objects methods""" l = [] for i in self.classes.class_def : for j in i.get_methods() : l.append( j ) return l def get_len_methods(self) : return len( self.get_methods() ) def get_method_descriptor(self, class_name, method_name, descriptor) : """ Return the specific method @param class_name : the class name of the method @param method_name : the name of the method @param descriptor : the descriptor of the method """ key = class_name + method_name + descriptor if self.__cache_methods == None : self.__cache_methods = {} for i in self.classes.class_def : for j in i.get_methods() : self.__cache_methods[ j.get_class_name() + j.get_name() + j.get_descriptor() ] = j try : return self.__cache_methods[ key ] except KeyError : return None def get_methods_class(self, class_name) : """ Return methods of a class @param class_name : the class name """ l = [] for i in self.classes.class_def : for j in i.get_methods() : if class_name == j.get_class_name() : l.append( j ) return l def get_fields_class(self, class_name) : """ Return fields of a class @param class_name : the class name """ l = [] for i in self.classes.class_def : for j in i.get_fields() : if class_name == j.get_class_name() : l.append( j ) return l def get_field_descriptor(self, class_name, field_name, descriptor) : """ Return the specific field @param class_name : the class name of the field @param field_name : the name of the field @param descriptor : the descriptor of the field """ for i in self.classes.class_def : if class_name == i.get_name() : for j in i.get_fields() : if field_name == j.get_name() and descriptor == j.get_descriptor() : return j return None def get_class_manager(self) : """ Return directly the class manager @rtype : L{ClassManager} """ return self.map_list.get_class_manager() def get_strings(self) : """ Return all strings """ return [i.get() for i in self.strings] def get_regex_strings(self, regular_expressions) : """ Return all taget strings matched the regex in input """ str_list = [] if regular_expressions.count is None : return None for i in self.get_strings() : if re.match(regular_expressions, i) : str_list.append(i) return str_list def get_type(self) : return "DVM" def get_BRANCH_DVM_OPCODES(self) : return BRANCH_DVM_OPCODES def get_determineNext(self) : return determineNext def get_determineException(self) : return determineException def get_DVM_TOSTRING(self) : return DVM_TOSTRING() def set_decompiler(self, decompiler) : self.CM.set_decompiler( decompiler ) def set_vmanalysis(self, vmanalysis) : self.CM.set_vmanalysis( vmanalysis ) def set_gvmanalysis(self, gvmanalysis) : self.CM.set_gvmanalysis( gvmanalysis ) def create_xref(self, python_export=True) : gvm = self.CM.get_gvmanalysis() for _class in self.get_classes() : for method in _class.get_methods() : method.XREFfrom = XREF() method.XREFto = XREF() key = "%s %s %s" % (method.get_class_name(), method.get_name(), method.get_descriptor()) if key in gvm.nodes : for i in gvm.G.predecessors( gvm.nodes[ key ].id ) : xref = gvm.nodes_id[ i ] xref_meth = self.get_method_descriptor( xref.class_name, xref.method_name, xref.descriptor) if xref_meth != None : name = FormatClassToPython( xref_meth.get_class_name() ) + "__" + FormatNameToPython( xref_meth.get_name() ) + "__" + FormatDescriptorToPython( xref_meth.get_descriptor() ) if python_export == True : setattr( method.XREFfrom, name, xref_meth ) method.XREFfrom.add( xref_meth, xref.edges[ gvm.nodes[ key ] ] ) for i in gvm.G.successors( gvm.nodes[ key ].id ) : xref = gvm.nodes_id[ i ] xref_meth = self.get_method_descriptor( xref.class_name, xref.method_name, xref.descriptor) if xref_meth != None : name = FormatClassToPython( xref_meth.get_class_name() ) + "__" + FormatNameToPython( xref_meth.get_name() ) + "__" + FormatDescriptorToPython( xref_meth.get_descriptor() ) if python_export == True : setattr( method.XREFto, name, xref_meth ) method.XREFto.add( xref_meth, gvm.nodes[ key ].edges[ xref ] ) def create_dref(self, python_export=True) : vmx = self.CM.get_vmanalysis() for _class in self.get_classes() : for field in _class.get_fields() : field.DREFr = DREF() field.DREFw = DREF() paths = vmx.tainted_variables.get_field( field.get_class_name(), field.get_name(), field.get_descriptor() ) if paths != None : access = {} access["R"] = {} access["W"] = {} for path in paths.get_paths() : if path.get_access_flag() == 'R' : method_class_name = path.get_method().get_class_name() method_name = path.get_method().get_name() method_descriptor = path.get_method().get_descriptor() dref_meth = self.get_method_descriptor( method_class_name, method_name, method_descriptor ) name = FormatClassToPython( dref_meth.get_class_name() ) + "__" + FormatNameToPython( dref_meth.get_name() ) + "__" + FormatDescriptorToPython( dref_meth.get_descriptor() ) if python_export == True : setattr( field.DREFr, name, dref_meth ) try : access["R"][ path.get_method() ].append( path ) except KeyError : access["R"][ path.get_method() ] = [] access["R"][ path.get_method() ].append( path ) else : method_class_name = path.get_method().get_class_name() method_name = path.get_method().get_name() method_descriptor = path.get_method().get_descriptor() dref_meth = self.get_method_descriptor( method_class_name, method_name, method_descriptor ) name = FormatClassToPython( dref_meth.get_class_name() ) + "__" + FormatNameToPython( dref_meth.get_name() ) + "__" + FormatDescriptorToPython( dref_meth.get_descriptor() ) if python_export == True : setattr( field.DREFw, name, dref_meth ) try : access["W"][ path.get_method() ].append( path ) except KeyError : access["W"][ path.get_method() ] = [] access["W"][ path.get_method() ].append( path ) for i in access["R"] : field.DREFr.add( i, access["R"][i] ) for i in access["W"] : field.DREFw.add( i, access["W"][i] ) class XREF : def __init__(self) : self.items = [] def add(self, x, y): self.items.append((x, y)) class DREF : def __init__(self) : self.items = [] def add(self, x, y): self.items.append((x, y))
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from networkx import DiGraph import os from xml.sax.saxutils import escape from androguard.core.analysis import analysis try : from androguard.core.analysis.libsign.libsign import entropy except ImportError : import math def entropy(data): entropy = 0 if len(data) == 0 : return entropy for x in range(256): p_x = float(data.count(chr(x)))/len(data) if p_x > 0: entropy += - p_x*math.log(p_x, 2) return entropy DEFAULT_SIGNATURE = analysis.SIGNATURE_L0_4 def create_entropies(vmx, m) : try : default_signature = vmx.get_method_signature(m, predef_sign = DEFAULT_SIGNATURE).get_string() l = [ default_signature, entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Landroid"] } } ).get_string() ), entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Ljava"] } } ).get_string() ), entropy( vmx.get_method_signature(m, "hex" ).get_string() ), entropy( vmx.get_method_signature(m, "L2" ).get_string() ), ] return l except KeyError : return [ "", 0.0, 0.0, 0.0, 0.0 ] def create_info(vmx, m) : E = create_entropies(vmx, m) H = {} H["signature"] = E[0] H["signature_entropy"] = entropy( E[0] ) H["android_api_entropy"] = E[1] H["java_api_entropy"] = E[2] H["hex_entropy"] = E[3] H["exceptions_entropy"] = E[4] return H class Data : def __init__(self, vm, vmx, gvmx, a=None) : self.vm = vm self.vmx = vmx self.gvmx = gvmx self.a = a self.apk_data = None self.dex_data = None if self.a != None : self.apk_data = ApkViewer( self.a ) self.dex_data = DexViewer( vm, vmx, gvmx ) self.gvmx.set_new_attributes( create_info ) self.export_methods_to_gml() def export_methodcalls_to_gml(self) : return self.gvmx.export_to_gml() def export_methods_to_gml(self) : print self.gvmx.G for node in self.gvmx.G.nodes() : print self.gvmx.nodes_id[ node ].method_name, self.gvmx.nodes_id[ node ].get_attributes() def export_apk_to_gml(self) : if self.apk_data != None : return self.apk_data.export_to_gml() def export_dex_to_gml(self) : if self.dex_data != None : return self.dex_data.export_to_gml() class DexViewer : def __init__(self, vm, vmx, gvmx) : self.vm = vm self.vmx = vmx self.gvmx = gvmx def _create_node(self, id, height, width, color, label) : buff = "<node id=\"%d\">\n" % id buff += "<data key=\"d6\">\n" buff += "<y:ShapeNode>\n" buff += "<y:Geometry height=\"%f\" width=\"%f\"/>\n" % (16 * height, 7.5 * width) buff += "<y:Fill color=\"#%s\" transparent=\"false\"/>\n" % color buff += "<y:NodeLabel alignment=\"left\" autoSizePolicy=\"content\" fontFamily=\"Dialog\" fontSize=\"13\" fontStyle=\"plain\" hasBackgroundColor=\"false\" hasLineColor=\"false\" modelName=\"internal\" modelPosition=\"c\" textColor=\"#000000\" visible=\"true\">\n" buff += escape(label) buff += "</y:NodeLabel>\n" buff += "</y:ShapeNode>\n" buff += "</data>\n" buff += "</node>\n" return buff def add_exception_node(self, exception, id_i) : buff = "" # 9933FF height = 2 width = 0 label = "" label += "%x:%x\n" % (exception.start, exception.end) for i in exception.exceptions : c_label = "\t(%s -> %x %s)\n" % (i[0], i[1], i[2].get_name()) label += c_label width = max(len(c_label), width) height += 1 return self._create_node( id_i, height, width, "9333FF", label ) def add_method_node(self, i, id_i) : height = 0 width = 0 label = "" label += i.get_name() + "\n" label += i.get_descriptor() height = 3 width = len(label) return self._create_node( id_i, height, width, "FF0000", label ) def add_node(self, i, id_i) : height = 0 width = 0 idx = i.start label = "" for ins in i.ins : c_label = "%x %s\n" % (idx, self.vm.dotbuff(ins, idx)) idx += ins.get_length() label += c_label width = max(width, len(c_label)) height += 1 if height < 10 : height += 3 return self._create_node( id_i, height, width, "FFCC00", label ) def add_edge(self, i, id_i, j, id_j, l_eid, val) : buff = "<edge id=\"%d\" source=\"%d\" target=\"%d\">\n" % (len(l_eid), id_i, id_j) buff += "<data key=\"d9\">\n" buff += "<y:PolyLineEdge>\n" buff += "<y:Arrows source=\"none\" target=\"standard\"/>\n" if val == 0 : buff += "<y:LineStyle color=\"#00FF00\" type=\"line\" width=\"1.0\"/>\n" elif val == 1 : buff += "<y:LineStyle color=\"#FF0000\" type=\"line\" width=\"1.0\"/>\n" else : buff += "<y:LineStyle color=\"#0000FF\" type=\"line\" width=\"1.0\"/>\n" buff += "</y:PolyLineEdge>\n" buff += "</data>\n" buff += "</edge>\n" l_eid[ "%d+%d" % (id_i, id_j) ] = len(l_eid) return buff def new_id(self, i, l) : try : return l[i] except KeyError : l[i] = len(l) return l[i] def export_to_gml(self) : H = {} for _class in self.vm.get_classes() : name = _class.get_name() name = name[1:-1] buff = "" buff += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" buff += "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:y=\"http://www.yworks.com/xml/graphml\" xmlns:yed=\"http://www.yworks.com/xml/yed/3\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd\">\n" buff += "<key attr.name=\"description\" attr.type=\"string\" for=\"node\" id=\"d5\"/>\n" buff += "<key for=\"node\" id=\"d6\" yfiles.type=\"nodegraphics\"/>\n" buff += "<key for=\"edge\" id=\"d9\" yfiles.type=\"edgegraphics\"/>\n" buff += "<graph edgedefault=\"directed\" id=\"G\">\n" print name buff_nodes = "" buff_edges = "" l_id = {} l_eid = {} for method in _class.get_methods() : mx = self.vmx.get_method( method ) exceptions = mx.exceptions id_method = self.new_id(method, l_id) buff_nodes += self.add_method_node(method, id_method) for i in mx.basic_blocks.get() : id_i = self.new_id(i, l_id) print i, id_i, i.exception_analysis buff_nodes += self.add_node( i, id_i ) # add childs nodes val = 0 if len(i.childs) > 1 : val = 1 elif len(i.childs) == 1 : val = 2 for j in i.childs : print "\t", j id_j = self.new_id(j[-1], l_id) buff_edges += self.add_edge(i, id_i, j[-1], id_j, l_eid, val) if val == 1 : val = 0 # add exceptions node if i.exception_analysis != None : id_exceptions = self.new_id(i.exception_analysis, l_id) buff_nodes += self.add_exception_node(i.exception_analysis, id_exceptions) buff_edges += self.add_edge(None, id_exceptions, None, id_i, l_eid, 2) buff_edges += self.add_edge(None, id_method, None, id_method+1, l_eid, 2) buff += buff_nodes buff += buff_edges buff += "</graph>\n" buff += "</graphml>\n" H[ name ] = buff return H class Directory : def __init__(self, name) : self.name = name self.basename = os.path.basename(name) self.color = "FF0000" self.width = len(self.name) def set_color(self, color) : self.color = color class File : def __init__(self, name, file_type, file_crc) : self.name = name self.basename = os.path.basename(name) self.file_type = file_type self.file_crc = file_crc self.color = "FFCC00" self.width = max(len(self.name), len(self.file_type)) def splitall(path, z) : if len(path) == 0 : return l = os.path.split( path ) z.append(l[0]) for i in l : return splitall( i, z ) class ApkViewer : def __init__(self, a) : self.a = a self.G = DiGraph() self.all_files = {} self.ids = {} root = Directory( "APK" ) root.set_color( "00FF00" ) self.ids[ root ] = len(self.ids) self.G.add_node( root ) for x, y, z in self.a.get_files_information() : print x, y, z, os.path.basename(x) l = [] splitall( x, l ) l.reverse() l.pop(0) last = root for i in l : if i not in self.all_files : tmp = Directory( i ) self.ids[ tmp ] = len(self.ids) self.all_files[ i ] = tmp else : tmp = self.all_files[ i ] self.G.add_edge(last, tmp) last = tmp n1 = last n2 = File( x, y, z ) self.G.add_edge(n1, n2) self.ids[ n2 ] = len(self.ids) def export_to_gml(self) : buff = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" buff += "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:y=\"http://www.yworks.com/xml/graphml\" xmlns:yed=\"http://www.yworks.com/xml/yed/3\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd\">\n" buff += "<key attr.name=\"description\" attr.type=\"string\" for=\"node\" id=\"d5\"/>\n" buff += "<key for=\"node\" id=\"d6\" yfiles.type=\"nodegraphics\"/>\n" buff += "<graph edgedefault=\"directed\" id=\"G\">\n" for node in self.G.nodes() : print node buff += "<node id=\"%d\">\n" % self.ids[node] buff += "<data key=\"d6\">\n" buff += "<y:ShapeNode>\n" buff += "<y:Geometry height=\"%f\" width=\"%f\"/>\n" % (60.0, 7 * node.width) buff += "<y:Fill color=\"#%s\" transparent=\"false\"/>\n" % node.color buff += "<y:NodeLabel>\n" buff += "%s\n" % node.basename if isinstance(node, File) : buff += "%s\n" % node.file_type buff += "%s\n" % hex(node.file_crc) buff += "</y:NodeLabel>\n" buff += "</y:ShapeNode>\n" buff += "</data>\n" buff += "</node>\n" nb = 0 for edge in self.G.edges() : buff += "<edge id=\"%d\" source=\"%d\" target=\"%d\">\n" % (nb, self.ids[edge[0]], self.ids[edge[1]]) buff += "</edge>\n" nb += 1 buff += "</graph>\n" buff += "</graphml>\n" return buff
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. # risks from classes.dex : # API <-> Permissions # method X is more dangerous than another one # const-string -> apk-tool # v0 <- X # v1 <- Y # v10 <- X # v11 <- Y # CALL( v0, v1 ) # obfuscated names GENERAL_RISK = 0 DANGEROUS_RISK = 1 SIGNATURE_SYSTEM_RISK = 2 SIGNATURE_RISK = 3 NORMAL_RISK = 4 MONEY_RISK = 5 SMS_RISK = 6 PHONE_RISK = 7 INTERNET_RISK = 8 PRIVACY_RISK = 9 DYNAMIC_RISK = 10 BINARY_RISK = 11 EXPLOIT_RISK = 12 RISK_VALUES = { DANGEROUS_RISK : 5, SIGNATURE_SYSTEM_RISK : 10, SIGNATURE_RISK : 10, NORMAL_RISK : 0, MONEY_RISK : 5, SMS_RISK : 5, PHONE_RISK : 5, INTERNET_RISK : 2, PRIVACY_RISK : 5, DYNAMIC_RISK : 5, BINARY_RISK : 10, EXPLOIT_RISK : 15, } GENERAL_PERMISSIONS_RISK = { "dangerous" : DANGEROUS_RISK, "signatureOrSystem" : SIGNATURE_SYSTEM_RISK, "signature" : SIGNATURE_RISK, "normal" : NORMAL_RISK, } PERMISSIONS_RISK = { "SEND_SMS" : [ MONEY_RISK, SMS_RISK ], "RECEIVE_SMS" : [ SMS_RISK ], "READ_SMS" : [ SMS_RISK ], "WRITE_SMS" : [ SMS_RISK ], "RECEIVE_SMS" : [ SMS_RISK ], "RECEIVE_MMS" : [ SMS_RISK ], "PHONE_CALL" : [ MONEY_RISK ], "PROCESS_OUTGOING_CALLS" : [ MONEY_RISK ], "CALL_PRIVILEGED" : [ MONEY_RISK ], "INTERNET" : [ MONEY_RISK, INTERNET_RISK ], "READ_PHONE_STATE" : [ PRIVACY_RISK ], "READ_CONTACTS" : [ PRIVACY_RISK ], "READ_HISTORY_BOOKMARKS" : [ PRIVACY_RISK ], "ACCESS_FINE_LOCATION" : [ PRIVACY_RISK ], "ACCESS_COARSE_LOCATION" : [ PRIVACY_RISK ], } LOW_RISK = "low" AVERAGE_RISK = "average" HIGH_RISK = "high" UNACCEPTABLE_RISK = "unacceptable" NULL_MALWARE_RISK = "null" AVERAGE_MALWARE_RISK = "average" HIGH_MALWARE_RISK = "high" UNACCEPTABLE_MALWARE_RISK = "unacceptable" from androguard.core.androconf import error, warning, debug, set_debug, get_debug from androguard.core.bytecodes import dvm from androguard.core.analysis import analysis from androguard.core.bytecodes.dvm_permissions import DVM_PERMISSIONS def add_system_rule(system, rule_name, rule) : system.rules[ rule_name ] = rule def create_system_risk() : try : import fuzzy except ImportError : error("please install pyfuzzy to use this module !") import fuzzy.System import fuzzy.InputVariable import fuzzy.fuzzify.Plain import fuzzy.OutputVariable import fuzzy.defuzzify.COGS import fuzzy.defuzzify.COG import fuzzy.defuzzify.MaxRight import fuzzy.defuzzify.MaxLeft import fuzzy.defuzzify.LM import fuzzy.set.Polygon import fuzzy.set.Singleton import fuzzy.set.Triangle import fuzzy.Adjective import fuzzy.operator.Input import fuzzy.operator.Compound import fuzzy.norm.Min import fuzzy.norm.Max import fuzzy.Rule import fuzzy.defuzzify.Dict system = fuzzy.System.System() input_Dangerous_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Money_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Privacy_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Binary_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Internet_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Dynamic_Risk = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) # Input variables # Dangerous Risk system.variables["input_Dangerous_Risk"] = input_Dangerous_Risk input_Dangerous_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (8.0, 1.0), (12.0, 0.0)]) ) input_Dangerous_Risk.adjectives[AVERAGE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(8.0, 0.0), (50.0, 1.0), (60.0, 0.0)]) ) input_Dangerous_Risk.adjectives[HIGH_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(50.0, 0.0), (85.0, 1.0), (95.0, 0.0)]) ) input_Dangerous_Risk.adjectives[UNACCEPTABLE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(85.0, 0.0), (100.0, 1.0)]) ) # Money Risk system.variables["input_Money_Risk"] = input_Money_Risk input_Money_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (3.0, 0.0)]) ) input_Money_Risk.adjectives[UNACCEPTABLE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(4.0, 0.0), (5.0, 1.0), (30.0, 1.0)]) ) # Privacy Risk system.variables["input_Privacy_Risk"] = input_Privacy_Risk input_Privacy_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (6.0, 1.0), (10.0, 0.0)]) ) input_Privacy_Risk.adjectives[HIGH_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(6.0, 0.0), (10.0, 1.0), (20.0, 0.0)]) ) input_Privacy_Risk.adjectives[UNACCEPTABLE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(15.0, 0.0), (20.0, 1.0), (30.0, 1.0)]) ) # Binary Risk system.variables["input_Binary_Risk"] = input_Binary_Risk input_Binary_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (6.0, 1.0), (10.0, 0.0)]) ) input_Binary_Risk.adjectives[AVERAGE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(6.0, 0.0), (10.0, 1.0), (15.0, 0.0)]) ) input_Binary_Risk.adjectives[HIGH_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(10.0, 0.0), (20.0, 1.0), (24.0, 0.0)]) ) input_Binary_Risk.adjectives[UNACCEPTABLE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(23.0, 0.0), (30.0, 1.0), (40.0, 1.0)]) ) # Internet Risk system.variables["input_Internet_Risk"] = input_Internet_Risk #input_Internet_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (1.0, 1.0)]) ) input_Internet_Risk.adjectives[HIGH_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(1.0, 0.0), (5.0, 1.0), (30.0, 1.0)]) ) # Dynamic Risk system.variables["input_Dynamic_Risk"] = input_Dynamic_Risk input_Dynamic_Risk.adjectives[LOW_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (3.0, 0.0)])) input_Dynamic_Risk.adjectives[UNACCEPTABLE_RISK] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(4.0, 0.0), (5.0, 1.0), (50.0, 1.0)]) ) # Output variables output_malware_risk = fuzzy.OutputVariable.OutputVariable( defuzzify=fuzzy.defuzzify.COGS.COGS(), description="malware risk", min=0.0,max=100.0, ) #output_malware_risk = fuzzy.OutputVariable.OutputVariable(defuzzify=fuzzy.defuzzify.Dict.Dict()) output_malware_risk.adjectives[NULL_MALWARE_RISK] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(0.0)) output_malware_risk.adjectives[AVERAGE_MALWARE_RISK] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(30.0)) output_malware_risk.adjectives[HIGH_MALWARE_RISK] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(60.0)) output_malware_risk.adjectives[UNACCEPTABLE_MALWARE_RISK] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(100.0)) system.variables["output_malware_risk"] = output_malware_risk # Rules #RULE 0: DYNAMIC add_system_rule(system, "r0", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[NULL_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Dynamic_Risk"].adjectives[LOW_RISK] ) ) ) add_system_rule(system, "r0a", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[UNACCEPTABLE_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Dynamic_Risk"].adjectives[UNACCEPTABLE_RISK] ) ) ) #RULE 1: MONEY add_system_rule(system, "r1", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[NULL_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Money_Risk"].adjectives[LOW_RISK] ) ) ) add_system_rule(system, "r1a", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[UNACCEPTABLE_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Money_Risk"].adjectives[UNACCEPTABLE_RISK] ) ) ) #RULE 3 : BINARY add_system_rule(system, "r3", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[AVERAGE_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Binary_Risk"].adjectives[AVERAGE_RISK] ) ) ) add_system_rule(system, "r3a", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[HIGH_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Binary_Risk"].adjectives[HIGH_RISK] ) ) ) add_system_rule(system, "r3b", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[UNACCEPTABLE_MALWARE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Binary_Risk"].adjectives[UNACCEPTABLE_RISK] ) ) ) # PRIVACY + INTERNET add_system_rule(system, "r5", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[HIGH_MALWARE_RISK]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Privacy_Risk"].adjectives[LOW_RISK] ), fuzzy.operator.Input.Input( system.variables["input_Internet_Risk"].adjectives[HIGH_RISK] ) ) ) ) add_system_rule(system, "r5a", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[UNACCEPTABLE_MALWARE_RISK]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Privacy_Risk"].adjectives[HIGH_RISK] ), fuzzy.operator.Input.Input( system.variables["input_Internet_Risk"].adjectives[HIGH_RISK] ) ) ) ) add_system_rule(system, "r6", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[HIGH_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Dangerous_Risk"].adjectives[HIGH_RISK] ) ) ) add_system_rule(system, "r6a", fuzzy.Rule.Rule( adjective=[system.variables["output_malware_risk"].adjectives[UNACCEPTABLE_RISK]], operator=fuzzy.operator.Input.Input( system.variables["input_Dangerous_Risk"].adjectives[UNACCEPTABLE_RISK] ) ) ) return system PERFECT_SCORE = "perfect" HIGH_SCORE = "high" AVERAGE_SCORE = "average" LOW_SCORE = "low" NULL_METHOD_SCORE = "null" AVERAGE_METHOD_SCORE = "average" HIGH_METHOD_SCORE = "high" PERFECT_METHOD_SCORE = "perfect" def create_system_method_score() : try : import fuzzy except ImportError : error("please install pyfuzzy to use this module !") import fuzzy.System import fuzzy.InputVariable import fuzzy.fuzzify.Plain import fuzzy.OutputVariable import fuzzy.defuzzify.COGS import fuzzy.set.Polygon import fuzzy.set.Singleton import fuzzy.set.Triangle import fuzzy.Adjective import fuzzy.operator.Input import fuzzy.operator.Compound import fuzzy.norm.Min import fuzzy.norm.Max import fuzzy.Rule system = fuzzy.System.System() input_Length_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Match_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_AndroidEntropy_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_JavaEntropy_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Permissions_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Similarity_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) # Input variables # Length system.variables["input_Length_MS"] = input_Length_MS input_Length_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (50.0, 1.0), (100.0, 0.0)]) ) input_Length_MS.adjectives[AVERAGE_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(50.0, 0.0), (100.0, 1.0), (150.0, 1.0), (300.0, 0.0)]) ) input_Length_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(150.0, 0.0), (200.0, 1.0), (300.0, 1.0), (400.0, 0.0)]) ) input_Length_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(350.0, 0.0), (400.0, 1.0), (500.0, 1.0)]) ) # Match system.variables["input_Match_MS"] = input_Match_MS input_Match_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (20.0, 1.0), (50.0, 0.0)]) ) input_Match_MS.adjectives[AVERAGE_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(40.0, 0.0), (45.0, 1.0), (60.0, 1.0), (80.0, 0.0)]) ) input_Match_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(75.0, 0.0), (90.0, 1.0), (98.0, 1.0), (99.0, 0.0)]) ) input_Match_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(98.0, 0.0), (100.0, 1.0)]) ) #input_Match_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Singleton.Singleton( 100.0 ) ) # Android Entropy system.variables["input_AndroidEntropy_MS"] = input_AndroidEntropy_MS input_AndroidEntropy_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (4.0, 0.0)]) ) input_AndroidEntropy_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (30.0, 1.0)]) ) # Java Entropy system.variables["input_JavaEntropy_MS"] = input_JavaEntropy_MS input_JavaEntropy_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (4.0, 0.0)]) ) input_JavaEntropy_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (30.0, 1.0)]) ) # Permissions system.variables["input_Permissions_MS"] = input_Permissions_MS input_Permissions_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (3.0, 1.0), (4.0, 0.0)]) ) input_Permissions_MS.adjectives[AVERAGE_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (8.0, 1.0), (9.0, 0.0)]) ) input_Permissions_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(8.0, 0.0), (10.0, 1.0), (12.0, 1.0), (13.0, 0.0)]) ) input_Permissions_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(12.0, 0.0), (13.0, 1.0), (20.0, 1.0)]) ) # Similarity Match system.variables["input_Similarity_MS"] = input_Similarity_MS input_Similarity_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (0.1, 1.0), (0.3, 0.0)]) ) input_Similarity_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.3, 0.0), (0.35, 1.0), (0.4, 1.0)]) ) # Output variables output_method_score = fuzzy.OutputVariable.OutputVariable( defuzzify=fuzzy.defuzzify.COGS.COGS(), description="method score", min=0.0,max=100.0, ) output_method_score.adjectives[NULL_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(0.0)) output_method_score.adjectives[AVERAGE_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(50.0)) output_method_score.adjectives[HIGH_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(80.0)) output_method_score.adjectives[PERFECT_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(100.0)) system.variables["output_method_score"] = output_method_score add_system_rule(system, "android entropy null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_AndroidEntropy_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "java entropy null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_JavaEntropy_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "permissions null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "permissions average", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[AVERAGE_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[AVERAGE_SCORE] )) ) add_system_rule(system, "permissions high", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[HIGH_SCORE] )) ) add_system_rule(system, "permissions perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[PERFECT_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[PERFECT_SCORE] )) ) add_system_rule(system, "similarity low", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Similarity_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "length match perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[PERFECT_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_Match_MS"].adjectives[PERFECT_SCORE] ) ) ) ) add_system_rule(system, "length match null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[LOW_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_Match_MS"].adjectives[PERFECT_SCORE] ) ) ) ) add_system_rule(system, "length AndroidEntropy perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_AndroidEntropy_MS"].adjectives[HIGH_SCORE] ) ) ) ) add_system_rule(system, "length JavaEntropy perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_JavaEntropy_MS"].adjectives[HIGH_SCORE] ) ) ) ) add_system_rule(system, "length similarity perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[PERFECT_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_Similarity_MS"].adjectives[HIGH_SCORE] ), ) ) ) add_system_rule(system, "length similarity average", fuzzy.Rule.Rule( adjective=[system.variables["output_method_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[AVERAGE_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_Similarity_MS"].adjectives[HIGH_SCORE] ), ) ) ) return system def create_system_method_one_score() : try : import fuzzy except ImportError : error("please install pyfuzzy to use this module !") import fuzzy.System import fuzzy.InputVariable import fuzzy.fuzzify.Plain import fuzzy.OutputVariable import fuzzy.defuzzify.COGS import fuzzy.set.Polygon import fuzzy.set.Singleton import fuzzy.set.Triangle import fuzzy.Adjective import fuzzy.operator.Input import fuzzy.operator.Compound import fuzzy.norm.Min import fuzzy.norm.Max import fuzzy.Rule system = fuzzy.System.System() input_Length_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_AndroidEntropy_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_JavaEntropy_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) input_Permissions_MS = fuzzy.InputVariable.InputVariable(fuzzify=fuzzy.fuzzify.Plain.Plain()) # Input variables # Length system.variables["input_Length_MS"] = input_Length_MS input_Length_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (50.0, 1.0), (100.0, 0.0)]) ) input_Length_MS.adjectives[AVERAGE_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(50.0, 0.0), (100.0, 1.0), (150.0, 1.0), (300.0, 0.0)]) ) input_Length_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(150.0, 0.0), (200.0, 1.0), (300.0, 1.0), (400.0, 0.0)]) ) input_Length_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(350.0, 0.0), (400.0, 1.0), (500.0, 1.0)]) ) # Android Entropy system.variables["input_AndroidEntropy_MS"] = input_AndroidEntropy_MS input_AndroidEntropy_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (4.0, 0.0)]) ) input_AndroidEntropy_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (30.0, 1.0)]) ) # Java Entropy system.variables["input_JavaEntropy_MS"] = input_JavaEntropy_MS input_JavaEntropy_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (2.0, 1.0), (4.0, 0.0)]) ) input_JavaEntropy_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (30.0, 1.0)]) ) # Permissions system.variables["input_Permissions_MS"] = input_Permissions_MS input_Permissions_MS.adjectives[LOW_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(0.0, 1.0), (3.0, 1.0), (4.0, 0.0)]) ) input_Permissions_MS.adjectives[AVERAGE_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(3.0, 0.0), (4.0, 1.0), (8.0, 1.0), (9.0, 0.0)]) ) input_Permissions_MS.adjectives[HIGH_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(8.0, 0.0), (10.0, 1.0), (12.0, 1.0), (13.0, 0.0)]) ) input_Permissions_MS.adjectives[PERFECT_SCORE] = fuzzy.Adjective.Adjective( fuzzy.set.Polygon.Polygon([(12.0, 0.0), (13.0, 1.0), (20.0, 1.0)]) ) # Output variables output_method_score = fuzzy.OutputVariable.OutputVariable( defuzzify=fuzzy.defuzzify.COGS.COGS(), description="method one score", min=0.0,max=100.0, ) output_method_score.adjectives[NULL_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(0.0)) output_method_score.adjectives[AVERAGE_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(50.0)) output_method_score.adjectives[HIGH_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(80.0)) output_method_score.adjectives[PERFECT_METHOD_SCORE] = fuzzy.Adjective.Adjective(fuzzy.set.Singleton.Singleton(100.0)) system.variables["output_method_one_score"] = output_method_score add_system_rule(system, "android entropy null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_AndroidEntropy_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "java entropy null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_JavaEntropy_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "permissions null", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[NULL_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[LOW_SCORE] )) ) add_system_rule(system, "permissions average", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[AVERAGE_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[AVERAGE_SCORE] )) ) add_system_rule(system, "permissions high", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[HIGH_SCORE] )) ) add_system_rule(system, "permissions perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[PERFECT_METHOD_SCORE]], operator=fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[PERFECT_SCORE] )) ) add_system_rule(system, "length permissions perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[PERFECT_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_Permissions_MS"].adjectives[PERFECT_SCORE] ) ) ) ) add_system_rule(system, "length AndroidEntropy perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_AndroidEntropy_MS"].adjectives[HIGH_SCORE] ) ) ) ) add_system_rule(system, "length JavaEntropy perfect", fuzzy.Rule.Rule( adjective=[system.variables["output_method_one_score"].adjectives[HIGH_METHOD_SCORE]], operator=fuzzy.operator.Compound.Compound( fuzzy.norm.Min.Min(), fuzzy.operator.Input.Input( system.variables["input_Length_MS"].adjectives[PERFECT_SCORE] ), fuzzy.operator.Input.Input( system.variables["input_JavaEntropy_MS"].adjectives[HIGH_SCORE] ) ) ) ) return system def export_system(system, directory) : from fuzzy.doc.plot.gnuplot import doc d = doc.Doc(directory) d.createDoc(system) import fuzzy.doc.structure.dot.dot import subprocess for name,rule in system.rules.items(): cmd = "dot -T png -o '%s/fuzzy-Rule %s.png'" % (directory,name) f = subprocess.Popen(cmd, shell=True, bufsize=32768, stdin=subprocess.PIPE).stdin fuzzy.doc.structure.dot.dot.print_header(f,"XXX") fuzzy.doc.structure.dot.dot.print_dot(rule,f,system,"") fuzzy.doc.structure.dot.dot.print_footer(f) cmd = "dot -T png -o '%s/fuzzy-System.png'" % directory f = subprocess.Popen(cmd, shell=True, bufsize=32768, stdin=subprocess.PIPE).stdin fuzzy.doc.structure.dot.dot.printDot(system,f) d.overscan=0 in_vars = [name for name,var in system.variables.items() if isinstance(var,fuzzy.InputVariable.InputVariable)] out_vars = [name for name,var in system.variables.items() if isinstance(var,fuzzy.OutputVariable.OutputVariable)] if len(in_vars) == 2 and not ( isinstance(system.variables[in_vars[0]].fuzzify,fuzzy.fuzzify.Dict.Dict) or isinstance(system.variables[in_vars[1]].fuzzify,fuzzy.fuzzify.Dict.Dict) ): for out_var in out_vars: args = [] if isinstance(system.variables[out_var].defuzzify,fuzzy.defuzzify.Dict.Dict): for adj in system.variables[out_var].adjectives: d.create3DPlot_adjective(system, in_vars[0], in_vars[1], out_var, adj, {}) else: d.create3DPlot(system, in_vars[0], in_vars[1], out_var, {}) SYSTEM = None class RiskIndicator : """ Calculate the risk to install a specific android application by using : Permissions : - dangerous - signatureOrSystem - signature - normal - money - internet - sms - call - privacy API : - DexClassLoader Files : - binary file - shared library note : pyfuzzy without fcl support (don't install antlr) """ def __init__(self) : #set_debug() global SYSTEM if SYSTEM == None : SYSTEM = create_system_risk() # export_system( SYSTEM, "./output" ) self.system_method_risk = create_system_method_one_score() def __eval_risk_perm(self, list_details_permissions, risks) : for i in list_details_permissions : permission = i if permission.find(".") != -1 : permission = permission.split(".")[-1] # print permission, GENERAL_PERMISSIONS_RISK[ list_details_permissions[ i ][0] ] risk_type = GENERAL_PERMISSIONS_RISK[ list_details_permissions[ i ][0] ] risks[ DANGEROUS_RISK ] += RISK_VALUES [ risk_type ] try : for j in PERMISSIONS_RISK[ permission ] : risks[ j ] += RISK_VALUES[ j ] except KeyError : pass def __eval_risk_dyn(self, vmx, risks) : for m, _ in vmx.tainted_packages.get_packages() : if m.get_info() == "Ldalvik/system/DexClassLoader;" : for path in m.get_paths() : if path.get_access_flag() == analysis.TAINTED_PACKAGE_CREATE : risks[ DYNAMIC_RISK ] = RISK_VALUES[ DYNAMIC_RISK ] return def __eval_risk_bin(self, list_details_files, risks) : for i in list_details_files : if "ELF" in list_details_files[ i ] : # shared library if "shared" in list_details_files[ i ] : risks[ BINARY_RISK ] += RISK_VALUES [ BINARY_RISK ] # binary else : risks[ BINARY_RISK ] += RISK_VALUES [ EXPLOIT_RISK ] def __eval_risks(self, risks) : output_values = {"output_malware_risk" : 0.0} input_val = {} input_val['input_Dangerous_Risk'] = risks[ DANGEROUS_RISK ] input_val['input_Money_Risk'] = risks[ MONEY_RISK ] input_val['input_Privacy_Risk'] = risks[ PRIVACY_RISK ] input_val['input_Binary_Risk'] = risks[ BINARY_RISK ] input_val['input_Internet_Risk'] = risks[ INTERNET_RISK ] input_val['input_Dynamic_Risk'] = risks[ DYNAMIC_RISK ] #print input_val, SYSTEM.calculate(input=input_val, output = output_values) val = output_values[ "output_malware_risk" ] return val def with_apk(self, apk_file, analysis=None, analysis_method=None) : """ @param apk_file : an L{APK} object @rtype : return the risk of the apk file (from 0.0 to 100.0) """ if apk_file.is_valid_APK() : if analysis == None : return self.with_apk_direct( apk_file ) else : return self.with_apk_analysis( apk_file, analysis_method ) return -1 def with_apk_direct(self, apk) : risks = { DANGEROUS_RISK : 0.0, MONEY_RISK : 0.0, PRIVACY_RISK : 0.0, INTERNET_RISK : 0.0, BINARY_RISK : 0.0, DYNAMIC_RISK : 0.0, } self.__eval_risk_perm( apk.get_details_permissions(), risks ) self.__eval_risk_bin( apk.get_files_types(), risks ) val = self.__eval_risks( risks ) return val def with_apk_analysis( self, apk, analysis_method=None ) : return self.with_dex( apk.get_dex(), apk, analysis_method ) def with_dex(self, dex_file, apk=None, analysis_method=None) : """ @param dex_file : a buffer @rtype : return the risk of the dex file (from 0.0 to 100.0) """ try : vm = dvm.DalvikVMFormat( dex_file ) except Exception, e : return -1 vmx = analysis.VMAnalysis( vm ) return self.with_dex_direct( vm, vmx, apk, analysis_method ) def with_dex_direct(self, vm, vmx, apk=None, analysis_method=None) : risks = { DANGEROUS_RISK : 0.0, MONEY_RISK : 0.0, PRIVACY_RISK : 0.0, INTERNET_RISK : 0.0, BINARY_RISK : 0.0, DYNAMIC_RISK : 0.0, } if apk : self.__eval_risk_bin( apk.get_files_types(), risks ) self.__eval_risk_perm( apk.get_details_permissions(), risks ) else : d = {} for i in vmx.get_permissions( [] ) : d[ i ] = DVM_PERMISSIONS["MANIFEST_PERMISSION"][i] self.__eval_risk_perm( d, risks ) self.__eval_risk_dyn( vmx, risks ) val = self.__eval_risks( risks ) if analysis_method == None : return val, {} ########################## score_order_sign = {} import sys sys.path.append("./elsim") from elsim.elsign.libelsign import libelsign for method in vm.get_methods() : if method.get_length() < 80 : continue score_order_sign[ method ] = self.get_method_score( method.get_length(), libelsign.entropy( vmx.get_method_signature(method, "L4", { "L4" : { "arguments" : ["Landroid"] } } ).get_string() ), libelsign.entropy( vmx.get_method_signature(method, "L4", { "L4" : { "arguments" : ["Ljava"] } } ).get_string() ), map(lambda perm : (perm, DVM_PERMISSIONS["MANIFEST_PERMISSION"][ perm ]), vmx.get_permissions_method( method )), ) for v in sorted(score_order_sign, key=lambda x : score_order_sign[x], reverse=True) : print v.get_name(), v.get_class_name(), v.get_descriptor(), v.get_length(), score_order_sign[ v ] ########################## return val, score_order_sign def get_method_score(self, length, android_entropy, java_entropy, permissions) : val_permissions = 0 for i in permissions : val_permissions += RISK_VALUES[ GENERAL_PERMISSIONS_RISK[ i[1][0] ] ] try : for j in PERMISSIONS_RISK[ i[0] ] : val_permissions += RISK_VALUES[ j ] except KeyError : pass print length, android_entropy, java_entropy, val_permissions output_values = {"output_method_one_score" : 0.0} input_val = {} input_val['input_Length_MS'] = length input_val['input_AndroidEntropy_MS'] = android_entropy input_val['input_JavaEntropy_MS'] = java_entropy input_val['input_Permissions_MS'] = val_permissions self.system_method_risk.calculate(input=input_val, output = output_values) score = output_values[ "output_method_one_score" ] return score def simulate(self, risks) : return self.__eval_risks( risks ) class MethodScore : def __init__(self, length, matches, android_entropy, java_entropy, permissions, similarity_matches) : self.system = create_system_method_score() #export_system( self.system, "./output" ) val_permissions = 0 for i in permissions : val_permissions += RISK_VALUES[ GENERAL_PERMISSIONS_RISK[ i[1][0] ] ] try : for j in PERMISSIONS_RISK[ i[0] ] : val_permissions += RISK_VALUES[ j ] except KeyError : pass print length, matches, android_entropy, java_entropy, similarity_matches, val_permissions output_values = {"output_method_score" : 0.0} input_val = {} input_val['input_Length_MS'] = length input_val['input_Match_MS'] = matches input_val['input_AndroidEntropy_MS'] = android_entropy input_val['input_JavaEntropy_MS'] = java_entropy input_val['input_Permissions_MS'] = val_permissions input_val['input_Similarity_MS'] = similarity_matches self.system.calculate(input=input_val, output = output_values) self.score = output_values[ "output_method_score" ] def get_score(self) : return self.score
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from networkx import DiGraph from xml.sax.saxutils import escape from androguard.core import bytecode from androguard.core.bytecodes.dvm_permissions import DVM_PERMISSIONS from androguard.core.analysis.risk import PERMISSIONS_RISK, INTERNET_RISK, PRIVACY_RISK, PHONE_RISK, SMS_RISK, MONEY_RISK from androguard.core.analysis.analysis import TAINTED_PACKAGE_CREATE DEFAULT_RISKS = { INTERNET_RISK : ( "INTERNET_RISK", (195, 255, 0) ), PRIVACY_RISK : ( "PRIVACY_RISK", (255, 255, 51) ), PHONE_RISK : ( "PHONE_RISK", ( 255, 216, 0 ) ), SMS_RISK : ( "SMS_RISK", ( 255, 93, 0 ) ), MONEY_RISK : ( "MONEY_RISK", ( 255, 0, 0 ) ), } DEXCLASSLOADER_COLOR = (0, 0, 0) ACTIVITY_COLOR = (51, 255, 51) SERVICE_COLOR = (0, 204, 204) RECEIVER_COLOR = (204, 51, 204) ID_ATTRIBUTES = { "type" : 0, "class_name" : 1, "method_name" : 2, "descriptor" : 3, "permissions" : 4, "permissions_level" : 5, "dynamic_code" : 6, } class GVMAnalysis : def __init__(self, vmx, apk) : self.vmx = vmx self.vm = self.vmx.get_vm() self.nodes = {} self.nodes_id = {} self.entry_nodes = [] self.G = DiGraph() for j in self.vmx.tainted_packages.get_internal_packages() : n1 = self._get_node( j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor() ) n2 = self._get_node( j.get_class_name(), j.get_name(), j.get_descriptor() ) self.G.add_edge( n1.id, n2.id ) n1.add_edge( n2, j ) # print "\t %s %s %s %x ---> %s %s %s" % (j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor(), \ # j.get_bb().start + j.get_idx(), \ # j.get_class_name(), j.get_name(), j.get_descriptor()) if apk != None : for i in apk.get_activities() : j = bytecode.FormatClassToJava(i) n1 = self._get_exist_node( j, "onCreate", "(Landroid/os/Bundle;)V" ) if n1 != None : n1.set_attributes( { "type" : "activity" } ) n1.set_attributes( { "color" : ACTIVITY_COLOR } ) n2 = self._get_new_node_from( n1, "ACTIVITY" ) n2.set_attributes( { "color" : ACTIVITY_COLOR } ) self.G.add_edge( n2.id, n1.id ) self.entry_nodes.append( n1.id ) for i in apk.get_services() : j = bytecode.FormatClassToJava(i) n1 = self._get_exist_node( j, "onCreate", "()V" ) if n1 != None : n1.set_attributes( { "type" : "service" } ) n1.set_attributes( { "color" : SERVICE_COLOR } ) n2 = self._get_new_node_from( n1, "SERVICE" ) n2.set_attributes( { "color" : SERVICE_COLOR } ) self.G.add_edge( n2.id, n1.id ) self.entry_nodes.append( n1.id ) for i in apk.get_receivers() : j = bytecode.FormatClassToJava(i) n1 = self._get_exist_node( j, "onReceive", "(Landroid/content/Context; Landroid/content/Intent;)V" ) if n1 != None : n1.set_attributes( { "type" : "receiver" } ) n1.set_attributes( { "color" : RECEIVER_COLOR } ) n2 = self._get_new_node_from( n1, "RECEIVER" ) n2.set_attributes( { "color" : RECEIVER_COLOR } ) self.G.add_edge( n2.id, n1.id ) self.entry_nodes.append( n1.id ) # Specific Java/Android library for c in self.vm.get_classes() : #if c.get_superclassname() == "Landroid/app/Service;" : # n1 = self._get_node( c.get_name(), "<init>", "()V" ) # n2 = self._get_node( c.get_name(), "onCreate", "()V" ) # self.G.add_edge( n1.id, n2.id ) if c.get_superclassname() == "Ljava/lang/Thread;" or c.get_superclassname() == "Ljava/util/TimerTask;" : for i in self.vm.get_method("run") : if i.get_class_name() == c.get_name() : n1 = self._get_node( i.get_class_name(), i.get_name(), i.get_descriptor() ) n2 = self._get_node( i.get_class_name(), "start", i.get_descriptor() ) # link from start to run self.G.add_edge( n2.id, n1.id ) n2.add_edge( n1, {} ) # link from init to start for init in self.vm.get_method("<init>") : if init.get_class_name() == c.get_name() : n3 = self._get_node( init.get_class_name(), "<init>", init.get_descriptor() ) #n3 = self._get_node( i.get_class_name(), "<init>", i.get_descriptor() ) self.G.add_edge( n3.id, n2.id ) n3.add_edge( n2, {} ) #elif c.get_superclassname() == "Landroid/os/AsyncTask;" : # for i in self.vm.get_method("doInBackground") : # if i.get_class_name() == c.get_name() : # n1 = self._get_node( i.get_class_name(), i.get_name(), i.get_descriptor() ) # n2 = self._get_exist_node( i.get_class_name(), "execute", i.get_descriptor() ) # print n1, n2, i.get_descriptor() #for j in self.vm.get_method("doInBackground") : # n2 = self._get_exist_node( i.get_class_name(), j.get_name(), j.get_descriptor() ) # print n1, n2 # n2 = self._get_node( i.get_class_name(), " # raise("ooo") #for j in self.vmx.tainted_packages.get_internal_new_packages() : # print "\t %s %s %s %x ---> %s %s %s" % (j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor(), \ # j.get_bb().start + j.get_idx(), \ # j.get_class_name(), j.get_name(), j.get_descriptor()) list_permissions = self.vmx.get_permissions( [] ) for x in list_permissions : for j in list_permissions[ x ] : #print "\t %s %s %s %x ---> %s %s %s" % (j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor(), \ # j.get_bb().start + j.get_idx(), \ # j.get_class_name(), j.get_name(), j.get_descriptor()) n1 = self._get_exist_node( j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor() ) if n1 == None : continue n1.set_attributes( { "permissions" : 1 } ) n1.set_attributes( { "permissions_level" : DVM_PERMISSIONS[ "MANIFEST_PERMISSION" ][ x ][0] } ) n1.set_attributes( { "permissions_details" : x } ) try : for tmp_perm in PERMISSIONS_RISK[ x ] : if tmp_perm in DEFAULT_RISKS : n2 = self._get_new_node( j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor() + " " + DEFAULT_RISKS[ tmp_perm ][0], DEFAULT_RISKS[ tmp_perm ][0] ) n2.set_attributes( { "color" : DEFAULT_RISKS[ tmp_perm ][1] } ) self.G.add_edge( n2.id, n1.id ) n1.add_risk( DEFAULT_RISKS[ tmp_perm ][0] ) n1.add_api( x, j.get_class_name() + "-" + j.get_name() + "-" + j.get_descriptor() ) except KeyError : pass # Tag DexClassLoader for m, _ in self.vmx.tainted_packages.get_packages() : if m.get_info() == "Ldalvik/system/DexClassLoader;" : for path in m.get_paths() : if path.get_access_flag() == TAINTED_PACKAGE_CREATE : n1 = self._get_exist_node( path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor() ) n2 = self._get_new_node( path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor() + " " + "DEXCLASSLOADER", "DEXCLASSLOADER" ) n1.set_attributes( { "dynamic_code" : "true" } ) n2.set_attributes( { "color" : DEXCLASSLOADER_COLOR } ) self.G.add_edge( n2.id, n1.id ) n1.add_risk( "DEXCLASSLOADER" ) def _get_exist_node(self, class_name, method_name, descriptor) : key = "%s %s %s" % (class_name, method_name, descriptor) try : return self.nodes[ key ] except KeyError : return None def _get_node(self, class_name, method_name, descriptor) : key = "%s %s %s" % (class_name, method_name, descriptor) if key not in self.nodes : self.nodes[ key ] = NodeF( len(self.nodes), class_name, method_name, descriptor ) self.nodes_id[ self.nodes[ key ].id ] = self.nodes[ key ] return self.nodes[ key ] def _get_new_node_from(self, n, label) : return self._get_new_node( n.class_name, n.method_name, n.descriptor + label, label ) def _get_new_node(self, class_name, method_name, descriptor, label) : key = "%s %s %s" % (class_name, method_name, descriptor) if key not in self.nodes : self.nodes[ key ] = NodeF( len(self.nodes), class_name, method_name, descriptor, label, False ) self.nodes_id[ self.nodes[ key ].id ] = self.nodes[ key ] return self.nodes[ key ] def set_new_attributes(self, cm) : for i in self.G.nodes() : n1 = self.nodes_id[ i ] m1 = self.vm.get_method_descriptor( n1.class_name, n1.method_name, n1.descriptor ) H = cm( self.vmx, m1 ) n1.set_attributes( H ) def export_to_gexf(self) : buff = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" buff += "<gexf xmlns=\"http://www.gephi.org/gexf\" xmlns:viz=\"http://www.gephi.org/gexf/viz\">\n" buff += "<graph type=\"static\">\n" buff += "<attributes class=\"node\" type=\"static\">\n" buff += "<attribute default=\"normal\" id=\"%d\" title=\"type\" type=\"string\"/>\n" % ID_ATTRIBUTES[ "type"] buff += "<attribute id=\"%d\" title=\"class_name\" type=\"string\"/>\n" % ID_ATTRIBUTES[ "class_name"] buff += "<attribute id=\"%d\" title=\"method_name\" type=\"string\"/>\n" % ID_ATTRIBUTES[ "method_name"] buff += "<attribute id=\"%d\" title=\"descriptor\" type=\"string\"/>\n" % ID_ATTRIBUTES[ "descriptor"] buff += "<attribute default=\"0\" id=\"%d\" title=\"permissions\" type=\"integer\"/>\n" % ID_ATTRIBUTES[ "permissions"] buff += "<attribute default=\"normal\" id=\"%d\" title=\"permissions_level\" type=\"string\"/>\n" % ID_ATTRIBUTES[ "permissions_level"] buff += "<attribute default=\"false\" id=\"%d\" title=\"dynamic_code\" type=\"boolean\"/>\n" % ID_ATTRIBUTES[ "dynamic_code"] buff += "</attributes>\n" buff += "<nodes>\n" for node in self.G.nodes() : buff += "<node id=\"%d\" label=\"%s\">\n" % (node, escape(self.nodes_id[ node ].label)) buff += self.nodes_id[ node ].get_attributes_gexf() buff += "</node>\n" buff += "</nodes>\n" buff += "<edges>\n" nb = 0 for edge in self.G.edges() : buff += "<edge id=\"%d\" source=\"%d\" target=\"%d\"/>\n" % (nb, edge[0], edge[1]) nb += 1 buff += "</edges>\n" buff += "</graph>\n" buff += "</gexf>\n" return buff def export_to_gml(self) : buff = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" buff += "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:y=\"http://www.yworks.com/xml/graphml\" xmlns:yed=\"http://www.yworks.com/xml/yed/3\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd\">\n" buff += "<key attr.name=\"description\" attr.type=\"string\" for=\"node\" id=\"d5\"/>\n" buff += "<key for=\"node\" id=\"d6\" yfiles.type=\"nodegraphics\"/>\n" buff += "<graph edgedefault=\"directed\" id=\"G\">\n" for node in self.G.nodes() : buff += "<node id=\"%d\">\n" % (node) #fd.write( "<node id=\"%d\" label=\"%s\">\n" % (node, escape(self.nodes_id[ node ].label)) ) buff += self.nodes_id[ node ].get_attributes_gml() buff += "</node>\n" nb = 0 for edge in self.G.edges() : buff += "<edge id=\"%d\" source=\"%d\" target=\"%d\"/>\n" % (nb, edge[0], edge[1]) nb += 1 buff += "</graph>\n" buff += "</graphml>\n" return buff def get_paths_method(self, method) : return self.get_paths( method.get_class_name(), method.get_name(), method.get_descriptor() ) def get_paths(self, class_name, method_name, descriptor) : import connectivity_approx as ca paths = [] key = "%s %s %s" % (class_name, method_name, descriptor) if key not in self.nodes : return paths for origin in self.G.nodes() : #self.entry_nodes : if ca.vertex_connectivity_approx(self.G, origin, self.nodes[ key ].id) > 0 : for path in ca.node_independent_paths(self.G, origin, self.nodes[ key ].id) : if self.nodes_id[ path[0] ].real == True : paths.append( path ) return paths def print_paths_method(self, method) : self.print_paths( method.get_class_name(), method.get_name(), method.get_descriptor() ) def print_paths(self, class_name, method_name, descriptor) : paths = self.get_paths( class_name, method_name, descriptor ) for path in paths : print path, ":" print "\t", for p in path[:-1] : print self.nodes_id[ p ].label, "-->", print self.nodes_id[ path[-1] ].label DEFAULT_NODE_TYPE = "normal" DEFAULT_NODE_PERM = 0 DEFAULT_NODE_PERM_LEVEL = -1 PERMISSIONS_LEVEL = { "dangerous" : 3, "signatureOrSystem" : 2, "signature" : 1, "normal" : 0, } COLOR_PERMISSIONS_LEVEL = { "dangerous" : (255, 0, 0), "signatureOrSystem" : (255, 63, 63), "signature" : (255, 132, 132), "normal" : (255, 181, 181), } class NodeF : def __init__(self, id, class_name, method_name, descriptor, label=None, real=True) : self.class_name = class_name self.method_name = method_name self.descriptor = descriptor self.id = id self.real = real self.risks = [] self.api = {} self.edges = {} if label == None : self.label = "%s %s %s" % (class_name, method_name, descriptor) else : self.label = label self.attributes = { "type" : DEFAULT_NODE_TYPE, "color" : None, "permissions" : DEFAULT_NODE_PERM, "permissions_level" : DEFAULT_NODE_PERM_LEVEL, "permissions_details" : set(), "dynamic_code" : "false", } def add_edge(self, n, idx) : try : self.edges[ n ].append( idx ) except KeyError : self.edges[ n ] = [] self.edges[ n ].append( idx ) def get_attributes_gexf(self) : buff = "" if self.attributes[ "color" ] != None : buff += "<viz:color r=\"%d\" g=\"%d\" b=\"%d\"/>\n" % (self.attributes[ "color" ][0], self.attributes[ "color" ][1], self.attributes[ "color" ][2]) buff += "<attvalues>\n" buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["class_name"], escape(self.class_name)) buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["method_name"], escape(self.method_name)) buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["descriptor"], escape(self.descriptor)) if self.attributes[ "type" ] != DEFAULT_NODE_TYPE : buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["type"], self.attributes[ "type" ]) if self.attributes[ "permissions" ] != DEFAULT_NODE_PERM : buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["permissions"], self.attributes[ "permissions" ]) buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["permissions_level"], self.attributes[ "permissions_level_name" ]) buff += "<attvalue id=\"%d\" value=\"%s\"/>\n" % (ID_ATTRIBUTES["dynamic_code"], self.attributes[ "dynamic_code" ]) buff += "</attvalues>\n" return buff def get_attributes_gml(self) : buff = "" buff += "<data key=\"d6\">\n" buff += "<y:ShapeNode>\n" height = 10 width = max(len(self.class_name), len(self.method_name)) width = max(width, len(self.descriptor)) buff += "<y:Geometry height=\"%f\" width=\"%f\"/>\n" % (16 * height, 8 * width) if self.attributes[ "color" ] != None : buff += "<y:Fill color=\"#%02x%02x%02x\" transparent=\"false\"/>\n" % (self.attributes[ "color" ][0], self.attributes[ "color" ][1], self.attributes[ "color" ][2]) buff += "<y:NodeLabel alignment=\"left\" autoSizePolicy=\"content\" fontFamily=\"Dialog\" fontSize=\"13\" fontStyle=\"plain\" hasBackgroundColor=\"false\" hasLineColor=\"false\" modelName=\"internal\" modelPosition=\"c\" textColor=\"#000000\" visible=\"true\">\n" label = self.class_name + "\n" + self.method_name + "\n" + self.descriptor buff += escape(label) buff += "</y:NodeLabel>\n" buff += "</y:ShapeNode>\n" buff += "</data>\n" return buff def get_attributes(self) : return self.attributes def get_attribute(self, name) : return self.attributes[ name ] def set_attributes(self, values) : for i in values : if i == "permissions" : self.attributes[ "permissions" ] += values[i] elif i == "permissions_level" : if values[i] > self.attributes[ "permissions_level" ] : self.attributes[ "permissions_level" ] = PERMISSIONS_LEVEL[ values[i] ] self.attributes[ "permissions_level_name" ] = values[i] self.attributes[ "color" ] = COLOR_PERMISSIONS_LEVEL[ values[i] ] elif i == "permissions_details" : self.attributes[ i ].add( values[i] ) else : self.attributes[ i ] = values[i] def add_risk(self, risk) : if risk not in self.risks : self.risks.append( risk ) def add_api(self, perm, api) : if perm not in self.api : self.api[ perm ] = [] if api not in self.api[ perm ] : self.api[ perm ].append( api )
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import re, random, string, cPickle from androguard.core.androconf import error, warning from androguard.core.bytecodes import jvm, dvm from androguard.core.bytecodes.api_permissions import DVM_PERMISSIONS_BY_PERMISSION, DVM_PERMISSIONS_BY_ELEMENT class ContextField : def __init__(self, mode) : self.mode = mode self.details = [] def set_details(self, details) : for i in details : self.details.append( i ) class ContextMethod : def __init__(self) : self.details = [] def set_details(self, details) : for i in details : self.details.append( i ) class ExternalFM : def __init__(self, class_name, name, descriptor) : self.class_name = class_name self.name = name self.descriptor = descriptor def get_class_name(self) : return self.class_name def get_name(self) : return self.name def get_descriptor(self) : return self.descriptor class ToString : def __init__(self, tab) : self.__tab = tab self.__re_tab = {} for i in self.__tab : self.__re_tab[i] = [] for j in self.__tab[i] : self.__re_tab[i].append( re.compile( j ) ) self.__string = "" def push(self, name) : for i in self.__tab : for j in self.__re_tab[i] : if j.match(name) != None : if len(self.__string) > 0 : if i == 'O' and self.__string[-1] == 'O' : continue self.__string += i def get_string(self) : return self.__string class BreakBlock(object) : def __init__(self, _vm, idx) : self._vm = _vm self._start = idx self._end = self._start self._ins = [] self._ops = [] self._fields = {} self._methods = {} def get_ops(self) : return self._ops def get_fields(self) : return self._fields def get_methods(self) : return self._methods def push(self, ins) : self._ins.append(ins) self._end += ins.get_length() def get_start(self) : return self._start def get_end(self) : return self._end def show(self) : for i in self._ins : print "\t\t", i.show(0) ##### JVM ###### FIELDS = { "getfield" : "R", "getstatic" : "R", "putfield" : "W", "putstatic" : "W", } METHODS = [ "invokestatic", "invokevirtual", "invokespecial" ] JVM_TOSTRING = { "O" : jvm.MATH_JVM_OPCODES.keys(), "I" : jvm.INVOKE_JVM_OPCODES, "G" : jvm.FIELD_READ_JVM_OPCODES, "P" : jvm.FIELD_WRITE_JVM_OPCODES, } BREAK_JVM_OPCODES_RE = [] for i in jvm.BREAK_JVM_OPCODES : BREAK_JVM_OPCODES_RE.append( re.compile( i ) ) class Stack : def __init__(self) : self.__elems = [] def gets(self) : return self.__elems def push(self, elem) : self.__elems.append( elem ) def get(self) : return self.__elems[-1] def pop(self) : return self.__elems.pop(-1) def nil(self) : return len(self.__elems) == 0 def insert_stack(self, idx, elems) : if elems != self.__elems : for i in elems : self.__elems.insert(idx, i) idx += 1 def show(self) : nb = 0 if len(self.__elems) == 0 : print "\t--> nil" for i in self.__elems : print "\t-->", nb, ": ", i nb += 1 class StackTraces : def __init__(self) : self.__elems = [] def save(self, idx, i_idx, ins, stack_pickle, msg_pickle) : self.__elems.append( (idx, i_idx, ins, stack_pickle, msg_pickle) ) def get(self) : for i in self.__elems : yield (i[0], i[1], i[2], cPickle.loads( i[3] ), cPickle.loads( i[4] ) ) def show(self) : for i in self.__elems : print i[0], i[1], i[2].get_name() cPickle.loads( i[3] ).show() print "\t", cPickle.loads( i[4] ) def push_objectref(_vm, ins, special, stack, res, ret_v) : value = "OBJ_REF_@_%s" % str(special) stack.push( value ) def push_objectref_l(_vm, ins, special, stack, res, ret_v) : stack.push( "VARIABLE_LOCAL_%d" % special ) def push_objectref_l_i(_vm, ins, special, stack, res, ret_v) : stack.push( "VARIABLE_LOCAL_%d" % ins.get_operands() ) def pop_objectref(_vm, ins, special, stack, res, ret_v) : ret_v.add_return( stack.pop() ) def multi_pop_objectref_i(_vm, ins, special, stack, res, ret_v) : for i in range(0, ins.get_operands()[1]) : stack.pop() def push_objectres(_vm, ins, special, stack, res, ret_v) : value = "" if special[0] == 1 : value += special[1] + "(" + str( res.pop() ) + ") " else : for i in range(0, special[0]) : value += str( res.pop() ) + special[1] value = value[:-1] stack.push( value ) def push_integer_i(_vm, ins, special, stack, res, ret_v) : value = ins.get_operands() stack.push( value ) def push_integer_d(_vm, ins, special, stack, res, ret_v) : stack.push( special ) def push_float_d(_vm, ins, special, stack, res, ret_v) : stack.push( special ) def putfield(_vm, ins, special, stack, res, ret_v) : ret_v.add_return( stack.pop() ) def putstatic(_vm, ins, special, stack, res, ret_v) : stack.pop() def getfield(_vm, ins, special, stack, res, ret_v) : ret_v.add_return( stack.pop() ) stack.push( "FIELD" ) def getstatic(_vm, ins, special, stack, res, ret_v) : stack.push( "FIELD_STATIC" ) def new(_vm, ins, special, stack, res, ret_v) : stack.push( "NEW_OBJ" ) def dup(_vm, ins, special, stack, res, ret_v) : l = [] for i in range(0, special+1) : l.append( stack.pop() ) l.reverse() l.insert( 0, l[-1] ) for i in l : stack.push( i ) def dup2(_vm, ins, special, stack, res, ret_v) : l = [] for i in range(0, special+1) : l.append( stack.pop() ) l.reverse() l.insert( 0, l[-1] ) l.insert( 1, l[-2] ) for i in l : stack.push( i ) #FIXME def ldc(_vm, ins, special, stack, res, ret_v) : #print ins.get_name(), ins.get_operands(), special stack.push( "STRING" ) def invoke(_vm, ins, special, stack, res, ret_v) : desc = ins.get_operands()[-1] param = desc[1:desc.find(")")] ret = desc[desc.find(")")+1:] # print "DESC --->", param, calc_nb( param ), ret, calc_nb( ret ) for i in range(0, calc_nb( param )) : stack.pop() # objectref : static or not for i in range(0, special) : stack.pop() for i in range(0, calc_nb( ret )): stack.push( "E" ) def set_arrayref(_vm, ins, special, stack, res, ret_v) : ret_v.add_msg( "SET VALUE %s %s @ ARRAY REF %s %s" % (special, str(stack.pop()), str(stack.pop()), str(stack.pop())) ) def set_objectref(_vm, ins, special, stack, res, ret_v) : ret_v.add_msg( "SET OBJECT REF %d --> %s" % (special, str(stack.pop())) ) def set_objectref_i(_vm, ins, special, stack, res, ret_v) : ret_v.add_msg( "SET OBJECT REF %d --> %s" % (ins.get_operands(), str(stack.pop())) ) def swap(_vm, ins, special, stack, res, ret_v) : l = stack.pop() l2 = stack.pop() stack.push(l2) stack.push(l) def calc_nb(info) : if info == "" or info == "V" : return 0 if ";" in info : n = 0 for i in info.split(";") : if i != "" : n += 1 return n else : return len(info) - info.count('[') INSTRUCTIONS_ACTIONS = { "aaload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "aastore" : [ { set_arrayref : None } ], "aconst_null" : [ { push_objectref : "null" } ], "aload" : [ { push_objectref_l_i : None } ], "aload_0" : [ { push_objectref_l : 0 } ], "aload_1" : [ { push_objectref_l : 1 } ], "aload_2" : [ { push_objectref_l : 2 } ], "aload_3" : [ { push_objectref_l : 3 } ], "anewarray" : [ { pop_objectref : None }, { push_objectref : [ 1, "ANEWARRAY" ] } ], "areturn" : [ { pop_objectref : None } ], "arraylength" : [ { pop_objectref : None }, { push_objectres : [ 1, 'LENGTH' ] } ], "astore" : [ { set_objectref_i : None } ], "astore_0" : [ { set_objectref : 0 } ], "astore_1" : [ { set_objectref : 1 } ], "astore_2" : [ { set_objectref : 2 } ], "astore_3" : [ { set_objectref : 3 } ], "athrow" : [ { pop_objectref : None }, { push_objectres : [ 1, "throw" ] } ], "baload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "bastore" : [ { set_arrayref : "byte" } ], "bipush" : [ { push_integer_i : None } ], "caload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "castore" : [ { set_arrayref : "char" } ], "checkcast" : [ { pop_objectref : None }, { push_objectres : [ 1, "checkcast" ] } ], "d2f" : [ { pop_objectref : None }, { push_objectres : [ 1, 'float' ] } ], "d2i" : [ { pop_objectref : None }, { push_objectres : [ 1, 'integer' ] } ], "d2l" : [ { pop_objectref : None }, { push_objectres : [ 1, 'long' ] } ], "dadd" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '+' ] } ], "daload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "dastore" : [ { set_arrayref : "double" } ], "dcmpg" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "dcmpl" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "dconst_0" : [ { push_float_d : 0.0 } ], "dconst_1" : [ { push_float_d : 1.0 } ], "ddiv" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '&' ] } ], "dload" : [ { push_objectref_l_i : None } ], "dload_0" : [ { push_objectref_l : 0 } ], "dload_1" : [ { push_objectref_l : 1 } ], "dload_2" : [ { push_objectref_l : 2 } ], "dload_3" : [ { push_objectref_l : 3 } ], "dmul" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '*' ] } ], "dneg" : [ { pop_objectref : None }, { push_objectres : [ 1, '-' ] } ], "drem" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, 'rem' ] } ], "dreturn" : [ { pop_objectref : None } ], "dstore" : [ { set_objectref_i : None } ], "dstore_0" : [ { set_objectref : 0 } ], "dstore_1" : [ { set_objectref : 1 } ], "dstore_2" : [ { set_objectref : 2 } ], "dstore_3" : [ { set_objectref : 3 } ], "dsub" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '-' ] } ], "dup" : [ { dup : 0 } ], "dup_x1" : [ { dup : 1 } ], "dup_x2" : [ { dup : 2 } ], "dup2" : [ { dup2 : 0 } ], "dup2_x1" : [ { dup2 : 1 } ], "dup2_x2" : [ { dup2 : 2 } ], "f2d" : [ { pop_objectref : None }, { push_objectres : [ 1, 'double' ] } ], "f2i" : [ { pop_objectref : None }, { push_objectres : [ 1, 'integer' ] } ], "f2l" : [ { pop_objectref : None }, { push_objectres : [ 1, 'long' ] } ], "fadd" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '+' ] } ], "faload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "fastore" : [ { set_arrayref : "float" } ], "fcmpg" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "fcmpl" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "fconst_0" : [ { push_float_d : 0.0 } ], "fconst_1" : [ { push_float_d : 1.0 } ], "fconst_2" : [ { push_float_d : 2.0 } ], "fdiv" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '&' ] } ], "fload" : [ { push_objectref_l_i : None } ], "fload_0" : [ { push_objectref_l : 0 } ], "fload_1" : [ { push_objectref_l : 1 } ], "fload_2" : [ { push_objectref_l : 2 } ], "fload_3" : [ { push_objectref_l : 3 } ], "fmul" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '*' ] } ], "fneg" : [ { pop_objectref : None }, { push_objectres : [ 1, '-' ] } ], "freturn" : [ { pop_objectref : None } ], "fstore" : [ { set_objectref_i : None } ], "fstore_0" : [ { set_objectref : 0 } ], "fstore_1" : [ { set_objectref : 1 } ], "fstore_2" : [ { set_objectref : 2 } ], "fstore_3" : [ { set_objectref : 3 } ], "fsub" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '-' ] } ], "getfield" : [ { getfield : None } ], "getstatic" : [ { getstatic : None } ], "goto" : [ {} ], "goto_w" : [ {} ], "i2b" : [ { pop_objectref : None }, { push_objectres : [ 1, 'byte' ] } ], "i2c" : [ { pop_objectref : None }, { push_objectres : [ 1, 'char' ] } ], "i2d" : [ { pop_objectref : None }, { push_objectres : [ 1, 'double' ] } ], "i2f" : [ { pop_objectref : None }, { push_objectres : [ 1, 'float' ] } ], "i2l" : [ { pop_objectref : None }, { push_objectres : [ 1, 'long' ] } ], "i2s" : [ { pop_objectref : None }, { push_objectres : [ 1, 'string' ] } ], "iadd" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '+' ] } ], "iaload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "iand" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '&' ] } ], "iastore" : [ { set_arrayref : "int" } ], "iconst_m1" : [ { push_integer_d : -1 } ], "iconst_0" : [ { push_integer_d : 0 } ], "iconst_1" : [ { push_integer_d : 1 } ], "iconst_2" : [ { push_integer_d : 2 } ], "iconst_3" : [ { push_integer_d : 3 } ], "iconst_4" : [ { push_integer_d : 4 } ], "iconst_5" : [ { push_integer_d : 5 } ], "idiv" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '/' ] } ], "if_acmpeq" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_acmpne" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmpeq" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmpne" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmplt" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmpge" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmpgt" : [ { pop_objectref : None }, { pop_objectref : None } ], "if_icmple" : [ { pop_objectref : None }, { pop_objectref : None } ], "ifeq" : [ { pop_objectref : None } ], "ifne" : [ { pop_objectref : None } ], "iflt" : [ { pop_objectref : None } ], "ifge" : [ { pop_objectref : None } ], "ifgt" : [ { pop_objectref : None } ], "ifle" : [ { pop_objectref : None } ], "ifnonnull" : [ { pop_objectref : None } ], "ifnull" : [ { pop_objectref : None } ], "iinc" : [ {} ], "iload" : [ { push_objectref_l_i : None } ], "iload_1" : [ { push_objectref_l : 1 } ], "iload_2" : [ { push_objectref_l : 2 } ], "iload_3" : [ { push_objectref_l : 3 } ], "imul" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '*' ] } ], "ineg" : [ { pop_objectref : None }, { push_objectres : [ 1, '-' ] } ], "instanceof" : [ { pop_objectref : None }, { push_objectres : [ 1, 'instanceof' ] } ], "invokeinterface" : [ { invoke : 1 } ], "invokespecial" : [ { invoke : 1 } ], "invokestatic" : [ { invoke : 0 } ], "invokevirtual": [ { invoke : 1 } ], "ior" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '|' ] } ], "irem" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, 'REM' ] } ], "ireturn" : [ { pop_objectref : None } ], "ishl" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '<<' ] } ], "ishr" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '>>' ] } ], "istore" : [ { set_objectref_i : None } ], "istore_0" : [ { set_objectref : 0 } ], "istore_1" : [ { set_objectref : 1 } ], "istore_2" : [ { set_objectref : 2 } ], "istore_3" : [ { set_objectref : 3 } ], "isub" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '-' ] } ], "iushr" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '>>' ] } ], "ixor" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '^' ] } ], "jsr" : [ { push_integer_i : None } ], "jsr_w" : [ { push_integer_i : None } ], "l2d" : [ { pop_objectref : None }, { push_objectres : [ 1, 'double' ] } ], "l2f" : [ { pop_objectref : None }, { push_objectres : [ 1, 'float' ] } ], "l2i" : [ { pop_objectref : None }, { push_objectres : [ 1, 'integer' ] } ], "ladd" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '+' ] } ], "laload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "land" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '&' ] } ], "lastore" : [ { set_arrayref : "long" } ], "lcmp" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "lconst_0" : [ { push_float_d : 0.0 } ], "lconst_1" : [ { push_float_d : 1.0 } ], "ldc" : [ { ldc : None } ], "ldc_w" : [ { ldc : None } ], "ldc2_w" : [ { ldc : None } ], "ldiv" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '/' ] } ], "lload" : [ { push_objectref_l_i : None } ], "lload_0" : [ { push_objectref_l : 0 } ], "lload_1" : [ { push_objectref_l : 1 } ], "lload_2" : [ { push_objectref_l : 2 } ], "lload_3" : [ { push_objectref_l : 3 } ], "lmul" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '*' ] } ], "lneg" : [ { pop_objectref : None }, { push_objectres : [ 1, '-' ] } ], "lookupswitch" : [ { pop_objectref : None } ], "lor" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '|' ] } ], "lrem" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, 'REM' ] } ], "lreturn" : [ { pop_objectref : None } ], "lshl" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '<<' ] } ], "lshr" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '>>' ] } ], "lstore" : [ { set_objectref_i : None } ], "lstore_0" : [ { set_objectref : 0 } ], "lstore_1" : [ { set_objectref : 1 } ], "lstore_2" : [ { set_objectref : 2 } ], "lstore_3" : [ { set_objectref : 3 } ], "lsub" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '-' ] } ], "lushr" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '>>' ] } ], "lxor" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectres : [ 2, '^' ] } ], "monitorenter" : [ { pop_objectref : None } ], "monitorexit" : [ { pop_objectref : None } ], "multianewarray" : [ { multi_pop_objectref_i : None }, { push_objectref : 0 } ], "new" : [ { new : None } ], "newarray" : [ { pop_objectref : None }, { push_objectref : [ 1, "NEWARRAY" ] } ], "nop" : [ {} ], "pop" : [ { pop_objectref : None } ], "pop2" : [ { pop_objectref : None }, { pop_objectref : None } ], "putfield" : [ { putfield : None }, { pop_objectref : None } ], "putstatic" : [ { putstatic : None } ], "ret" : [ {} ], "return" : [ {} ], "saload" : [ { pop_objectref : None }, { pop_objectref : None }, { push_objectref : 0 } ], "sastore" : [ { set_arrayref : "short" } ], "sipush" : [ { push_integer_i : None } ], "swap" : [ { swap : None } ], "tableswitch" : [ { pop_objectref : None } ], "wide" : [ {} ], } class ReturnValues : def __init__(self) : self.__elems = [] self.__msgs = [] def add_msg(self, e) : self.__msgs.append( e ) def add_return(self, e) : self.__elems.append( e ) def get_msg(self) : return self.__msgs def get_return(self) : return self.__elems class ExternalMethod : def __init__(self, class_name, name, descriptor) : self.__class_name = class_name self.__name = name self.__descriptor = descriptor def get_name(self) : return "M@[%s][%s]-[%s]" % (self.__class_name, self.__name, self.__descriptor) def set_fathers(self, f) : pass class JVMBasicBlock : def __init__(self, start, vm, method, context) : self.__vm = vm self.method = method self.context = context self.__stack = Stack() self.stack_traces = StackTraces() self.ins = [] self.fathers = [] self.childs = [] self.start = start self.end = self.start self.break_blocks = [] self.free_blocks_offsets = [] self.name = "%s-BB@0x%x" % (self.method.get_name(), self.start) def get_stack(self) : return self.__stack.gets() def get_method(self) : return self.method def get_name(self) : return self.name def get_start(self) : return self.start def get_end(self) : return self.end def get_last(self) : return self.ins[-1] def push(self, i) : self.ins.append( i ) self.end += i.get_length() def set_fathers(self, f) : self.fathers.append( f ) def set_childs(self, values) : # print self, self.start, self.end, values, self.ins[-1].get_name() if values == [] : next_block = self.context.get_basic_block( self.end + 1 ) if next_block != None : self.childs.append( ( self.end - self.ins[-1].get_length(), self.end, next_block ) ) else : for i in values : #print i, self.context.get_basic_block( i ) if i != -1 : self.childs.append( ( self.end - self.ins[-1].get_length(), i, self.context.get_basic_block( i ) ) ) for c in self.childs : if c[2] != None : c[2].set_fathers( ( c[1], c[0], self ) ) def prev_free_block_offset(self, idx=0) : last = -1 #print "IDX", idx, self.free_blocks_offsets if self.free_blocks_offsets == [] : return -1 for i in self.free_blocks_offsets : if i <= idx : last = i else : return last return last def random_free_block_offset(self) : return self.free_blocks_offsets[ random.randint(0, len(self.free_blocks_offsets) - 1) ] def next_free_block_offset(self, idx=0) : #print idx, self.__free_blocks_offsets for i in self.free_blocks_offsets : if i > idx : return i return -1 def get_random_free_block_offset(self) : return self.free_blocks_offsets[ random.randint(0, len(self.free_blocks_offsets) - 1) ] def get_random_break_block(self) : return self.break_blocks[ random.randint(0, len(self.break_blocks) - 1) ] def get_break_block(self, idx) : for i in self.break_blocks : if idx >= i.get_start() and idx <= i.get_end() : return i return None def analyze_break_blocks(self) : idx = self.get_start() current_break = JVMBreakBlock( self.__vm, idx ) self.break_blocks.append(current_break) for i in self.ins : name = i.get_name() ##################### Break Block ######################## match = False for j in BREAK_JVM_OPCODES_RE : if j.match(name) != None : match = True break current_break.push( i ) if match == True : current_break.analyze() current_break = JVMBreakBlock( self.__vm, current_break.get_end() ) self.break_blocks.append( current_break ) ######################################################### idx += i.get_length() def analyze(self) : idx = 0 for i in self.ins : ################### TAINTED LOCAL VARIABLES ################### if "load" in i.get_name() or "store" in i.get_name() : action = i.get_name() access_flag = [ "R", "load" ] if "store" in action : access_flag = [ "W", "store" ] if "_" in action : name = i.get_name().split(access_flag[1]) value = name[1][-1] else : value = i.get_operands() variable_name = "%s-%s" % (i.get_name()[0], value) self.context.get_tainted_variables().add( variable_name, TAINTED_LOCAL_VARIABLE, self.method ) self.context.get_tainted_variables().push_info( TAINTED_LOCAL_VARIABLE, variable_name, (access_flag[0], idx, self, self.method) ) ######################################################### ################### TAINTED FIELDS ################### elif i.get_name() in FIELDS : o = i.get_operands() desc = getattr(self.__vm, "get_field_descriptor")(o[0], o[1], o[2]) # It's an external #if desc == None : # desc = ExternalFM( o[0], o[1], o[2] ) # print "RES", res, "-->", desc.get_name() self.context.get_tainted_variables().push_info( TAINTED_FIELD, [o[0], o[1], o[2]], (FIELDS[ i.get_name() ][0], idx, self, self.method) ) ######################################################### ################### TAINTED PACKAGES ################### elif "new" in i.get_name() or "invoke" in i.get_name() or "getstatic" in i.get_name() : if "new" in i.get_name() : self.context.get_tainted_packages().push_info( i.get_operands(), (TAINTED_PACKAGE_CREATE, idx, self, self.method) ) else : self.context.get_tainted_packages().push_info( i.get_operands()[0], (TAINTED_PACKAGE_CALL, idx, self, self.method, i.get_operands()[1], i.get_operands()[2]) ) ######################################################### ################### TAINTED INTEGERS ################### if "ldc" == i.get_name() : o = i.get_operands() if o[0] == "CONSTANT_Integer" : self.context.get_tainted_integers().push_info( i, (o[1], idx, self, self.method) ) elif "sipush" in i.get_name() : self.context.get_tainted_integers().push_info( i, (i.get_operands(), idx, self, self.method) ) elif "bipush" in i.get_name() : self.context.get_tainted_integers().push_info( i, (i.get_operands(), idx, self, self.method) ) ######################################################### idx += i.get_length() def set_exception(self, exception_analysis) : pass # FIXME : create a recursive function to follow the cfg, because it does not work with obfuscator def analyze_code(self) : self.analyze_break_blocks() #print "ANALYZE CODE -->", self.name d = {} for i in self.fathers : # print "\t FATHER ->", i[2].get_name(), i[2].get_stack(), i[0], i[1] d[ i[0] ] = i[2] self.free_blocks_offsets.append( self.get_start() ) idx = 0 for i in self.ins : # print i.get_name(), self.start + idx, idx # i.show(idx) if self.start + idx in d : self.__stack.insert_stack( 0, d[ self.start + idx ].get_stack() ) ret_v = ReturnValues() res = [] try : #print i.get_name(), i.get_name() in INSTRUCTIONS_ACTIONS if INSTRUCTIONS_ACTIONS[ i.get_name() ] == [] : print "[[[[ %s is not yet implemented ]]]]" % i.get_name() raise("ooops") i_idx = 0 for actions in INSTRUCTIONS_ACTIONS[ i.get_name() ] : for action in actions : action( self.__vm, i, actions[action], self.__stack, res, ret_v ) for val in ret_v.get_return() : res.append( val ) #self.__stack.show() self.stack_traces.save( idx, i_idx, i, cPickle.dumps( self.__stack ), cPickle.dumps( ret_v.get_msg() ) ) i_idx += 1 except KeyError : print "[[[[ %s is not in INSTRUCTIONS_ACTIONS ]]]]" % i.get_name() except IndexError : print "[[[[ Analysis failed in %s-%s-%s ]]]]" % (self.method.get_class_name(), self.method.get_name(), self.method.get_descriptor()) idx += i.get_length() if self.__stack.nil() == True and i != self.ins[-1] : self.free_blocks_offsets.append( idx + self.get_start() ) def show(self) : print "\t@", self.name idx = 0 nb = 0 for i in self.ins : print "\t\t", nb, idx, i.show(nb) nb += 1 idx += i.get_length() print "" print "\t\tFree blocks offsets --->", self.free_blocks_offsets print "\t\tBreakBlocks --->", len(self.break_blocks) print "\t\tF --->", ', '.join( i[2].get_name() for i in self.fathers ) print "\t\tC --->", ', '.join( i[2].get_name() for i in self.childs ) self.stack_traces.show() def get_ins(self) : return self.ins class JVMBreakBlock(BreakBlock) : def __init__(self, _vm, idx) : super(JVMBreakBlock, self).__init__(_vm, idx) self.__info = { "F" : [ "get_field_descriptor", self._fields, ContextField ], "M" : [ "get_method_descriptor", self._methods, ContextMethod ], } def get_free(self) : if self._ins == [] : return False if "store" in self._ins[-1].get_name() : return True elif "putfield" in self._ins[-1].get_name() : return True return False def analyze(self) : ctt = [] stack = Stack() for i in self._ins : v = self.trans(i) if v != None : ctt.append( v ) t = "" for mre in jvm.MATH_JVM_RE : if mre[0].match( i.get_name() ) : self._ops.append( mre[1] ) break # Woot it's a field ! if i.get_name() in FIELDS : t = "F" elif i.get_name() in METHODS : t = "M" if t != "" : o = i.get_operands() desc = getattr(self._vm, self.__info[t][0])(o[0], o[1], o[2]) # It's an external if desc == None : desc = ExternalFM( o[0], o[1], o[2] ) if desc not in self.__info[t][1] : self.__info[t][1][desc] = [] if t == "F" : self.__info[t][1][desc].append( self.__info[t][2]( FIELDS[ i.get_name() ][0] ) ) # print "RES", res, "-->", desc.get_name() # self.__tf.push_info( desc, [ FIELDS[ i.get_name() ][0], res ] ) elif t == "M" : self.__info[t][1][desc].append( self.__info[t][2]() ) for i in self._fields : for k in self._fields[i] : k.set_details( ctt ) for i in self._methods : for k in self._methods[i] : k.set_details( ctt ) def trans(self, i) : v = i.get_name()[0:2] if v == "il" or v == "ic" or v == "ia" or v == "si" or v == "bi" : return "I" if v == "ba" : return "B" if v == "if" : return "IF" if v == "ir" : return "RET" if "and" in i.get_name() : return "&" if "add" in i.get_name() : return "+" if "sub" in i.get_name() : return "-" if "xor" in i.get_name() : return "^" if "ldc" in i.get_name() : return "I" if "invokevirtual" in i.get_name() : return "M" + i.get_operands()[2] if "getfield" in i.get_name() : return "F" + i.get_operands()[2] DVM_FIELDS_ACCESS = { "iget" : "R", "iget-wide" : "R", "iget-object" : "R", "iget-boolean" : "R", "iget-byte" : "R", "iget-char" : "R", "iget-short" : "R", "iput" : "W", "iput-wide" : "W", "iput-object" : "W", "iput-boolean" : "W", "iput-byte" : "W", "iput-char" : "W", "iput-short" : "W", "sget" : "R", "sget-wide" : "R", "sget-object" : "R", "sget-boolean" : "R", "sget-byte" : "R", "sget-char" : "R", "sget-short" : "R", "sput" : "W", "sput-wide" : "W", "sput-object" : "W", "sput-boolean" : "W", "sput-byte" : "W", "sput-char" : "W", "sput-short" : "W", } class DVMBasicBlock : def __init__(self, start, vm, method, context) : self.__vm = vm self.method = method self.context = context self.ins = [] self.fathers = [] self.childs = [] self.start = start self.end = self.start self.break_blocks = [] self.free_blocks_offsets = [] self.special_ins = {} self.name = "%s-BB@0x%x" % (self.method.get_name(), self.start) self.exception_analysis = None def get_method(self) : return self.method def get_name(self) : return self.name def get_start(self) : return self.start def get_end(self) : return self.end def get_last(self) : return self.ins[-1] def push(self, i) : self.ins.append( i ) self.end += i.get_length() def set_fathers(self, f) : self.fathers.append( f ) def set_childs(self, values) : #print self, self.start, self.end, values, self.ins[-1].get_name() if values == [] : next_block = self.context.get_basic_block( self.end + 1 ) if next_block != None : self.childs.append( ( self.end - self.ins[-1].get_length(), self.end, next_block ) ) else : for i in values : if i != -1 : next_block = self.context.get_basic_block( i ) if next_block != None : self.childs.append( ( self.end - self.ins[-1].get_length(), i, next_block) ) for c in self.childs : if c[2] != None : c[2].set_fathers( ( c[1], c[0], self ) ) def analyze(self) : idx = 0 for i in self.ins : op_value = i.get_op_value() #if i.get_name() in DVM_FIELDS_ACCESS : if (op_value >= 0x52 and op_value <= 0x6d) : desc = self.__vm.get_cm_field( i.get_ref_kind() ) self.context.get_tainted_variables().push_info( TAINTED_FIELD, desc, (DVM_FIELDS_ACCESS[ i.get_name() ][0], idx, self, self.method) ) #elif "invoke" in i.get_name() : elif (op_value >= 0x6e and op_value <= 0x72) or (op_value >= 0x74 and op_value <= 0x78) : idx_meth = i.get_ref_kind() method_info = self.__vm.get_cm_method( idx_meth ) self.context.get_tainted_packages().push_info( method_info[0], (TAINTED_PACKAGE_CALL, idx, self, self.method, method_info[1], method_info[2][0] + method_info[2][1]) ) #method = self.__vm.get_class_manager().get_method_ref( idx_meth ) #self.context.tags.emit( method ) #elif "new-instance" in i.get_name() : elif op_value == 0x22 : type_info = self.__vm.get_cm_type( i.get_ref_kind() ) self.context.get_tainted_packages().push_info( type_info, (TAINTED_PACKAGE_CREATE, idx, self, self.method) ) #elif "const-string" in i.get_name() : elif (op_value >= 0x1a and op_value <= 0x1b) : string_name = self.__vm.get_cm_string( i.get_ref_kind() ) self.context.get_tainted_variables().add( string_name, TAINTED_STRING ) self.context.get_tainted_variables().push_info( TAINTED_STRING, string_name, ("R", idx, self, self.method) ) elif op_value == 0x26 or (op_value >= 0x2b and op_value <= 0x2c) : code = self.method.get_code().get_bc() self.special_ins[ i ] = code.get_ins_off( self.get_start() + idx + i.get_ref_off() * 2 ) idx += i.get_length() def get_special_ins(self, ins) : try : return self.special_ins[ ins ] except : return None def set_exception(self, exception_analysis) : self.exception_analysis = exception_analysis def analyze_code(self) : pass def get_ins(self) : return self.ins TAINTED_LOCAL_VARIABLE = 0 TAINTED_FIELD = 1 TAINTED_STRING = 2 class Path : def __init__(self, info, info_obj=None) : self.access_flag = info[0] self.idx = info[1] self.bb = info[2] self.method = info[3] self.info_obj = info_obj def get_offset(self) : return self.bb.start + self.idx def get_class_name(self) : if isinstance(self.info_obj, list) : return self.info_obj[0] return self.info_obj.get_class_name() def get_name(self) : if isinstance(self.info_obj, list) : return self.info_obj[1] return self.info_obj.get_name() def get_descriptor(self) : if isinstance(self.info_obj, list) : return self.info_obj[2] return self.info_obj.get_descriptor() def get_access_flag(self) : return self.access_flag def get_idx(self) : return self.idx def get_bb(self) : return self.bb def get_method(self) : return self.method class TaintedVariable : def __init__(self, var, _type) : self.var = var self.type = _type self.paths = [] def get_type(self) : return self.type def get_info(self) : if self.type == TAINTED_FIELD : return [ self.var[0], self.var[2], self.var[1] ] return self.var def push(self, info) : p = Path( info, self.var ) self.paths.append( p ) return p def get_paths_access(self, mode) : for i in self.paths : if i.get_access_flag() in mode : yield i def get_all_paths(self) : return self.paths def get_paths(self) : for i in self.paths : yield i def get_paths_length(self) : return len(self.paths) def show_paths(self) : for path in self.paths : print path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) class TaintedVariables : def __init__(self, _vm) : self.__vm = _vm self.__vars = { TAINTED_LOCAL_VARIABLE : {}, TAINTED_FIELD : {}, TAINTED_STRING : {}, } self.__methods = { TAINTED_FIELD : {}, TAINTED_STRING : {}, } # functions to get particulars elements def get_string(self, s) : try : return self.__vars[ TAINTED_STRING ][ s ] except KeyError : return None def get_field(self, class_name, name, descriptor) : key = class_name + descriptor + name try : return self.__vars[ TAINTED_FIELD ] [ key ] except KeyError : return None # permission functions def get_permissions_method(self, method) : permissions = [] for f, f1 in self.get_fields() : data = "%s-%s-%s" % (f1[0], f1[1], f1[2]) if data in DVM_PERMISSIONS_BY_ELEMENT : for path in f.get_all_paths() : if path.get_method() == method : if DVM_PERMISSIONS_BY_ELEMENT[ data ] not in permissions : permissions.append( DVM_PERMISSIONS_BY_ELEMENT[ data ] ) return permissions def get_permissions(self, permissions_needed) : """ @param permissions_needed : a list of restricted permissions to get ([] returns all permissions) @rtype : a dictionnary of permissions' paths """ permissions = {} pn = permissions_needed if permissions_needed == [] : pn = DVM_PERMISSIONS_BY_PERMISSION.keys() for f, f1 in self.get_fields() : data = "%s-%s-%s" % (f.var[0], f.var[2], f.var[1]) if data in DVM_PERMISSIONS_BY_ELEMENT : if DVM_PERMISSIONS_BY_ELEMENT[ data ] in pn : try : permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ].extend( f.get_all_paths() ) except KeyError : permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ] = [] permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ].extend( f.get_all_paths() ) return permissions # global functions def get_strings(self) : for i in self.__vars[ TAINTED_STRING ] : yield self.__vars[ TAINTED_STRING ][ i ], i def get_fields(self) : for i in self.__vars[ TAINTED_FIELD ] : yield self.__vars[ TAINTED_FIELD ][ i ], i # specifics functions def get_strings_by_method(self, method) : try : return self.__methods[ TAINTED_STRING ][ method ] except KeyError : return {} def get_fields_by_method(self, method) : try : return self.__methods[ TAINTED_FIELD ][ method ] except KeyError : return {} def get_local_variables(self, _method) : try : return self.__vars[ TAINTED_LOCAL_VARIABLE ][ _method ] except KeyError : return None def get_fields_by_bb(self, bb) : l = [] for i in self.__vars[ TAINTED_FIELD ] : for j in self.__vars[ TAINTED_FIELD ][i].get_paths() : if j.get_bb() == bb : l.append( (i, j.get_access_flag()) ) return l def add(self, var, _type, _method=None) : if _type == TAINTED_FIELD : key = var[0] + var[1] + var[2] if key not in self.__vars[ TAINTED_FIELD ] : self.__vars[ TAINTED_FIELD ][ key ] = TaintedVariable( var, _type ) elif _type == TAINTED_STRING : if var not in self.__vars[ TAINTED_STRING ] : self.__vars[ TAINTED_STRING ][ var ] = TaintedVariable( var, _type ) elif _type == TAINTED_LOCAL_VARIABLE : if _method not in self.__vars[ TAINTED_LOCAL_VARIABLE ] : self.__vars[ TAINTED_LOCAL_VARIABLE ][ _method ] = {} if var not in self.__vars[ TAINTED_LOCAL_VARIABLE ][ _method ] : self.__vars[ TAINTED_LOCAL_VARIABLE ][ _method ][ var ] = TaintedVariable( var, _type ) def push_info(self, _type, var, info) : if _type == TAINTED_FIELD : self.add( var, _type ) key = var[0] + var[1] + var[2] p = self.__vars[ _type ][ key ].push( info ) #try : # self.__methods[ _type ][ p.get_method() ][ key ].append( p ) #except KeyError : # try : # self.__methods[ _type ][ p.get_method() ][ key ] = [] # except KeyError : # self.__methods[ _type ][ p.get_method() ] = {} # self.__methods[ _type ][ p.get_method() ][ key ] = [] # self.__methods[ _type ][ p.get_method() ][ key ].append( p ) elif _type == TAINTED_STRING : self.add( var, _type ) # p = self.__vars[ _type ][ var ].push( info ) #try : # self.__methods[ _type ][ p.get_method() ][ var ].append( p ) #except KeyError : # try : # self.__methods[ _type ][ p.get_method() ][ var ] = [] # except KeyError : # self.__methods[ _type ][ p.get_method() ] = {} # self.__methods[ _type ][ p.get_method() ][ var ] = [] # self.__methods[ _type ][ p.get_method() ][ var ].append( p ) elif _type == TAINTED_LOCAL_VARIABLE : self.add( var, _type, info[-1] ) self.__vars[ TAINTED_LOCAL_VARIABLE ][ info[-1] ][ var ].push( info ) class PathI(Path) : def __init__(self, info) : Path.__init__( self, info ) self.value = info[0] def get_value(self) : return self.value class TaintedInteger : def __init__(self, info) : self.info = PathI( info ) def get(self) : return self.info class TaintedIntegers : def __init__(self, _vm) : self.__vm = _vm self.__integers = [] self.__hash = {} def get_method(self, method) : try : return self.__hash[ method ] except KeyError : return [] def push_info(self, ins, info) : #print ins, ins.get_name(), ins.get_operands(), info ti = TaintedInteger( info ) self.__integers.append( ti ) try : self.__hash[ info[-1] ].append( ti ) except KeyError : self.__hash[ info[-1] ] = [] self.__hash[ info[-1] ].append( ti ) def get_integers(self) : for i in self.__integers : yield i TAINTED_PACKAGE_CREATE = 0 TAINTED_PACKAGE_CALL = 1 TAINTED_PACKAGE = { TAINTED_PACKAGE_CREATE : "C", TAINTED_PACKAGE_CALL : "M" } def show_Path(paths) : """ Show paths of packages @param paths : a list of paths L{PathP} """ for path in paths : if isinstance(path, PathP) : if path.get_access_flag() == TAINTED_PACKAGE_CALL : print "%s %s %s (@%s-0x%x) ---> %s %s %s" % (path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), \ path.get_bb().get_name(), path.get_bb().start + path.get_idx(), \ path.get_class_name(), path.get_name(), path.get_descriptor()) else : print "%s %s %s (@%s-0x%x) ---> %s" % (path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), \ path.get_bb().get_name(), path.get_bb().start + path.get_idx(), \ path.get_class_name()) else : print "%s %s %s ---> %s %s %s %s %s %x" % (path.get_class_name(), path.get_name(), path.get_descriptor(), path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), (path.get_bb().start + path.get_idx() ) ) def show_PathVariable(paths) : for path in paths : print path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % ( path.get_bb().start + path.get_idx()) class PathP(Path) : def __init__(self, info, class_name) : Path.__init__( self, info ) self.class_name = class_name if info[0] == TAINTED_PACKAGE_CALL : self.name = info[-2] self.descriptor = info[-1] def get_class_name(self) : return self.class_name def get_name(self) : return self.name def get_descriptor(self) : return self.descriptor class TaintedPackage : def __init__(self, name) : self.name = name self.paths = { TAINTED_PACKAGE_CREATE : [], TAINTED_PACKAGE_CALL : [] } def get_name(self) : return self.name # FIXME : remote it to use get_name def get_info(self) : return self.name def gets(self) : return self.paths def push(self, info) : p = PathP( info, self.get_name() ) self.paths[ info[0] ].append( p ) return p def get_objects_paths(self) : return self.paths[ TAINTED_PACKAGE_CREATE ] def search_method(self, name, descriptor) : """ @param name : a regexp for the name of the method @param descriptor : a regexp for the descriptor of the method @rtype : a list of called paths """ l = [] m_name = re.compile(name) m_descriptor = re.compile(descriptor) for path in self.paths[ TAINTED_PACKAGE_CALL ] : if m_name.match( path.get_name() ) != None and m_descriptor.match( path.get_descriptor() ) != None : l.append( path ) return l def get_method(self, name, descriptor) : l = [] for path in self.paths[ TAINTED_PACKAGE_CALL ] : if path.get_name() == name and path.get_descriptor() == descriptor : l.append( path ) return l def get_paths(self) : for i in self.paths : for j in self.paths[ i ] : yield j def get_paths_length(self) : x = 0 for i in self.paths : x += len(self.paths[ i ]) return x def get_methods(self) : return [ path for path in self.paths[ TAINTED_PACKAGE_CALL ] ] def show(self, format) : print self.name for _type in self.paths : print "\t -->", _type if _type == TAINTED_PACKAGE_CALL : for path in sorted(self.paths[ _type ], key=lambda x: getattr(x, format)()) : print "\t\t => %s %s <-- %s@%x in %s" % (path.get_name(), path.get_descriptor(), path.get_bb().get_name(), path.get_idx(), path.get_method().get_name()) else : for path in self.paths[ _type ] : print "\t\t => %s@%x in %s" % (path.get_bb().get_name(), path.get_idx(), path.get_method().get_name()) def show_Permissions( dx ) : """ Show where permissions are used in a specific application @param dx : the analysis virtual machine """ p = dx.get_permissions( [] ) for i in p : print i, ":" show_Path( p[i] ) def show_DynCode(dx) : """ Show where dynamic code is used @param dx : the analysis virtual machine """ paths = dx.tainted_packages.search_methods( "Ldalvik/system/DexClassLoader;", ".", ".") show_Path( paths ) def show_NativeMethods(dx) : """ Show the native methods @param dx : the analysis virtual machine """ d = dx.get_vm() for i in d.get_methods() : if i.get_access_flags() & 0x100 : print i.get_class_name(), i.get_name(), i.get_descriptor() def show_ReflectionCode(dx) : """ Show the reflection code @param dx : the analysis virtual machine """ paths = dx.tainted_packages.search_methods( "Ljava/lang/reflect/Method;", ".", ".") show_Path( paths ) def is_dyn_code(dx) : """ Dynamic code loading is present ? @param dx : the analysis virtual machine @rtype : boolean """ paths = dx.tainted_packages.search_methods( "Ldalvik/system/DexClassLoader;", ".", ".") if paths != [] : return True return False def is_reflection_code(dx) : """ Reflection is present ? @param dx : the analysis virtual machine @rtype : boolean """ paths = dx.tainted_packages.search_methods( "Ljava/lang/reflect/Method;", ".", ".") if paths != [] : return True return False def is_native_code(dx) : """ Native code is present ? @param dx : the analysis virtual machine @rtype : boolean """ paths = dx.tainted_packages.search_methods( "Ljava/lang/System;", "loadLibrary", ".") if paths != [] : return True return False class TaintedPackages : def __init__(self, _vm) : self.__vm = _vm self.__packages = {} self.__methods = {} def _add_pkg(self, name) : if name not in self.__packages : self.__packages[ name ] = TaintedPackage( name ) def push_info(self, class_name, info) : self._add_pkg( class_name ) p = self.__packages[ class_name ].push( info ) try : self.__methods[ p.get_method() ][ class_name ].append( p ) except : try : self.__methods[ p.get_method() ][ class_name ] = [] except : self.__methods[ p.get_method() ] = {} self.__methods[ p.get_method() ][ class_name ] = [] self.__methods[ p.get_method() ][ class_name ].append( p ) def get_packages_by_method(self, method) : try : return self.__methods[ method ] except KeyError : return {} def get_package(self, name) : return self.__packages[ name ] def get_packages_by_bb(self, bb): """ @rtype : return a list of packaged used in a basic block """ l = [] for i in self.__packages : paths = self.__packages[i].gets() for j in paths : for k in paths[j] : if k.get_bb() == bb : l.append( (i, k.get_access_flag(), k.get_idx(), k.get_method()) ) return l def get_packages(self) : for i in self.__packages : yield self.__packages[ i ], i def get_internal_packages_from_package(self, package) : classes = self.__vm.get_classes_names() l = [] for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method().get_class_name() == package and j.get_class_name() in classes : l.append( j ) return l def get_internal_packages(self) : """ @rtype : return a list of the internal packages called in the application """ classes = self.__vm.get_classes_names() l = [] for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method().get_class_name() in classes and m.get_info() in classes : if j.get_access_flag() == TAINTED_PACKAGE_CALL : l.append( j ) return l def get_internal_new_packages(self) : """ @rtype : return a list of the internal packages called in the application """ classes = self.__vm.get_classes_names() l = [] for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method().get_class_name() in classes and m.get_info() in classes : if j.get_access_flag() == TAINTED_PACKAGE_CREATE : l.append( j ) return l def get_external_packages(self) : """ @rtype : return a list of the external packages called in the application """ classes = self.__vm.get_classes_names() l = [] for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method().get_class_name() in classes and m.get_info() not in classes : if j.get_access_flag() == TAINTED_PACKAGE_CALL : l.append( j ) return l def search_packages(self, package_name) : """ @param package_name : a regexp for the name of the package @rtype : a list of called packages' paths """ ex = re.compile( package_name ) l = [] for m, _ in self.get_packages() : if ex.match( m.get_info() ) != None : l.extend( m.get_methods() ) return l def search_unique_packages(self, package_name) : """ @param package_name : a regexp for the name of the package """ ex = re.compile( package_name ) l = [] d = {} for m, _ in self.get_packages() : if ex.match( m.get_info() ) != None : for path in m.get_methods() : try : d[ path.get_class_name() + path.get_name() + path.get_descriptor() ] += 1 except KeyError : d[ path.get_class_name() + path.get_name() + path.get_descriptor() ] = 0 l.append( [ path.get_class_name(), path.get_name(), path.get_descriptor() ] ) return l, d def search_methods(self, class_name, name, descriptor, re_expr=True) : """ @param class_name : a regexp for the class name of the method (the package) @param name : a regexp for the name of the method @param descriptor : a regexp for the descriptor of the method @rtype : a list of called methods' paths """ l = [] if re_expr == True : ex = re.compile( class_name ) for m, _ in self.get_packages() : if ex.match( m.get_info() ) != None : l.extend( m.search_method( name, descriptor ) ) return l def search_objects(self, class_name) : """ @param class_name : a regexp for the class name @rtype : a list of created objects' paths """ ex = re.compile( class_name ) l = [] for m, _ in self.get_packages() : if ex.match( m.get_info() ) != None : l.extend( m.get_objects_paths() ) return l def search_crypto_packages(self) : """ @rtype : a list of called crypto packages """ return self.search_packages( "Ljavax/crypto/" ) def search_telephony_packages(self) : """ @rtype : a list of called telephony packages """ return self.search_packages( "Landroid/telephony/" ) def search_net_packages(self) : """ @rtype : a list of called net packages """ return self.search_packages( "Landroid/net/" ) def get_method(self, class_name, name, descriptor) : try : return self.__packages[ class_name ].get_method( name, descriptor ) except KeyError : return [] def get_permissions_method(self, method) : permissions = [] for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method() == method : if j.get_access_flag() == TAINTED_PACKAGE_CALL : tmp = j.get_descriptor() tmp = tmp[ : tmp.rfind(")") + 1 ] data = "%s-%s-%s" % (m.get_info(), j.get_name(), tmp) if data in DVM_PERMISSIONS_BY_ELEMENT : if DVM_PERMISSIONS_BY_ELEMENT[ data ] not in permissions : permissions.append( DVM_PERMISSIONS_BY_ELEMENT[ data ] ) return permissions def get_permissions(self, permissions_needed) : """ @param permissions_needed : a list of restricted permissions to get ([] returns all permissions) @rtype : a dictionnary of permissions' paths """ permissions = {} pn = permissions_needed if permissions_needed == [] : pn = DVM_PERMISSIONS_BY_PERMISSION.keys() classes = self.__vm.get_classes_names() for m, _ in self.get_packages() : paths = m.get_methods() for j in paths : if j.get_method().get_class_name() in classes and m.get_info() not in classes : if j.get_access_flag() == TAINTED_PACKAGE_CALL : tmp = j.get_descriptor() tmp = tmp[ : tmp.rfind(")") + 1 ] #data = "%s-%s-%s" % (m.get_info(), j.get_name(), j.get_descriptor()) data = "%s-%s-%s" % (m.get_info(), j.get_name(), tmp) if data in DVM_PERMISSIONS_BY_ELEMENT : if DVM_PERMISSIONS_BY_ELEMENT[ data ] in pn : try : permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ].append( j ) except KeyError : permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ] = [] permissions[ DVM_PERMISSIONS_BY_ELEMENT[ data ] ].append( j ) return permissions class Enum(object): def __init__(self, names): self.names = names for value, name in enumerate(self.names): setattr(self, name.upper(), value) def tuples(self): return tuple(enumerate(self.names)) TAG_ANDROID = Enum([ 'ANDROID', 'TELEPHONY', 'ACCESSIBILITYSERVICE', 'ACCOUNTS', 'ANIMATION', 'APP', 'BLUETOOTH', 'CONTENT', 'DATABASE', 'DRM', 'GESTURE', 'GRAPHICS', 'HARDWARE', 'INPUTMETHODSERVICE', 'LOCATION', 'MEDIA', 'MTP', 'NET', 'NFC', 'OPENGL', 'OS', 'PREFERENCE', 'PROVIDER', 'RENDERSCRIPT', 'SAX', 'SECURITY', 'SERVICE', 'SPEECH', 'SUPPORT', 'TEST', 'TEXT', 'UTIL', 'VIEW', 'WEBKIT', 'WIDGET', 'DALVIK_BYTECODE', 'DALVIK_SYSTEM']) TAG_REVERSE_ANDROID = dict((i[0], i[1]) for i in TAG_ANDROID.tuples()) TAGS_ANDROID = { TAG_ANDROID.ANDROID : [ 0, "Landroid" ], TAG_ANDROID.TELEPHONY : [ 0, "Landroid/telephony"], TAG_ANDROID.ACCESSIBILITYSERVICE : [ 0, "Landroid/accessibilityservice" ], TAG_ANDROID.ACCOUNTS : [ 0, "Landroid/accounts" ], TAG_ANDROID.ANIMATION : [ 0, "Landroid/animation" ], TAG_ANDROID.APP : [ 0, "Landroid/app" ], TAG_ANDROID.BLUETOOTH : [ 0, "Landroid/bluetooth" ], TAG_ANDROID.CONTENT : [ 0, "Landroid/content" ], TAG_ANDROID.DATABASE : [ 0, "Landroid/database" ], TAG_ANDROID.DRM : [ 0, "Landroid/drm" ], TAG_ANDROID.GESTURE : [ 0, "Landroid/gesture" ], TAG_ANDROID.GRAPHICS : [ 0, "Landroid/graphics" ], TAG_ANDROID.HARDWARE : [ 0, "Landroid/hardware" ], TAG_ANDROID.INPUTMETHODSERVICE : [ 0, "Landroid/inputmethodservice" ], TAG_ANDROID.LOCATION : [ 0, "Landroid/location" ], TAG_ANDROID.MEDIA : [ 0, "Landroid/media" ], TAG_ANDROID.MTP : [ 0, "Landroid/mtp" ], TAG_ANDROID.NET : [ 0, "Landroid/net" ], TAG_ANDROID.NFC : [ 0, "Landroid/nfc" ], TAG_ANDROID.OPENGL : [ 0, "Landroid/opengl" ], TAG_ANDROID.OS : [ 0, "Landroid/os" ], TAG_ANDROID.PREFERENCE : [ 0, "Landroid/preference" ], TAG_ANDROID.PROVIDER : [ 0, "Landroid/provider" ], TAG_ANDROID.RENDERSCRIPT : [ 0, "Landroid/renderscript" ], TAG_ANDROID.SAX : [ 0, "Landroid/sax" ], TAG_ANDROID.SECURITY : [ 0, "Landroid/security" ], TAG_ANDROID.SERVICE : [ 0, "Landroid/service" ], TAG_ANDROID.SPEECH : [ 0, "Landroid/speech" ], TAG_ANDROID.SUPPORT : [ 0, "Landroid/support" ], TAG_ANDROID.TEST : [ 0, "Landroid/test" ], TAG_ANDROID.TEXT : [ 0, "Landroid/text" ], TAG_ANDROID.UTIL : [ 0, "Landroid/util" ], TAG_ANDROID.VIEW : [ 0, "Landroid/view" ], TAG_ANDROID.WEBKIT : [ 0, "Landroid/webkit" ], TAG_ANDROID.WIDGET : [ 0, "Landroid/widget" ], TAG_ANDROID.DALVIK_BYTECODE : [ 0, "Ldalvik/bytecode" ], TAG_ANDROID.DALVIK_SYSTEM : [ 0, "Ldalvik/system" ], } class Tags : def __init__(self, patterns=TAGS_ANDROID, reverse=TAG_REVERSE_ANDROID) : self.tags = set() self.patterns = patterns self.reverse = TAG_REVERSE_ANDROID for i in self.patterns : self.patterns[i][1] = re.compile(self.patterns[i][1]) def emit(self, method) : for i in self.patterns : if self.patterns[i][0] == 0 : if self.patterns[i][1].search( method.get_class() ) != None : self.tags.add( i ) def emit_by_classname(self, classname) : for i in self.patterns : if self.patterns[i][0] == 0 : if self.patterns[i][1].search( classname ) != None : self.tags.add( i ) def __contains__(self, key) : return key in self.tags def __str__(self) : return str([ self.reverse[ i ] for i in self.tags ]) def empty(self) : return self.tags == set() class BasicBlocks : def __init__(self, _vm, tv) : self.__vm = _vm self.tainted = tv self.bb = [] def push(self, bb): self.bb.append( bb ) def pop(self, idx) : return self.bb.pop( idx ) def get_basic_block(self, idx) : for i in self.bb : if idx >= i.get_start() and idx < i.get_end() : return i return None def get_tainted_integers(self) : return self.tainted["integers"] def get_tainted_packages(self) : return self.tainted["packages"] def get_tainted_variables(self) : return self.tainted["variables"] def get_random(self) : """ @rtype : return a random basic block """ return self.bb[ random.randint(0, len(self.bb) - 1) ] def get(self) : """ @rtype : return each basic block """ for i in self.bb : yield i def gets(self) : """ @rtype : a list of basic blocks """ return self.bb def get_basic_block_pos(self, idx) : return self.bb[idx] class ExceptionAnalysis : def __init__(self, exception, bb) : self.start = exception[0] self.end = exception[1] self.exceptions = exception[2:] for i in self.exceptions : i.append( bb.get_basic_block( i[1] ) ) def show_buff(self) : buff = "%x:%x\n" % (self.start, self.end) for i in self.exceptions : buff += "\t(%s -> %x %s)\n" % (i[0], i[1], i[2].get_name()) return buff[:-1] class Exceptions : def __init__(self, _vm) : self.__vm = _vm self.exceptions = [] def add(self, exceptions, basic_blocks) : for i in exceptions : self.exceptions.append( ExceptionAnalysis( i, basic_blocks ) ) def get_exception(self, addr_start, addr_end) : for i in self.exceptions : if i.start >= addr_start and i.end <= addr_end : return i elif addr_end <= i.end and addr_start >= i.start : return i return None def gets(self) : return self.exceptions def get(self) : for i in self.exceptions : yield i class MethodAnalysis : """ This class analyses in details a method of a class/dex file """ def __init__(self, vm, method, tv, code_analysis=False) : """ @param _vm : a L{JVMFormat} or L{DalvikVMFormat} object @param _method : a method object @param tv : a dictionnary of tainted information """ self.__vm = vm self.method = method setattr(self.method, "analysis", self) self.tainted = tv BO = { "BasicOPCODES" : jvm.BRANCH2_JVM_OPCODES, "BasicClass" : JVMBasicBlock, "Dnext" : jvm.determineNext, "Dexception" : jvm.determineException } if self.__vm.get_type() == "DVM" : BO = { "BasicOPCODES" : dvm.BRANCH_DVM_OPCODES, "BasicClass" : DVMBasicBlock, "Dnext" : dvm.determineNext, "Dexception" : dvm.determineException } BO["BasicOPCODES_H"] = [] for i in BO["BasicOPCODES"] : BO["BasicOPCODES_H"].append( re.compile( i ) ) self.basic_blocks = BasicBlocks( self.__vm, self.tainted ) self.exceptions = Exceptions( self.__vm ) code = self.method.get_code() if code == None : return current_basic = BO["BasicClass"]( 0, self.__vm, self.method, self.basic_blocks ) self.basic_blocks.push( current_basic ) ########################################################## bc = code.get_bc() l = [] h = {} idx = 0 for i in bc.get() : for j in BO["BasicOPCODES_H"] : if j.match(i.get_name()) != None : v = BO["Dnext"]( i, idx, self.method ) h[ idx ] = v l.extend( v ) break idx += i.get_length() excepts = BO["Dexception"]( self.__vm, self.method ) for i in excepts: l.extend([i[0]]) idx = 0 for i in bc.get() : # index is a destination if idx in l : if current_basic.ins != [] : current_basic = BO["BasicClass"]( current_basic.get_end(), self.__vm, self.method, self.basic_blocks ) self.basic_blocks.push( current_basic ) current_basic.push( i ) # index is a branch instruction if idx in h : current_basic = BO["BasicClass"]( current_basic.get_end(), self.__vm, self.method, self.basic_blocks ) self.basic_blocks.push( current_basic ) idx += i.get_length() if current_basic.ins == [] : self.basic_blocks.pop( -1 ) for i in self.basic_blocks.get() : try : i.set_childs( h[ i.end - i.ins[-1].get_length() ] ) except KeyError : i.set_childs( [] ) # Create exceptions self.exceptions.add(excepts, self.basic_blocks) for i in self.basic_blocks.get() : # analyze each basic block i.analyze() # setup exception by basic block i.set_exception( self.exceptions.get_exception( i.start, i.end ) ) if code_analysis == True : for i in self.basic_blocks.get() : i.analyze_code() def get_length(self) : """ @rtype : an integer which is the length of the code """ return self.get_code().get_length() def get_vm(self) : return self.__vm def get_method(self) : return self.method def get_local_variables(self) : return self.tainted["variables"].get_local_variables( self.method ) def show(self) : print "METHOD", self.method.get_class_name(), self.method.get_name(), self.method.get_descriptor() for i in self.basic_blocks.get() : print "\t", i i.show() print "" def show_methods(self) : print "\t #METHODS :" for i in self.__bb : methods = i.get_methods() for method in methods : print "\t\t-->", method.get_class_name(), method.get_name(), method.get_descriptor() for context in methods[method] : print "\t\t\t |---|", context.details def create_tags(self) : self.tags = Tags() for i in self.tainted["packages"].get_packages_by_method( self.method ) : self.tags.emit_by_classname( i ) SIGNATURE_L0_0 = "L0_0" SIGNATURE_L0_1 = "L0_1" SIGNATURE_L0_2 = "L0_2" SIGNATURE_L0_3 = "L0_3" SIGNATURE_L0_4 = "L0_4" SIGNATURE_L0_5 = "L0_5" SIGNATURE_L0_6 = "L0_6" SIGNATURE_L0_0_L1 = "L0_0:L1" SIGNATURE_L0_1_L1 = "L0_1:L1" SIGNATURE_L0_2_L1 = "L0_2:L1" SIGNATURE_L0_3_L1 = "L0_3:L1" SIGNATURE_L0_4_L1 = "L0_4:L1" SIGNATURE_L0_5_L1 = "L0_5:L1" SIGNATURE_L0_0_L2 = "L0_0:L2" SIGNATURE_L0_0_L3 = "L0_0:L3" SIGNATURE_HEX = "hex" SIGNATURE_SEQUENCE_BB = "sequencebb" SIGNATURES = { SIGNATURE_L0_0 : { "type" : 0 }, SIGNATURE_L0_1 : { "type" : 1 }, SIGNATURE_L0_2 : { "type" : 2, "arguments" : ["Landroid"] }, SIGNATURE_L0_3 : { "type" : 2, "arguments" : ["Ljava"] }, SIGNATURE_L0_4 : { "type" : 2, "arguments" : ["Landroid", "Ljava"] }, SIGNATURE_L0_5 : { "type" : 3, "arguments" : ["Landroid"] }, SIGNATURE_L0_6 : { "type" : 3, "arguments" : ["Ljava"] }, SIGNATURE_SEQUENCE_BB : {}, SIGNATURE_HEX : {}, } from sign import Signature class VMAnalysis : """ This class analyses a class file or a dex file @param _vm : a virtual machine object """ def __init__(self, _vm, code_analysis=False) : """ @param _vm : a L{JVMFormat} or L{DalvikFormatVM} @param code_analysis : True if you would like to do an advanced analyse of the code (e.g : to search free offset to insert codes """ self.__vm = _vm self.tainted_variables = TaintedVariables( self.__vm ) self.tainted_packages = TaintedPackages( self.__vm ) self.tainted_integers = TaintedIntegers( self.__vm ) self.tainted = { "variables" : self.tainted_variables, "packages" : self.tainted_packages, "integers" : self.tainted_integers, } self.signature = Signature( self.tainted ) for i in self.__vm.get_all_fields() : self.tainted_variables.add( [ i.get_class_name(), i.get_descriptor(), i.get_name() ], TAINTED_FIELD ) self.methods = [] self.hmethods = {} self.__nmethods = {} for i in self.__vm.get_methods() : x = MethodAnalysis( self.__vm, i, self.tainted, code_analysis ) self.methods.append( x ) self.hmethods[ i ] = x self.__nmethods[ i.get_name() ] = x def get_vm(self) : return self.__vm def get_method(self, method) : """ Return an analysis method @param method : a classical method object @rtype : L{MethodAnalysis} """ return self.hmethods[ method ] def get_tainted_variables(self) : """ Return the tainted variables @rtype : L{TaintedVariables} """ return self.tainted_variables def get_tainted_packages(self) : """ Return the tainted packages @rtype : L{TaintedPackages} """ return self.tainted_packages def get_tainted_fields(self) : return self.get_tainted_variables().get_fields() def get_tainted_field(self, class_name, name, descriptor) : """ Return a specific tainted field @param class_name : the name of the class @param name : the name of the field @param descriptor : the descriptor of the field @rtype : L{TaintedVariable} """ return self.tainted_variables.get_field( class_name, name, descriptor ) def get_methods(self) : """ Return each analysis method @rtype : L{MethodAnalysis} """ for i in self.hmethods : yield self.hmethods[i] def get_method_signature(self, method, grammar_type="", options={}, predef_sign="") : """ Return a specific signature for a specific method @param method : a reference to method from a vm class @param grammar_type : the type of the signature @param options : the options of the signature @param predef_sign : used a predefined signature @rtype : L{Sign} """ if predef_sign != "" : g = "" o = {} for i in predef_sign.split(":") : if "_" in i : g += "L0:" o[ "L0" ] = SIGNATURES[ i ] else : g += i g += ":" return self.signature.get_method( self.get_method( method ), g[:-1], o ) else : return self.signature.get_method( self.get_method( method ), grammar_type, options ) def get_permissions(self, permissions_needed) : """ @param permissions_needed : a list of restricted permissions to get ([] returns all permissions) @rtype : a dictionnary of permissions' paths """ permissions = {} permissions.update( self.tainted_packages.get_permissions( permissions_needed ) ) permissions.update( self.tainted_variables.get_permissions( permissions_needed ) ) return permissions def get_permissions_method(self, method) : permissions_f = self.tainted_packages.get_permissions_method( method ) permissions_v = self.tainted_variables.get_permissions_method( method ) return list( set( permissions_f + permissions_v ) ) def create_tags(self) : for i in self.methods : i.create_tags()
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from androguard.core.analysis.analysis import TAINTED_PACKAGE_CREATE, TAINTED_PACKAGE_CALL from androguard.core.bytecodes import dvm TAINTED_PACKAGE_INTERNAL_CALL = 2 FIELD_ACCESS = { "R" : 0, "W" : 1 } PACKAGE_ACCESS = { TAINTED_PACKAGE_CREATE : 0, TAINTED_PACKAGE_CALL : 1, TAINTED_PACKAGE_INTERNAL_CALL : 2 } class Sign : def __init__(self) : self.levels = {} self.hlevels = [] def add(self, level, value) : self.levels[ level ] = value self.hlevels.append( level ) def get_level(self, l) : return self.levels[ "L%d" % l ] def get_string(self) : buff = "" for i in self.hlevels : buff += self.levels[ i ] return buff def get_list(self) : return self.levels[ "sequencebb" ] class Signature : def __init__(self, tainted_information) : self.__tainted = tainted_information self._cached_signatures = {} self._cached_fields = {} self._cached_packages = {} self._global_cached = {} self.levels = { # Classical method signature with basic blocks, strings, fields, packages "L0" : { 0 : ( "_get_strings_a", "_get_fields_a", "_get_packages_a" ), 1 : ( "_get_strings_pa", "_get_fields_a", "_get_packages_a" ), 2 : ( "_get_strings_a", "_get_fields_a", "_get_packages_pa_1" ), 3 : ( "_get_strings_a", "_get_fields_a", "_get_packages_pa_2" ), }, # strings "L1" : [ "_get_strings_a1" ], # exceptions "L2" : [ "_get_exceptions" ], # fill array data "L3" : [ "_get_fill_array_data" ], } self.classes_names = None self._init_caches() def _get_sequence_bb(self, analysis_method) : l = [] for i in analysis_method.basic_blocks.get() : buff = "" if len(i.get_ins()) > 5 : for ins in i.get_ins() : buff += ins.get_name() if buff != "" : l.append( buff ) return l def _get_sequence_bb2(self, analysis_method) : l = [] buff = "" nb = 0 for i in analysis_method.basic_blocks.get() : if nb == 0 : buff = "" for ins in i.get_ins() : buff += ins.get_name() nb += 1 if nb > 5 : l.append( buff ) nb = 0 if nb != 0 : l.append( buff ) return l def _get_hex(self, analysis_method) : code = analysis_method.get_method().get_code() if code == None : return "" buff = "" for i in code.get_bc().get() : buff += dvm.clean_name_instruction( i ) buff += dvm.static_operand_instruction( i ) return buff def _get_bb(self, analysis_method, functions, options) : bbs = [] for b in analysis_method.basic_blocks.get() : l = [] l.append( (b.start, "B") ) l.append( (b.start, "[") ) internal = [] op_value = b.get_last().get_op_value() # return if op_value >= 0x0e and op_value <= 0x11 : internal.append( (b.end-1, "R") ) # if elif op_value >= 0x32 and op_value <= 0x3d : internal.append( (b.end-1, "I") ) # goto elif op_value >= 0x28 and op_value <= 0x2a : internal.append( (b.end-1, "G") ) # sparse or packed switch elif op_value >= 0x2b and op_value <= 0x2c : internal.append( (b.end-1, "G") ) for f in functions : try : internal.extend( getattr( self, f )( analysis_method, options ) ) except TypeError : internal.extend( getattr( self, f )( analysis_method ) ) internal.sort() for i in internal : if i[0] >= b.start and i[0] < b.end : l.append( i ) del internal l.append( (b.end, "]") ) bbs.append( ''.join(i[1] for i in l) ) return bbs def _init_caches(self) : if self._cached_fields == {} : for f_t, f in self.__tainted["variables"].get_fields() : self._cached_fields[ f ] = f_t.get_paths_length() n = 0 for f in sorted( self._cached_fields ) : self._cached_fields[ f ] = n n += 1 if self._cached_packages == {} : for m_t, m in self.__tainted["packages"].get_packages() : self._cached_packages[ m ] = m_t.get_paths_length() n = 0 for m in sorted( self._cached_packages ) : self._cached_packages[ m ] = n n += 1 def _get_fill_array_data(self, analysis_method) : buff = "" for b in analysis_method.basic_blocks.get() : for i in b.ins : if i.get_name() == "FILL-ARRAY-DATA" : buff_tmp = i.get_operands() for j in range(0, len(buff_tmp)) : buff += "\\x%02x" % ord( buff_tmp[j] ) return buff def _get_exceptions(self, analysis_method) : buff = "" method = analysis_method.get_method() code = method.get_code() if code == None or code.get_tries_size() <= 0 : return buff handler_catch_list = code.get_handlers() for handler_catch in handler_catch_list.get_list() : for handler in handler_catch.get_handlers() : buff += analysis_method.get_vm().get_cm_type( handler.get_type_idx() ) return buff def _get_strings_a1(self, analysis_method) : buff = "" strings_method = self.__tainted["variables"].get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : buff += s.replace('\n', ' ') return buff def _get_strings_pa(self, analysis_method) : l = [] strings_method = self.__tainted["variables"].get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : l.append( (path.get_bb().start + path.get_idx(), "S%d" % len(s) ) ) return l def _get_strings_a(self, analysis_method) : key = "SA-%s" % analysis_method if key in self._global_cached : return self._global_cached[ key ] l = [] strings_method = self.__tainted["variables"].get_strings_by_method( analysis_method.get_method() ) for s in strings_method : for path in strings_method[s] : l.append( (path.get_bb().start + path.get_idx(), "S") ) self._global_cached[ key ] = l return l def _get_fields_a(self, analysis_method) : key = "FA-%s" % analysis_method if key in self._global_cached : return self._global_cached[ key ] fields_method = self.__tainted["variables"].get_fields_by_method( analysis_method.get_method() ) l = [] for f in fields_method : for path in fields_method[ f ] : #print (path.get_bb().start + path.get_idx(), "F%d" % FIELD_ACCESS[ path.get_access_flag() ]) l.append( (path.get_bb().start + path.get_idx(), "F%d" % FIELD_ACCESS[ path.get_access_flag() ]) ) self._global_cached[ key ] = l return l def _get_packages_a(self, analysis_method) : packages_method = self.__tainted["packages"].get_packages_by_method( analysis_method.get_method() ) l = [] for m in packages_method : for path in packages_method[ m ] : l.append( (path.get_bb().start + path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) return l def _get_packages(self, analysis_method, include_packages) : l = self._get_packages_pa_1( analysis_method, include_packages ) return "".join([ i[1] for i in l ]) def _get_packages_pa_1(self, analysis_method, include_packages) : key = "PA1-%s-%s" % (analysis_method, include_packages) if key in self._global_cached : return self._global_cached[ key ] packages_method = self.__tainted["packages"].get_packages_by_method( analysis_method.get_method() ) if self.classes_names == None : self.classes_names = analysis_method.get_vm().get_classes_names() l = [] for m in packages_method : for path in packages_method[ m ] : present = False for i in include_packages : if m.find(i) == 0 : present = True break if path.get_access_flag() == 1 : if path.get_class_name() in self.classes_names : l.append( (path.get_bb().start + path.get_idx(), "P%s" % (PACKAGE_ACCESS[ 2 ]) ) ) else : if present == True : l.append( (path.get_bb().start + path.get_idx(), "P%s{%s%s%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], path.get_class_name(), path.get_name(), path.get_descriptor()) ) ) else : l.append( (path.get_bb().start + path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) else : if present == True : l.append( (path.get_bb().start + path.get_idx(), "P%s{%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], m) ) ) else : l.append( (path.get_bb().start + path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) self._global_cached[ key ] = l return l def _get_packages_pa_2(self, analysis_method, include_packages) : packages_method = self.__tainted["packages"].get_packages_by_method( analysis_method.get_method() ) l = [] for m in packages_method : for path in packages_method[ m ] : present = False for i in include_packages : if m.find(i) == 0 : present = True break if present == True : l.append( (path.get_bb().start + path.get_idx(), "P%s" % (PACKAGE_ACCESS[ path.get_access_flag() ]) ) ) continue if path.get_access_flag() == 1 : l.append( (path.get_bb().start + path.get_idx(), "P%s{%s%s%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], path.get_class_name(), path.get_name(), path.get_descriptor()) ) ) else : l.append( (path.get_bb().start + path.get_idx(), "P%s{%s}" % (PACKAGE_ACCESS[ path.get_access_flag() ], m) ) ) return l def get_method(self, analysis_method, signature_type, signature_arguments={}) : key = "%s-%s-%s" % (analysis_method, signature_type, signature_arguments) if key in self._cached_signatures : return self._cached_signatures[ key ] s = Sign() #print signature_type, signature_arguments for i in signature_type.split(":") : # print i, signature_arguments[ i ] if i == "L0" : _type = self.levels[ i ][ signature_arguments[ i ][ "type" ] ] try : _arguments = signature_arguments[ i ][ "arguments" ] except KeyError : _arguments = [] value = self._get_bb( analysis_method, _type, _arguments ) s.add( i, ''.join(z for z in value) ) elif i == "L4" : try : _arguments = signature_arguments[ i ][ "arguments" ] except KeyError : _arguments = [] value = self._get_packages( analysis_method, _arguments ) s.add( i , value ) elif i == "hex" : value = self._get_hex( analysis_method ) s.add( i, value ) elif i == "sequencebb" : _type = ('_get_strings_a', '_get_fields_a', '_get_packages_pa_1') _arguments = ['Landroid', 'Ljava'] #value = self._get_bb( analysis_method, _type, _arguments ) #s.add( i, value ) value = self._get_sequence_bb( analysis_method ) s.add( i, value ) else : for f in self.levels[ i ] : value = getattr( self, f )( analysis_method ) s.add( i, value ) self._cached_signatures[ key ] = s return s
Python
# This file is part of Androguard. # # Copyright (C) 2010, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import os, logging, types, random, string ANDROGUARD_VERSION = "1.3" def get_ascii_string(s) : try : return s.decode("ascii") except UnicodeDecodeError : d = "" for i in s : if ord(i) < 128 : d += i else : d += "%x" % ord(i) return d class Color: normal = "\033[0m" black = "\033[30m" red = "\033[31m" green = "\033[32m" yellow = "\033[33m" blue = "\033[34m" purple = "\033[35m" cyan = "\033[36m" grey = "\033[37m" bold = "\033[1m" uline = "\033[4m" blink = "\033[5m" invert = "\033[7m" CONF = { "BIN_DED" : "ded.sh", "PATH_DED" : "./decompiler/ded/", "PATH_DEX2JAR" : "./decompiler/dex2jar/", "BIN_DEX2JAR" : "dex2jar.sh", "PATH_JAD" : "./decompiler/jad/", "BIN_JAD" : "jad", "PRETTY_SHOW" : 1, # Full python or mix python/c++ (native) #"ENGINE" : "automatic", "ENGINE" : "python", "RECODE_ASCII_STRING" : False, "RECODE_ASCII_STRING_METH" : get_ascii_string, "DEOBFUSCATED_STRING" : True, # "DEOBFUSCATED_STRING_METH" : get_deobfuscated_string, "PATH_JARSIGNER" : "jarsigner", "COLORS" : { "OFFSET" : Color.yellow, "OFFSET_ADDR" : Color.green, "INSTRUCTION_NAME" : Color.yellow, "BRANCH_FALSE" : Color.red, "BRANCH_TRUE" : Color.green, "BRANCH" : Color.blue, "EXCEPTION" : Color.cyan, "BB" : Color.purple, "NOTE" : Color.red, } } def disable_colors() : """ Disable colors from the output (color = normal)""" for i in CONF["COLORS"] : CONF["COLORS"][i] = Color.normal def remove_colors() : """ Remove colors from the output (no escape sequences)""" for i in CONF["COLORS"] : CONF["COLORS"][i] = "" def enable_colors(colors) : for i in colors : CONF["COLORS"][i] = colors[i] def save_colors() : c = {} for i in CONF["COLORS"] : c[i] = CONF["COLORS"][i] return c def long2int( l ) : if l > 0x7fffffff : l = (0x7fffffff & l) - 0x80000000 return l def long2str(l): """Convert an integer to a string.""" if type(l) not in (types.IntType, types.LongType): raise ValueError, 'the input must be an integer' if l < 0: raise ValueError, 'the input must be greater than 0' s = '' while l: s = s + chr(l & 255L) l >>= 8 return s def str2long(s): """Convert a string to a long integer.""" if type(s) not in (types.StringType, types.UnicodeType): raise ValueError, 'the input must be a string' l = 0L for i in s: l <<= 8 l |= ord(i) return l def random_string() : return random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) def is_android(filename) : """Return the type of the file @param filename : the filename @rtype : "APK", "DEX", "ELF", None """ fd = open( filename, "r") val = None f_bytes = fd.read(7) val = is_android_raw( f_bytes ) fd.close() return val def is_android_raw(raw) : val = None f_bytes = raw[:7] if f_bytes[0:2] == "PK" : val = "APK" elif f_bytes[0:3] == "dex" : val = "DEX" elif f_bytes[0:7] == "\x7fELF\x01\x01\x01" : val = "ELF" elif f_bytes[0:4] == "\x03\x00\x08\x00" : val = "AXML" return val # from scapy log_andro = logging.getLogger("andro") console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) log_andro.addHandler(console_handler) log_runtime = logging.getLogger("andro.runtime") # logs at runtime log_interactive = logging.getLogger("andro.interactive") # logs in interactive functions log_loading = logging.getLogger("andro.loading") # logs when loading andro def set_debug() : log_andro.setLevel( logging.DEBUG ) def get_debug() : return log_andro.getEffectiveLevel() == logging.DEBUG def warning(x): log_runtime.warning(x) def error(x) : log_runtime.error(x) raise() def debug(x) : log_runtime.debug(x) def set_options(key, value) : CONF[ key ] = value def save_to_disk(buff, output) : fd = open(output, "w") fd.write(buff) fd.close() def rrmdir( directory ): 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, name)) os.rmdir( directory )
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from androguard.core import androconf from androguard.core.bytecodes import jvm from androguard.core.bytecodes import dvm from androguard.core.bytecodes import apk from androguard.core.analysis import analysis class BC : def __init__(self, bc) : self.__bc = bc def get_vm(self) : return self.__bc def get_analysis(self) : return self.__a def analyze(self) : self.__a = analysis.VMAnalysis( self.__bc, code_analysis=True ) self.__bc.set_vmanalysis( self.__a ) def _get(self, val, name) : l = [] r = getattr(self.__bc, val)(name) for i in r : l.append( i ) return l def _gets(self, val) : l = [] r = getattr(self.__bc, val)() for i in r : l.append( i ) return l def gets(self, name) : return self._gets("get_" + name) def get(self, val, name) : return self._get("get_" + val, name) def insert_direct_method(self, name, method) : return self.__bc.insert_direct_method(name, method) def insert_craft_method(self, name, proto, codes) : return self.__bc.insert_craft_method( name, proto, codes) def show(self) : self.__bc.show() def pretty_show(self) : self.__bc.pretty_show() def save(self) : return self.__bc.save() def __getattr__(self, value) : return getattr(self.__bc, value) class Androguard: """Androguard is the main object to abstract and manage differents formats @param files : a list of filenames (filename must be terminated by .class or .dex) @param raw : specify if the filename is in fact a raw buffer (default : False) #FIXME """ def __init__(self, files, raw=False) : self.__files = files self.__orig_raw = {} for i in self.__files : self.__orig_raw[ i ] = open(i, "rb").read() self.__bc = [] self._analyze() def _iterFlatten(self, root): if isinstance(root, (list, tuple)): for element in root : for e in self._iterFlatten(element) : yield e else: yield root def _analyze(self) : for i in self.__files : #print "processing ", i if ".class" in i : bc = jvm.JVMFormat( self.__orig_raw[ i ] ) elif ".jar" in i : x = jvm.JAR( i ) bc = x.get_classes() elif ".dex" in i : bc = dvm.DalvikVMFormat( self.__orig_raw[ i ] ) elif ".apk" in i : x = apk.APK( i ) bc = dvm.DalvikVMFormat( x.get_dex() ) else : ret_type = androconf.is_android( i ) if ret_type == "APK" : x = apk.APK( i ) bc = dvm.DalvikVMFormat( x.get_dex() ) elif ret_type == "DEX" : bc = dvm.DalvikVMFormat( open(i, "rb").read() ) elif ret_type == "ELF" : from androguard.core.binaries import elf bc = elf.ELF( open(i, "rb").read() ) else : raise( "Unknown bytecode" ) if isinstance(bc, list) : for j in bc : self.__bc.append( (j[0], BC( jvm.JVMFormat(j[1]) ) ) ) else : self.__bc.append( (i, BC( bc )) ) def ianalyze(self) : for i in self.get_bc() : i[1].analyze() def get_class(self, class_name) : for _, bc in self.__bc : if bc.get_class(class_name) == True : return bc return None def get_raw(self) : """Return raw format of all file""" l = [] for _, bc in self.__bc : l.append( bc._get_raw() ) return l def get_orig_raw(self) : return self.__orig_raw def get_method_descriptor(self, class_name, method_name, descriptor) : """ Return the specific method @param class_name : the class name of the method @param method_name : the name of the method @param descriptor : the descriptor of the method """ for file_name, bc in self.__bc : x = bc.get_method_descriptor( class_name, method_name, descriptor ) if x != None : return x, bc return None, None def get_field_descriptor(self, class_name, field_name, descriptor) : """ Return the specific field @param class_name : the class name of the field @param field_name : the name of the field @param descriptor : the descriptor of the field """ for file_name, bc in self.__bc : x = bc.get_field_descriptor( class_name, field_name, descriptor ) if x != None : return x, bc return None, None def get(self, name, val) : """ Return the specific value for all files @param name : @param val : """ if name == "file" : for file_name, bc in self.__bc : if file_name == val : return bc return None else : l = [] for file_name, bc in self.__bc : l.append( bc.get( name, val ) ) return list( self._iterFlatten(l) ) def gets(self, name) : """ Return the specific value for all files @param name : """ l = [] for file_name, bc in self.__bc : l.append( bc.gets( name ) ) return list( self._iterFlatten(l) ) def get_vms(self) : return [ i[1].get_vm() for i in self.__bc ] def get_bc(self) : return self.__bc def show(self) : """ Display all files """ for _, bc in self.__bc : bc.show() def pretty_show(self) : """ Display all files """ for _, bc in self.__bc : bc.pretty_show() class AndroguardS : """AndroguardS is the main object to abstract and manage differents formats but only per filename. In fact this class is just a wrapper to the main class Androguard @param filename : the filename to use (filename must be terminated by .class or .dex) @param raw : specify if the filename is a raw buffer (default : False) """ def __init__(self, filename, raw=False) : self.__filename = filename self.__orig_a = Androguard( [ filename ], raw ) self.__a = self.__orig_a.get( "file", filename ) def get_orig_raw(self) : return self.__orig_a.get_orig_raw()[ self.__filename ] def get_vm(self) : """ This method returns the VMFormat which correspond to the file @rtype: L{jvm.JVMFormat} or L{dvm.DalvikVMFormat} """ return self.__a.get_vm() def save(self) : """ Return the original format (with the modifications) into raw format @rtype: string """ return self.__a.save() def __getattr__(self, value) : try : return getattr(self.__orig_a, value) except AttributeError : return getattr(self.__a, value)
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from subprocess import Popen, PIPE, STDOUT import os, sys import xmlrpclib import cPickle class _Method : def __init__(self, proxy, name) : self.proxy = proxy self.name = name def __call__(self, *args): #print "CALL", self.name, args z = getattr( self.proxy, self.name, None ) #print "SEND", repr(cPickle.dumps( args ) ) try : if len(args) == 1 : ret = z( cPickle.dumps( args[0] ) ) else : ret = z( cPickle.dumps( args ) ) #print "RECEIVE", repr(ret) return cPickle.loads( ret ) except xmlrpclib.ProtocolError : return [] class MyXMLRPC : def __init__(self, proxy) : self.proxy = proxy def __getattr__(self, name) : return _Method(self.proxy, name) class BasicBlock : def __init__(self, ins) : self.ins = ins def show(self) : for i in self.ins : print i class Function : def __init__(self, name, start_ea, instructions, information) : #print name, start_ea self.name = name self.start_ea = start_ea self.information = information self.basic_blocks = [] self.instructions = instructions r = {} idx = 0 for i in instructions : r[ i[0] ] = idx idx += 1 for i in information[0] : try : start = r[i[0]] end = r[i[1]] + 1 self.basic_blocks.append( BasicBlock( instructions[start:end] ) ) except KeyError : pass def get_instructions(self) : return [ i for i in self.instructions ] def run_ida(idapath, wrapper_init_path, binpath) : os.environ["TVHEADLESS"] = "1" pid = os.fork() if pid == 0: wrapper_path = "-S" + wrapper_init_path l = [ idapath, "-A", wrapper_path, binpath ] print l compile = Popen(l, stdout=open('/dev/null', 'w'), stderr=STDOUT) stdout, stderr = compile.communicate() # print stdout, stderr sys.exit(0) class IDAPipe : def __init__(self, idapath, binpath, wrapper_init_path) : self.idapath = idapath self.binpath = binpath self.proxy = None run_ida(self.idapath, self.binpath, wrapper_init_path) while 1 : try : self.proxy = xmlrpclib.ServerProxy("http://localhost:9000/") self.proxy.is_connected() break except : pass #print self.proxy self.proxy = MyXMLRPC( self.proxy ) def quit(self) : try : self.proxy.quit() except : pass def _build_functions(self, functions) : F = {} for i in functions : F[ i ] = Function( functions[i][0], i, functions[i][1:-1], functions[i][-1] ) return F def get_quick_functions(self) : functions = self.get_raw() return self._build_functions( functions ) def get_raw(self) : return self.proxy.get_raw() def get_nb_functions(self) : return len(self.proxy.Functions()) def get_functions(self) : for function_ea in self.proxy.Functions() : self.get_function_addr( function_ea ) def get_function_name(self, name) : function_ea = self.proxy.get_function( name ) self.get_function_addr( function_ea ) def get_function_addr(self, function_ea) : if function_ea == -1 : return f_start = function_ea f_end = self.proxy.GetFunctionAttr(function_ea, 4) #FUNCATTR_END) edges = set() boundaries = set((f_start,)) for head in self.proxy.Heads(f_start, f_end) : if self.proxy.isCode( self.proxy.GetFlags( head ) ) : refs = self.proxy.CodeRefsFrom(head, 0) refs = set(filter(lambda x: x>=f_start and x<=f_end, refs)) #print head, f_end, refs, self.proxy.GetMnem(head), self.proxy.GetOpnd(head, 0), self.proxy.GetOpnd(head, 1) if refs : next_head = self.proxy.NextHead(head, f_end) if self.proxy.isFlow(self.proxy.GetFlags(next_head)): refs.add(next_head) # Update the boundaries found so far. boundaries.update(refs) # For each of the references found, and edge is # created. for r in refs: # If the flow could also come from the address # previous to the destination of the branching # an edge is created. if self.proxy.isFlow(self.proxy.GetFlags(r)): edges.add((self.proxy.PrevHead(r, f_start), r)) edges.add((head, r)) #print edges, boundaries # Let's build the list of (startEA, startEA) couples # for each basic block sorted_boundaries = sorted(boundaries, reverse = True) end_addr = self.proxy.PrevHead(f_end, f_start) bb_addr = [] for begin_addr in sorted_boundaries: bb_addr.append((begin_addr, end_addr)) # search the next end_addr which could be # farther than just the previous head # if data are interlaced in the code # WARNING: it assumes it won't epicly fail ;) end_addr = self.proxy.PrevHead(begin_addr, f_start) while not self.proxy.isCode(self.proxy.GetFlags(end_addr)): end_addr = self.proxy.PrevHead(end_addr, f_start) # And finally return the result bb_addr.reverse() #print bb_addr, sorted(edges) def display_function(f) : print f, f.name, f.information for i in f.basic_blocks : print i i.show()
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from idaapi import * from idautils import * from idc import * from SimpleXMLRPCServer import SimpleXMLRPCServer import cPickle def is_connected() : return True def wrapper_get_raw(oops) : F = {} for function_ea in Functions() : F[ function_ea ] = [] f_start = function_ea f_end = GetFunctionAttr(function_ea, FUNCATTR_END) edges = set() boundaries = set((f_start,)) F[ function_ea ].append( GetFunctionName(function_ea) ) for head in Heads(f_start, f_end) : if isCode( GetFlags( head ) ) : F[ function_ea ].append( (head, GetMnem(head), GetOpnd(head, 0), GetOpnd(head, 1), GetOpnd(head, 2)) ) refs = CodeRefsFrom(head, 0) refs = set(filter(lambda x: x>=f_start and x<=f_end, refs)) if refs : next_head = NextHead(head, f_end) if isFlow(GetFlags(next_head)): refs.add(next_head) # Update the boundaries found so far. boundaries.update(refs) # For each of the references found, and edge is # created. for r in refs: # If the flow could also come from the address # previous to the destination of the branching # an edge is created. if isFlow(GetFlags(r)): edges.add((PrevHead(r, f_start), r)) edges.add((head, r)) #print edges, boundaries # Let's build the list of (startEA, startEA) couples # for each basic block sorted_boundaries = sorted(boundaries, reverse = True) end_addr = PrevHead(f_end, f_start) bb_addr = [] for begin_addr in sorted_boundaries: bb_addr.append((begin_addr, end_addr)) # search the next end_addr which could be # farther than just the previous head # if data are interlaced in the code # WARNING: it assumes it won't epicly fail ;) end_addr = PrevHead(begin_addr, f_start) while not isCode(GetFlags(end_addr)): end_addr = PrevHead(end_addr, f_start) # And finally return the result bb_addr.reverse() F[ function_ea ].append( (bb_addr, sorted(edges)) ) return cPickle.dumps( F ) def wrapper_Heads(oops) : start, end = cPickle.loads(oops) return cPickle.dumps( [ x for x in Heads( start, end ) ] ) def wrapper_Functions(oops) : return cPickle.dumps( [ x for x in Functions() ] ) def wrapper_get_function(oops) : name = cPickle.loads(oops) for function_ea in Functions() : if GetFunctionName(function_ea) == name : return cPickle.dumps( function_ea ) return cPickle.dumps( -1 ) def wrapper_quit(oops) : qexit(0) class IDAWrapper : def _dispatch(self, x, params) : #fd = open("toto.txt", "w") #fd.write( x + "\n" ) #fd.write( str(type(params[0])) + "\n" ) #fd.close() params = cPickle.loads( *params ) if isinstance(params, tuple) == False : params = (params,) import types import idautils import idc #[getattr(idautils, a, None) for a in dir(idautils) if isinstance(getattr(idautils, a, None) , types.FunctionType)] for a in dir(idautils) : #fd.write( "\t" + a + "\n" ) if a == x : z = getattr(idautils, a, None) ret = z( *params ) if type(ret).__name__=='generator' : return cPickle.dumps( [ i for i in ret ] ) return cPickle.dumps( ret ) for a in dir(idc) : #fd.write( "\t" + a + "\n" ) if a == x : z = getattr(idc, a, None) ret = z( *params ) if type(ret).__name__=='generator' : return cPickle.dumps( [ i for i in ret ] ) return cPickle.dumps( ret ) return cPickle.dumps( [] ) def main() : autoWait() ea = ScreenEA() server = SimpleXMLRPCServer(("localhost", 9000)) server.register_function(is_connected, "is_connected") server.register_function(wrapper_get_raw, "get_raw") server.register_function(wrapper_get_function, "get_function") server.register_function(wrapper_Heads, "Heads") server.register_function(wrapper_Functions, "Functions") server.register_instance(IDAWrapper()) server.register_function(wrapper_quit, "quit") server.serve_forever() qexit(0) main()
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from elfesteem import * from miasm.tools.pe_helper import * from miasm.core import asmbloc from miasm.arch import arm_arch from miasm.core import bin_stream def disasm_at_addr(in_str, ad_to_dis, symbol_pool) : kargs = {} all_bloc = asmbloc.dis_bloc_all(arm_arch.arm_mn, in_str, ad_to_dis, set(), symbol_pool=symbol_pool, dontdis_retcall = False, follow_call = False, **kargs) print all_bloc for i in all_bloc : print i.label for j in i.lines : print "\t", type(j), j #.getname(), j.args2str() print class Function : def __init__(self, cm, name, info) : self.cm = cm self.name = name self.info = info def show(self) : print self.name, hex(self.info.value) self.cm.disasm_at_addr( self.info.value ) #self.cm.disasm_at_addr( self.info.value ) class ClassManager : def __init__(self, in_str, symbol_pool) : self.in_str = in_str self.symbol_pool = symbol_pool def disasm_at_addr(self, ad_to_dis) : disasm_at_addr( self.in_str, ad_to_dis, self.symbol_pool ) class ELF : def __init__(self, buff) : self.E = elf_init.ELF( buff ) self.in_str = bin_stream.bin_stream(self.E.virt) self.symbol_pool = None self.functions = [] self.create_symbol_pool() self.CM = ClassManager( self.in_str, self.symbol_pool ) self.create_functions() # for k, v in self.e.sh.symtab.symbols.items(): # if v.size != 0 : # print k, type(v), hex(v.value), v.size, v.other, v.info # if k == "rootshell" : # disasm_at_addr( in_str, v.value, symbol_pool ) def create_symbol_pool(self) : dll_dyn_funcs = get_import_address_elf(self.E) self.symbol_pool = asmbloc.asm_symbol_pool() for (n,f), ads in dll_dyn_funcs.items() : for ad in ads : l = self.symbol_pool.getby_name_create("%s_%s"%(n, f)) l.offset = ad self.symbol_pool.s_offset[l.offset] = l def show(self) : for i in self.get_functions(): i.show() def get_functions(self) : return self.functions def create_functions(self) : try : for k, v in self.E.sh.symtab.symbols.items(): if v.size != 0 : self.functions.append( Function(self.CM, k, v) ) except AttributeError : pass for k, v in self.E.sh.dynsym.symbols.items() : if v.size != 0 : self.functions.append( Function(self.CM, k, v) )
Python
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from struct import unpack, pack from androconf import Color, warning, error, CONF, disable_colors, enable_colors, remove_colors, save_colors def disable_print_colors() : colors = save_colors() remove_colors() return colors def enable_print_colors(colors) : enable_colors(colors) # Handle exit message def Exit( msg ): warning("Error : " + msg) raise("oops") def Warning( msg ): warning(msg) def _PrintBanner() : print "*" * 75 def _PrintSubBanner(title=None) : if title == None : print "#" * 20 else : print "#" * 10 + " " + title def _PrintNote(note, tab=0) : note_color = CONF["COLORS"]["NOTE"] print "\t" * tab + "%s# %s%s" % (note_color, note, Color.normal) # Print arg into a correct format def _Print(name, arg) : buff = name + " " if type(arg).__name__ == 'int' : buff += "0x%x" % arg elif type(arg).__name__ == 'long' : buff += "0x%x" % arg elif type(arg).__name__ == 'str' : buff += "%s" % arg elif isinstance(arg, SV) : buff += "0x%x" % arg.get_value() elif isinstance(arg, SVs) : buff += arg.get_value().__str__() print buff def PrettyShow( basic_blocks ) : if CONF["PRETTY_SHOW"] == 0 : PrettyShow0( basic_blocks ) elif CONF["PRETTY_SHOW"] == 1 : PrettyShow1( basic_blocks ) elif CONF["PRETTY_SHOW"] == 2 : PrettyShow1bis( basic_blocks ) def PrettyShowEx( exceptions ) : if len(exceptions) > 0 : print "Exceptions:" if CONF["PRETTY_SHOW"] == 0 : for i in exceptions : print "\t", "%s" % (i.show_buff()) else : for i in exceptions : print "\t", "%s%s%s" % (CONF["COLORS"]["EXCEPTION"], i.show_buff(), Color.normal) def PrettyShow0( basic_blocks ) : paths = [] for i in basic_blocks : val = 0 if len(i.childs) > 1 : val = 1 elif len(i.childs) == 1 : val = 2 for j in i.childs : paths.append( ( j[0], j[1], val ) ) if val == 1 : val = 0 nb = 0 idx = 0 for bb in basic_blocks : for ins in bb.ins : p = [] for j in paths : way = Color.green if j[2] == 1 : way = Color.red elif j[2] == 2 : way = Color.blue m_in = j[0] m_ax = j[1] if j[0] > j[1] : m_in = j[1] m_ax = j[0] if idx >= m_in and idx <= m_ax : if idx == j[0] : p.append( j[1] ) print "o", if idx == j[1] : print "%s>%s" % (way, Color.normal), if idx != j[0] and idx != j[1] : print "%s|%s" % (way, Color.normal), else : print " ", print "%s%d%s(%s%x%s)" % (Color.yellow, nb, Color.normal, Color.yellow, idx, Color.normal), ins.show( idx ) if p != [] : print "%s[" % Color.green, ' '.join("%x" % i for i in p), "]%s" % Color.normal, print idx += ( ins.get_length() ) nb += 1 def PrettyShow1( basic_blocks ) : idx = 0 nb = 0 offset_color = CONF["COLORS"]["OFFSET"] offset_addr_color = CONF["COLORS"]["OFFSET_ADDR"] instruction_name_color = CONF["COLORS"]["INSTRUCTION_NAME"] branch_false_color = CONF["COLORS"]["BRANCH_FALSE"] branch_true_color = CONF["COLORS"]["BRANCH_TRUE"] branch_color = CONF["COLORS"]["BRANCH"] exception_color = CONF["COLORS"]["EXCEPTION"] bb_color = CONF["COLORS"]["BB"] for i in basic_blocks : print "%s%s%s : " % (bb_color, i.name, Color.normal) for ins in i.ins : notes = ins.get_notes() if notes != [] : for note in notes : _PrintNote(note, 1) print "\t%s%-3d%s(%s%08x%s)" % (offset_color, nb, Color.normal, offset_addr_color, idx, Color.normal), print "%s%-20s%s %s" %(instruction_name_color, ins.get_name(), Color.normal, ins.get_output()), if ins == i.ins[-1] and i.childs != [] : if len(i.childs) == 2 : print "%s[ %s%s " % (branch_false_color, i.childs[0][2].name, branch_true_color), print ' '.join("%s" % c[2].name for c in i.childs[1:]), "]%s" % Color.normal, else : print "%s[" % branch_color, ' '.join("%s" % c[2].name for c in i.childs), "]%s" % Color.normal, idx += ins.get_length() nb += 1 print if i.exception_analysis != None : print "\t", "%s%s%s" % (exception_color, i.exception_analysis.show_buff(), Color.normal) print def PrettyShow1bis( basic_blocks ) : idx = 0 nb = 0 for i in basic_blocks : print "%s : " % (i.name) for ins in i.ins : print "\t%d(%x)" % (nb, idx), ins.show( idx ) if ins == i.ins[-1] and i.childs != [] : print "[", ' '.join("%s" % c[2].name for c in i.childs), "]", idx += ins.get_length() nb += 1 print print # Use to print diff basic blocks ! def PrettyShow2( basic_blocks, exclude_tags=[] ) : idx = 0 nb = 0 for i in basic_blocks : if i.bb_tag in exclude_tags : continue if i.bb_tag == 1 : print "%sDIFF%s" % (Color.cyan, Color.normal), elif i.bb_tag == 2 : print "%sNEW%s" %(Color.cyan, Color.normal), print "%s%s%s : " % (Color.purple, i.name, Color.normal) for ins in i.ins : print "\t%s%d%s(%s%x%s)" % (Color.yellow, nb, Color.normal, Color.yellow, idx, Color.normal), try : tag = getattr(ins, "diff_tag") except AttributeError : tag = 0 if tag == 1 : print "%s" % Color.green, elif tag == 2 : print "%s" % Color.red, ins.show( idx ) childs = None try : childs = getattr( ins, "childs" ) except AttributeError : if ins == i.ins[-1] : childs = i.childs if childs != None and childs != [] : if len(childs) == 2 : print "%s[ %s%s " % (Color.red, childs[0][2].name, Color.green), print ' '.join("%s" % c[2].name for c in childs[1:]), "]%s" % Color.normal, else : print "%s[" % Color.blue, ' '.join("%s" % c[2].name for c in childs), "]%s" % Color.normal, if tag == 0 : idx += ins.get_length() nb += 1 print print def method2dot( mx ) : """ Export analysis method to dot format @param mx : MethodAnalysis object @rtype : dot format buffer """ vm = mx.get_vm() buff = "" for i in mx.basic_blocks.get() : val = "green" if len(i.childs) > 1 : val = "red" elif len(i.childs) == 1 : val = "blue" for j in i.childs : buff += "\"%s\" -> \"%s\" [color=\"%s\"];\n" % ( i.get_name(), j[-1].get_name(), val ) if val == "red" : val = "green" idx = i.start label = "" for ins in i.ins : label += "%x %s\l" % (idx, vm.dotbuff(ins, idx)) idx += ins.get_length() buff += "\"%s\" [color=\"lightgray\", label=\"%s\"]\n" % (i.get_name(), label) return buff def method2format( output, _format="png", mx = None, raw = False ) : """ Export method to a specific file format @param output : output filename @param _format : format type (png, jpg ...) (default : png) @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer """ try : import pydot except ImportError : error("module pydot not found") buff = "digraph code {\n" buff += "graph [bgcolor=white];\n" buff += "node [color=lightgray, style=filled shape=box fontname=\"Courier\" fontsize=\"8\"];\n" if raw == False : buff += method2dot( mx ) else : buff += raw buff += "}" d = pydot.graph_from_dot_data( buff ) if d : getattr(d, "write_" + _format)( output ) def method2png( output, mx = None, raw = False ) : """ Export method to a png file format @param output : output filename @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer """ buff = raw if raw == False : buff = method2dot( mx ) method2format( output, "png", mx, buff ) def method2jpg( output, mx = None, raw = False ) : """ Export method to a jpg file format @param output : output filename @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer """ buff = raw if raw == False : buff = method2dot( mx ) method2format( output, "jpg", mx, buff ) class SV : """SV is used to handle more easily a value""" def __init__(self, size, buff) : self.__size = size self.__value = unpack(self.__size, buff)[0] def _get(self) : return pack(self.__size, self.__value) def __str__(self) : return "0x%x" % self.__value def __int__(self) : return self.__value def get_value_buff(self) : return self._get() def get_value(self) : return self.__value def set_value(self, attr) : self.__value = attr class SVs : """SVs is used to handle more easily a structure of different values""" def __init__(self, size, ntuple, buff) : self.__size = size self.__value = ntuple._make( unpack( self.__size, buff ) ) def _get(self) : l = [] for i in self.__value._fields : l.append( getattr( self.__value, i ) ) return pack( self.__size, *l) def _export(self) : return [ x for x in self.__value._fields ] def get_value_buff(self) : return self._get() def get_value(self) : return self.__value def set_value(self, attr) : self.__value = self.__value._replace( **attr ) def __str__(self) : return self.__value.__str__() def object_to_str(obj) : if isinstance(obj, str) : return obj elif isinstance(obj, bool) : return "" elif isinstance(obj, int) : return pack("<L", obj) elif obj == None : return "" else : #print type(obj), obj return obj.get_raw() class MethodBC(object) : def show(self, value) : getattr(self, "show_" + value)() class BuffHandle : def __init__(self, buff) : self.__buff = buff self.__idx = 0 def read_b(self, size) : return self.__buff[ self.__idx : self.__idx + size ] def read(self, size) : if isinstance(size, SV) : size = size.value buff = self.__buff[ self.__idx : self.__idx + size ] self.__idx += size return buff def end(self) : return self.__idx == len(self.__buff) class Buff : def __init__(self, offset, buff) : self.offset = offset self.buff = buff self.size = len(buff) class _Bytecode(object) : def __init__(self, buff) : try : import psyco psyco.full() except ImportError : pass self.__buff = buff self.__idx = 0 def read(self, size) : if isinstance(size, SV) : size = size.value buff = self.__buff[ self.__idx : self.__idx + size ] self.__idx += size return buff def readat(self, off) : if isinstance(off, SV) : off = off.value return self.__buff[ off : ] def read_b(self, size) : return self.__buff[ self.__idx : self.__idx + size ] def set_idx(self, idx) : if isinstance(idx, SV) : self.__idx = idx.value else : self.__idx = idx def get_idx(self) : return self.__idx def add_idx(self, idx) : self.__idx += idx def register(self, type_register, fct) : self.__registers[ type_register ].append( fct ) def get_buff(self) : return self.__buff def length_buff(self) : return len( self.__buff ) def save(self, filename) : fd = open(filename, "w") buff = self._save() fd.write( buff ) fd.close() def FormatClassToJava(input) : """ Transofmr a typical xml format class into java format @param input : the input class name """ return "L" + input.replace(".", "/") + ";" def FormatClassToPython(input) : i = input[:-1] i = i.replace("/", "_") i = i.replace("$", "_") return i def FormatNameToPython(input) : i = input.replace("<", "") i = i.replace(">", "") i = i.replace("$", "_") return i def FormatDescriptorToPython(input) : i = input.replace("/", "_") i = i.replace(";", "") i = i.replace("[", "") i = i.replace("(", "") i = i.replace(")", "") i = i.replace(" ", "") i = i.replace("$", "") return i ####################### class/method/field export ######################## def ExportVMToPython(vm) : """ Export classes/methods/fields' names in the python namespace @param vm : a VM object (DalvikVMFormat, JVMFormat) """ for _class in vm.get_classes() : ### Class name = "CLASS_" + FormatClassToPython( _class.get_name() ) setattr( vm, name, _class ) ### Methods m = {} for method in _class.get_methods() : if method.get_name() not in m : m[ method.get_name() ] = [] m[ method.get_name() ].append( method ) for i in m : if len(m[i]) == 1 : j = m[i][0] name = "METHOD_" + FormatNameToPython( j.get_name() ) setattr( _class, name, j ) else : for j in m[i] : name = "METHOD_" + FormatNameToPython( j.get_name() ) + "_" + FormatDescriptorToPython( j.get_descriptor() ) setattr( _class, name, j ) ### Fields f = {} for field in _class.get_fields() : if field.get_name() not in f : f[ field.get_name() ] = [] f[ field.get_name() ].append( field ) for i in f : if len(f[i]) == 1 : j = f[i][0] name = "FIELD_" + FormatNameToPython( j.get_name() ) setattr( _class, name, j ) else : for j in f[i] : name = "FIELD_" + FormatNameToPython( j.get_name() ) + "_" + FormatDescriptorToPython( j.get_descriptor() ) setattr( _class, name, j )
Python
#!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'androguard', version = '1.2', packages = find_packages(), scripts = ['androaxml.py', 'androcsign.py', 'androdiff.py', 'androgexf.py', 'androlyze.py', 'andromercury.py', 'androrisk.py', 'androsign.py', 'androsim.py', 'androxgmml.py', 'apkviewer.py', 'androdd.py', 'androapkinfo.py', ], install_requires=['distribute'], )
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os from optparse import OptionParser from androguard.core import androconf from androguard.core.bytecodes import apk, dvm from androguard.core.analysis import analysis sys.path.append("./elsim") from elsim import elsim from elsim.elsim_dalvik import ProxyDalvik, FILTERS_DALVIK_SIM from elsim.elsim_dalvik import ProxyDalvikStringMultiple, ProxyDalvikStringOne, FILTERS_DALVIK_SIM_STRING option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 2 } option_1 = { 'name' : ('-t', '--threshold'), 'help' : 'specify the threshold (0.0 to 1.0) to know if a method is similar. This option will impact on the filtering method. Because if you specify a higher value of the threshold, you will have more associations', 'nargs' : 1 } option_2 = { 'name' : ('-c', '--compressor'), 'help' : 'specify the compressor (BZ2, ZLIB, SNAPPY, LZMA, XZ). The final result depends directly of the type of compressor. But if you use LZMA for example, the final result will be better, but it take more time', 'nargs' : 1 } option_4 = { 'name' : ('-d', '--display'), 'help' : 'display all information about methods', 'action' : 'count' } option_5 = { 'name' : ('-n', '--new'), 'help' : 'calculate the final score only by using the ratio of included methods', 'action' : 'count' } option_6 = { 'name' : ('-e', '--exclude'), 'help' : 'exclude specific class name (python regexp)', 'nargs' : 1 } option_7 = { 'name' : ('-s', '--size'), 'help' : 'exclude specific method below the specific size (specify the minimum size of a method to be used (it is the length (bytes) of the dalvik method)', 'nargs' : 1 } option_8 = { 'name' : ('-x', '--xstrings'), 'help' : 'display similarities of strings', 'action' : 'count' } option_9 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } option_10 = { 'name' : ('-l', '--library'), 'help' : 'use python library (python) or specify the path of the shared library)', 'nargs' : 1 } options = [option_0, option_1, option_2, option_4, option_5, option_6, option_7, option_8, option_9, option_10] def check_one_file(a, d1, dx1, FS, threshold, file_input, view_strings=False, new=True, library=True) : d2 = None ret_type = androconf.is_android( file_input ) if ret_type == "APK" : a = apk.APK( file_input ) d2 = dvm.DalvikVMFormat( a.get_dex() ) elif ret_type == "DEX" : d2 = dvm.DalvikVMFormat( open(file_input, "rb").read() ) if d2 == None : return dx2 = analysis.VMAnalysis( d2 ) el = elsim.Elsim( ProxyDalvik(d1, dx1), ProxyDalvik(d2, dx2), FS, threshold, options.compressor, libnative=library ) el.show() print "\t--> methods: %f%% of similarities" % el.get_similarity_value(new) if options.display : print "SIMILAR methods:" diff_methods = el.get_similar_elements() for i in diff_methods : el.show_element( i ) print "IDENTICAL methods:" new_methods = el.get_identical_elements() for i in new_methods : el.show_element( i ) print "NEW methods:" new_methods = el.get_new_elements() for i in new_methods : el.show_element( i, False ) print "DELETED methods:" del_methods = el.get_deleted_elements() for i in del_methods : el.show_element( i ) print "SKIPPED methods:" skipped_methods = el.get_skipped_elements() for i in skipped_methods : el.show_element( i ) if view_strings : els = elsim.Elsim( ProxyDalvikStringMultiple(d1, dx1), ProxyDalvikStringMultiple(d2, dx2), FILTERS_DALVIK_SIM_STRING, threshold, options.compressor, libnative=library ) #els = elsim.Elsim( ProxyDalvikStringOne(d1, dx1), # ProxyDalvikStringOne(d2, dx2), FILTERS_DALVIK_SIM_STRING, threshold, options.compressor, libnative=library ) els.show() print "\t--> strings: %f%% of similarities" % els.get_similarity_value(new) if options.display : print "SIMILAR strings:" diff_strings = els.get_similar_elements() for i in diff_strings : els.show_element( i ) print "IDENTICAL strings:" new_strings = els.get_identical_elements() for i in new_strings : els.show_element( i ) print "NEW strings:" new_strings = els.get_new_elements() for i in new_strings : els.show_element( i, False ) print "DELETED strings:" del_strings = els.get_deleted_elements() for i in del_strings : els.show_element( i ) print "SKIPPED strings:" skipped_strings = els.get_skipped_elements() for i in skipped_strings : els.show_element( i ) def check_one_directory(a, d1, dx1, FS, threshold, directory, view_strings=False, new=True, library=True) : for root, dirs, files in os.walk( directory, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f print "filename: %s ..." % real_filename check_one_file(a, d1, dx1, FS, threshold, real_filename, view_strings, new, library) ############################################################ def main(options, arguments) : if options.input != None : a = None ret_type = androconf.is_android( options.input[0] ) if ret_type == "APK" : a = apk.APK( options.input[0] ) d1 = dvm.DalvikVMFormat( a.get_dex() ) elif ret_type == "DEX" : d1 = dvm.DalvikVMFormat( open(options.input[0], "rb").read() ) dx1 = analysis.VMAnalysis( d1 ) threshold = None if options.threshold != None : threshold = float(options.threshold) FS = FILTERS_DALVIK_SIM FS[elsim.FILTER_SKIPPED_METH].set_regexp( options.exclude ) FS[elsim.FILTER_SKIPPED_METH].set_size( options.size ) new = True if options.new != None : new = False library = True if options.library != None : library = options.library if options.library == "python" : library = False if os.path.isdir( options.input[1] ) == False : check_one_file( a, d1, dx1, FS, threshold, options.input[1], options.xstrings, new, library ) else : check_one_directory(a, d1, dx1, FS, threshold, options.input[1], options.xstrings, new, library ) elif options.version != None : print "Androsim version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os, cmd, threading, re, atexit from optparse import OptionParser import androguard, androconf, jvm # External Libraries # python-ptrace : http://bitbucket.org/haypo/python-ptrace/ from ptrace import PtraceError from ptrace.tools import locateProgram from ptrace.debugger import ProcessExit, DebuggerError, PtraceDebugger, ProcessExit, ProcessSignal, NewProcessEvent, ProcessExecution from ptrace.debugger.memory_mapping import readProcessMappings #################### option_0 = { 'name' : ('-i', '--input'), 'help' : 'pid', 'nargs' : 1 } option_1 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } options = [option_0, option_1] MAGIC_PATTERN = "\xca\xfe\xba\xbe" class AndroPreDump : def __init__(self, input) : self.data = [] self.pid = int(input) self.debugger = PtraceDebugger() self.process = self.debugger.addProcess(self.pid, is_attached=False) atexit.register(self.debugger.quit) Header = False Code = False self.procmaps = readProcessMappings(self.process) for pm in self.procmaps: if pm.permissions.find("w") != -1 and pm.pathname == None : # if Code == False and Header == True : # data = self.process.readBytes(pm.start, pm.end-pm.start) # idx = data.find("SourceFile") # if idx != -1 : # print "CODE", pm # self.data.append( (pm, data, idx) ) # Code = True if Header == False : data = self.process.readBytes(pm.start, pm.end-pm.start) idx = data.find(MAGIC_PATTERN) if idx != -1 : print "HEADER", pm self.data.append( (pm, data) ) Header = True self.dumpMemory( "java_dump_memory" ) # self.dumpFiles( "java_files" ) def write(self, idx, buff) : self.process.writeBytes( idx, buff ) def getFilesBuffer(self) : for i in self.data : d = i[1] x = d.find(MAGIC_PATTERN) idx = x while x != -1 : yield i[0].start + idx, d[x:] d = d[x+len(MAGIC_PATTERN):] idx += len(MAGIC_PATTERN) x = d.find(MAGIC_PATTERN) idx += x def dumpMemory(self, base_filename) : for i in self.data : fd = open(base_filename + "-" + "0x%x-0x%x" % (i[0].start, i[0].end), "w") fd.write( i[1] ) fd.close() def dumpFiles(self, base_filename) : for i in self.data : fd = open(base_filename + "-" + "0x%x-0x%x" % (i[0].start + i[2], i[0].end), "w") fd.write( i[1][i[2]:] ) fd.close() class AndroDump : def __init__(self, adp) : self.__adp = adp for i in self.__adp.getFilesBuffer() : try : print "0x%x :" % (i[0]) j = jvm.JVMFormat( i[1] ) for method in j.get_methods() : print "\t -->", method.get_class_name(), method.get_name(), method.get_descriptor() # if (method.get_class_name() == "Test2" and method.get_name() == "main") : # print "patch" # code = method.get_code() #code.remplace_at( 51, [ "bipush", 20 ] ) # code.show() # print "\t\t-> %x" % (len(j.save())) # self.__adp.write( i[0], j.save() ) except Exception, e : print e def main(options, arguments) : if options.input != None : apd = AndroPreDump( options.input ) AndroDump( apd ) elif options.version != None : print "Androdump version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os, cmd, threading, code, re from optparse import OptionParser from androguard.core import * from androguard.core.androgen import * from androguard.core.androconf import * from androguard.core.bytecode import * from androguard.core.bytecodes.jvm import * from androguard.core.bytecodes.dvm import * from androguard.core.bytecodes.apk import * from androguard.core.analysis.analysis import * from androguard.core.analysis.ganalysis import * from androguard.core.analysis.risk import * from androguard.decompiler.decompiler import * from androguard.core import androconf from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config from cPickle import dumps, loads option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 } option_1 = { 'name' : ('-d', '--display'), 'help' : 'display the file in human readable format', 'action' : 'count' } option_2 = { 'name' : ('-m', '--method'), 'help' : 'display method(s) respect with a regexp', 'nargs' : 1 } option_3 = { 'name' : ('-f', '--field'), 'help' : 'display field(s) respect with a regexp', 'nargs' : 1 } option_4 = { 'name' : ('-s', '--shell'), 'help' : 'open an interactive shell to play more easily with objects', 'action' : 'count' } option_5 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } option_6 = { 'name' : ('-p', '--pretty'), 'help' : 'pretty print !', 'action' : 'count' } option_7 = { 'name' : ('-t', '--type_pretty'), 'help' : 'set the type of pretty print (0, 1) !', 'nargs' : 1 } option_8 = { 'name' : ('-x', '--xpermissions'), 'help' : 'show paths of permissions', 'action' : 'count' } options = [option_0, option_1, option_2, option_3, option_4, option_5, option_6, option_7, option_8] def save_session(l, filename) : """ save your session ! @param l : a list of objects @param filename : output filename to save the session """ fd = open(filename, "w") fd.write( dumps(l, -1) ) fd.close() def load_session(filename) : """ load your session ! @param filename : the filename where the sessions has been saved @rtype : the elements of your session """ return loads( open(filename, "r").read() ) def interact() : cfg = Config() ipshell = InteractiveShellEmbed(config=cfg, banner1="Androlyze version %s" % androconf.ANDROGUARD_VERSION) ipshell() def AnalyzeAPK(filename, raw=False, decompiler=None) : """ Analyze an android application and setup all stuff for a more quickly analysis ! @param filename : the filename of the android application or a buffer which represents the application @param raw : True is you would like to use a buffer @param decompiler : ded, dex2jad, dad @rtype : return the APK, DalvikVMFormat, and VMAnalysis objects """ androconf.debug("APK ...") a = APK(filename, raw) d, dx = AnalyzeDex( filename, a.get_dex() ) if decompiler != None : androconf.debug("Decompiler ...") decompiler = decompiler.lower() if decompiler == "dex2jad" : d.set_decompiler( DecompilerDex2Jad( d, androconf.CONF["PATH_DEX2JAR"], androconf.CONF["BIN_DEX2JAR"], androconf.CONF["PATH_JAD"], androconf.CONF["BIN_JAD"] ) ) elif decompiler == "ded" : d.set_decompiler( DecompilerDed( d, androconf.CONF["PATH_DED"], androconf.CONF["BIN_DED"] ) ) elif decompiler == "dad" : d.set_decompiler( DecompilerDAD( d, dx ) ) else : print "Unknown decompiler, use default", decompiler d.set_decompiler( DecompilerDAD( d, dx ) ) return a, d, dx def AnalyzeDex(filename, raw=False) : """ 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 @param raw : True is you would like to use a buffe @rtype : return the DalvikVMFormat, and VMAnalysis objects """ androconf.debug("DalvikVMFormat ...") d = None if raw == False : d = DalvikVMFormat( open(filename, "rb").read() ) else : d = DalvikVMFormat( raw ) androconf.debug("EXPORT VM to python namespace") ExportVMToPython( d ) androconf.debug("VMAnalysis ...") dx = VMAnalysis( d ) androconf.debug("GVMAnalysis ...") gx = GVMAnalysis( dx, None ) d.set_vmanalysis( dx ) d.set_gvmanalysis( gx ) androconf.debug("XREF ...") d.create_xref() androconf.debug("DREF ...") d.create_dref() return d, dx def AAnalyzeDex(filename, raw=False, decompiler="dad") : """ 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 @param raw : True is you would like to use a buffe @param decompiler : ded, dex2jad, dad @rtype : return the DalvikVMFormat, and VMAnalysis objects """ d, dx = AnalyzeDex( filename, raw ) androconf.debug("Decompiler ...") decompiler = decompiler.lower() if decompiler == "dex2jad" : d.set_decompiler( DecompilerDex2Jad( d, androconf.CONF["PATH_DEX2JAR"], androconf.CONF["BIN_DEX2JAR"], androconf.CONF["PATH_JAD"], androconf.CONF["BIN_JAD"] ) ) elif decompiler == "ded" : d.set_decompiler ( DecompilerDed( d, androconf.CONF["PATH_DED"], androconf.CONF["BIN_DED"] ) ) elif decompiler == "dad" : d.set_decompiler( DecompilerDAD( d, dx ) ) return d, dx def AnalyzeElf(filename, raw=False) : from androguard.core.binaries.elf import ELF e = None if raw == False: e = ELF( open(filename, "rb").read() ) else: e = ELF( raw ) ExportElfToPython( e ) return e def AnalyzeJAR(filename, raw=False) : """ Analyze an java jar application and setup all stuff for a more quickly analysis ! @param filename : the filename of the jar or a buffer which represents the application @param raw : True is you would like to use a buffer @rtype : return the JAR, JVMFormat classes """ androconf.debug("JAR ...") a = JAR(filename, raw) d = AnalyzeClasses( a.get_classes() ) return a, d def AnalyzeClasses( classes ) : d = {} for i in classes : d[i[0]] = JVMFormat( i[1] ) return d def ExportElfToPython(e) : for function in e.get_functions(): name = "FUNCTION_" + function.name setattr( e, name, function ) def sort_length_method(vm) : l = [] for m in vm.get_methods() : code = m.get_code() if code != None : l.append( (code.get_length(), (m.get_class_name(), m.get_name(), m.get_descriptor()) ) ) l.sort(reverse=True) return l def main(options, arguments) : if options.shell != None : interact() elif options.input != None : _a = AndroguardS( options.input ) if options.type_pretty != None : CONF["PRETTY_SHOW"] = int( options.type_pretty ) if options.display != None : if options.pretty != None : _a.ianalyze() _a.pretty_show() else : _a.show() elif options.method != None : for method in _a.get("method", options.method) : if options.pretty != None : _a.ianalyze() method.pretty_show() else : method.show() elif options.field != None : for field in _a.get("field", options.field) : field.show() elif options.xpermissions != None : _a.ianalyze() perms_access = _a.get_analysis().get_permissions( [] ) for perm in perms_access : print "PERM : ", perm for path in perms_access[ perm ] : print "\t%s %s %s (@%s-0x%x) ---> %s %s %s" % ( path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), \ path.get_bb().get_name(), path.get_bb().start + path.get_idx(), \ path.get_class_name(), path.get_name(), path.get_descriptor()) elif options.version != None : print "Androlyze version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from xml.sax.saxutils import escape, unescape import sys, hashlib, os from optparse import OptionParser from androguard.core.bytecodes import apk, dvm from androguard.core.analysis import analysis, ganalysis from androguard.core import androconf option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input (dex, apk)', 'nargs' : 1 } option_1 = { 'name' : ('-o', '--output'), 'help' : 'filename output of the gexf', 'nargs' : 1 } options = [option_0, option_1] def main(options, arguments) : if options.input != None and options.output != None : ret_type = androconf.is_android( options.input ) vm = None a = None if ret_type == "APK" : a = apk.APK( options.input ) if a.is_valid_APK() : vm = dvm.DalvikVMFormat( a.get_dex() ) else : print "INVALID APK" elif ret_type == "DEX" : try : vm = dvm.DalvikVMFormat( open(options.input, "rb").read() ) except Exception, e : print "INVALID DEX", e vmx = analysis.VMAnalysis( vm ) gvmx = ganalysis.GVMAnalysis( vmx, a ) b = gvmx.export_to_gexf() androconf.save_to_disk( b, options.output ) if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os from optparse import OptionParser from androguard.core import androconf from androguard.core.bytecodes import apk from androguard.core.analysis import risk option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 1 } option_1 = { 'name' : ('-a', '--analysis'), 'help' : 'perform analysis to calculate the risk', 'action' : 'count' } option_2 = { 'name' : ('-m', '--method'), 'help' : 'perform analysis of each method', 'action' : 'count' } option_3 = { 'name' : ('-d', '--directory'), 'help' : 'directory : use this directory', 'nargs' : 1 } option_4 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' } options = [option_0, option_1, option_2, option_3, option_4] def analyze_app(filename, ri, a, analysis, method) : print filename, ri.with_apk( a, analysis, method ) def analyze_dex(filename, ri, d, analysis, method) : print filename, ri.with_dex( d, analysis_method=method ) def main(options, arguments) : if options.input != None : ri = risk.RiskIndicator() ret_type = androconf.is_android( options.input ) if ret_type == "APK" : a = apk.APK( options.input ) analyze_app( options.input, ri, a, options.analysis, options.method ) elif ret_type == "DEX" : analyze_dex( options.input, ri, open(options.input, "r").read(), options.analysis, options.method ) elif options.directory != None : ri = risk.RiskIndicator() for root, dirs, files in os.walk( options.directory, followlinks=True ) : if files != [] : for f in files : real_filename = root if real_filename[-1] != "/" : real_filename += "/" real_filename += f ret_type = androconf.is_android( real_filename ) if ret_type == "APK" : try : a = apk.APK( real_filename ) analyze_app( real_filename, ri, a, options.analysis, options.method ) except Exception, e : print e elif ret_type == "DEX" : analyze_dex( real_filename, ri, open(real_filename, "r").read(), options.analysis, options.method ) elif options.version != None : print "Androrisk version %s" % androconf.ANDROGUARD_VERSION if __name__ == "__main__" : parser = OptionParser() for option in options : param = option['name'] del option['name'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
Python
#!/usr/bin/env python f = open("permi", "r") b = f.readlines() f.close() for i in b : v = i.split(" ") if len(v) > 2 : buff = ' '.join( j for j in v[3:] ) buff = buff[:-1] j = 0 while j < len(buff) and buff[j] == ' ' : j += 1 buff = buff[j:] if len(buff) > 1 and buff[-1] != '.' : buff += "." print " \"%s\"" % v[2], ":", "\"%s\"," % buff
Python
#!/usr/bin/env python from xml.dom import minidom MANIFEST = "tools/permissions/AndroidManifest.xml" STRINGS = "tools/permissions/strings.xml" manifest_document = minidom.parse( MANIFEST ) strings_document = minidom.parse( STRINGS ) dstrings = {} for i in strings_document.getElementsByTagName( "string" ) : try : dstrings[ i.getAttribute( "name") ] = i.firstChild.data except AttributeError : pass for i in manifest_document.getElementsByTagName( "permission" ) : label_strings = i.getAttribute( "android:label" )[8:] description_strings = i.getAttribute( "android:description" )[8:] rdesc = "\"\"" rlabel = "\"\"" if label_strings == "" or description_strings == "" : if label_strings != "" : rlabel = dstrings[ label_strings ] elif description_strings != "" : rdesc = dstrings[ description_strings ] else : rlabel = dstrings[ label_strings ] rdesc = dstrings[ description_strings ] name = i.getAttribute("android:name") name = name[ name.rfind(".") + 1: ] print "\t\t\"%s\"" % name, ": [", "\"%s\"" % i.getAttribute( "android:protectionLevel" ), ",", rlabel, ",", rdesc, "],"
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Anthony Desnos <desnos at t0t0.org> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. from BeautifulSoup import BeautifulSoup, Tag import os, sys, re MANIFEST_PERMISSION_HTML = "docs/reference/android/Manifest.permission.html" PERMS = {} PERMS_RE = None PERMS_API = {} try : import psyco psyco.full() except ImportError : pass class Constant : def __init__(self, name, perms, desc_return) : self.name = name self.perms = perms self.desc_return = desc_return class Function : def __init__(self, name, perms, desc_return) : self.name = name self.perms = perms self.desc_return = desc_return def extractPerms( filename ) : soup = BeautifulSoup( open( filename ) ) s = "" for i in soup.findAll("table", attrs={'id' : "constants"}) : for j in i.findChildren( "tr" ): td = j.findChildren( "td" ) if td != [] : _type = str( td[0].text ) _name = str( td[1].text ) _desc = str( td[2].text ) PERMS[_name] = [ _type, _desc ] PERMS_API[_name] = {} s += _name + "|" #PERMS_RE = re.compile(s[:-1]) def extractInformation( filename ) : soup = BeautifulSoup( open( filename ) ) package = filename[ filename.find("reference/android/") : ][10:-5].replace("//", "/") package = package.replace("/", ".") for i in soup.findAll('a', attrs={'name' : re.compile(".")}) : next_div = i.findNext("div") perms = [] for perm in PERMS : perm_access = next_div.findAll(text=re.compile(perm)) if perm_access != [] : perms.append( perm ) #print i.name, i.get("name"), perm_access if perms != [] : element = None descs = i.findNext("span", attrs={'class' : 'normal'}) _descriptor_return = descs.next _descriptor_return = _descriptor_return.replace('', '') _descriptor_return = _descriptor_return.split() _descriptor_return = ' '.join(str(_d)for _d in _descriptor_return) if isinstance(descs.next.next, Tag) : _descriptor_return += " " + descs.next.next.text if len(next_div.findNext("h4").findAll("span")) > 2 : element = Function( i.get("name"), perms, _descriptor_return ) else : element = Constant( i.get("name"), perms, _descriptor_return ) for perm in perms : if package not in PERMS_API[ perm ] : PERMS_API[ perm ][ package ] = [] PERMS_API[ perm ][ package ].append( element ) def save_file( filename ): fd = open( filename, "w" ) fd.write("PERMISSIONS = {\n") for i in PERMS_API : if len(PERMS_API[ i ]) > 0 : fd.write("\"%s\" : {\n" % ( i )) for package in PERMS_API[ i ] : if len(PERMS_API[ i ][ package ]) > 0 : fd.write("\t\"%s\" : [\n" % package) for j in PERMS_API[ i ][ package ] : if isinstance(j, Function) : fd.write( "\t\t[\"F\"," "\"" + j.name + "\"," + "\"" + j.desc_return + "\"]" + ",\n") else : fd.write( "\t\t[\"C\"," "\"" + j.name + "\"," + "\"" + j.desc_return + "\"]" + ",\n") if len(PERMS_API[ i ][ package ]) > 0 : fd.write("\t],\n") if len(PERMS_API[ i ]) > 0 : fd.write("},\n\n") fd.write("}") fd.close() BASE_DOCS = sys.argv[1] extractPerms( BASE_DOCS + MANIFEST_PERMISSION_HTML ) ANDROID_PACKAGES = [ "accessibilityservice", "accounts", "animation", "app", "appwidget", "bluetooth", "content", "database", "drm", "gesture", "graphics", "hardware", "inputmethodservice", "location", "media", "net", "nfc", "opengl", "os", "preference", "provider", "renderscript", "sax", "service", "speech", "telephony", "text", "util", "view", "webkit", "widget", ] ANDROID_PACKAGES2 = [ "telephony" ] for i in ANDROID_PACKAGES : for root, dirs, files in os.walk( BASE_DOCS + "docs/reference/android/" + i + "/" ) : for file in files : print "Extracting from %s" % (root + "/" + file) #extractInformation( "/home/pouik/Bureau/android/android-sdk-linux_86/docs/reference/android/accounts/AccountManager.html" ) extractInformation( root + "/" + file ) #BASE_DOCS + "docs/reference/android/telephony/TelephonyManager.html" ) #extractInformation( BASE_DOCS + "docs/reference/android/net/sip/SipAudioCall.html" ) #android/accounts/Account.html" ) #"docs/reference/android/accounts/AccountManager.html" ) for i in PERMS_API : if len(PERMS_API[ i ]) > 0 : print "PERMISSION ", i for package in PERMS_API[ i ] : print "\t package ", package for j in PERMS_API[ i ][ package ] : if isinstance(j, Function) : print "\t\t function : ", j.name else : print "\t\t constant : ", j.name save_file( "./dvm_permissions_unformatted.py" ) #for i in soup.findAll('a') : #, attrs={'name' : re.compile("ACTION")}) : # if i.get("name") != None : # print i.name, i.get("name")#, i.findNextSlibing(text=re.compile("READ_PHONE_STATE")) #for i in soup.findAll(text=re.compile("READ_PHONE_STATE")) : # print i, i.parent.name, i.findPrevious(re.compile('^A')), i.findPreviousSibling(re.compile('^A')) # if i.contents != [] : # if i.contents[0] == "READ_PHONE_STATE" : # print "here", i.parent # parent = i.parent # while parent.name != "A" : # parent = parent.parent # print "step", parent # if "class" in parent : # print "step2", parent["class"] # time.sleep( 1 ) # print "end", previous.name
Python
PERMISSIONS_BY_HAND = { "SEND_SMS" : { "android.telephony.SmsManager" : [ [ "F", "getDefault()", "static SmsManager" ], [ "F", "sendDataMessage(java.lang.String, java.lang.String, short, byte[], PendingIntent, PendingIntent)", "void" ], # [ "F", "sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents", "void" ], [ "F", "sendTextMessage(java.lang.String, java.lang.String, java.lang.String, PendingIntent, PendingIntent)", "void" ], ], "android.telephony.gsm.SmsManager" : [ [ "F", "getDefault()", "static android.telephony.gsm.SmsManager" ], [ "F", "sendDataMessage(java.lang.String, java.lang.String, short, byte[], PendingIntent, PendingIntent)", "void" ], # [ "F", "sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents", "void" ], [ "F", "sendTextMessage(java.lang.String, java.lang.String, java.lang.String, PendingIntent, PendingIntent)", "void" ], ], }, "SET_WALLPAPER" : { "android.app.WallpaperManager" : [ [ "F", "setBitmap(Bitmap)", "void" ], ], }, "READ_CONTACTS" : { "android.provider.ContactsContract$CommonDataKinds$Phone" : [ [ "C", "CONTENT_URI", "Uri" ] ], }, }
Python
PERMISSIONS = { "BIND_DEVICE_ADMIN" : { "android.app.admin.DeviceAdminReceiver" : [ ["C","ACTION_DEVICE_ADMIN_ENABLED","public static final String"], ], }, "FACTORY_TEST" : { "android.content.pm.ApplicationInfo" : [ ["C","FLAG_FACTORY_TEST","public static final int"], ["C","flags","public int"], ], "android.content.Intent" : [ ["C","IntentResolution","public static final String"], ["C","ACTION_FACTORY_TEST","public static final String"], ], }, "BIND_INPUT_METHOD" : { "android.view.inputmethod.InputMethod" : [ ["C","SERVICE_INTERFACE","public static final String"], ], }, "AUTHENTICATE_ACCOUNTS" : { "android.accounts.AccountManager" : [ ["F","addAccountExplicitly(android.accounts.Account, java.lang.String, android.os.Bundle)","public boolean"], ["F","getPassword(android.accounts.Account)","public String"], ["F","getUserData(android.accounts.Account, java.lang.String)","public String"], ["F","peekAuthToken(android.accounts.Account, java.lang.String)","public String"], ["F","setAuthToken(android.accounts.Account, java.lang.String, java.lang.String)","public void"], ["F","setPassword(android.accounts.Account, java.lang.String)","public void"], ["F","setUserData(android.accounts.Account, java.lang.String, java.lang.String)","public void"], ], }, "INTERNET" : { "android.drm.DrmErrorEvent" : [ ["C","TYPE_NO_INTERNET_CONNECTION","public static final int"], ], }, "RECORD_AUDIO" : { "android.net.sip.SipAudioCall" : [ ["F","startAudio()","public void"], ], }, "ACCESS_MOCK_LOCATION" : { "android.location.LocationManager" : [ ["F","addTestProvider(java.lang.String, boolean, boolean, boolean, boolean, boolean, boolean, boolean, int, int)","public void"], ["F","clearTestProviderEnabled(java.lang.String)","public void"], ["F","clearTestProviderLocation(java.lang.String)","public void"], ["F","clearTestProviderStatus(java.lang.String)","public void"], ["F","removeTestProvider(java.lang.String)","public void"], ["F","setTestProviderEnabled(java.lang.String, boolean)","public void"], ["F","setTestProviderLocation(java.lang.String, android.location.Location)","public void"], ["F","setTestProviderStatus(java.lang.String, int, android.os.Bundle, long)","public void"], ], }, "VIBRATE" : { "android.provider.Settings.System" : [ ["C","VIBRATE_ON","public static final String"], ], "android.app.Notification" : [ ["C","DEFAULT_VIBRATE","public static final int"], ["C","defaults","public int"], ], "android.app.Notification.Builder" : [ ["F","setDefaults(int)","public Notification.Builder"], ], "android.media.AudioManager" : [ ["C","EXTRA_RINGER_MODE","public static final String"], ["C","EXTRA_VIBRATE_SETTING","public static final String"], ["C","EXTRA_VIBRATE_TYPE","public static final String"], ["C","FLAG_REMOVE_SOUND_AND_VIBRATE","public static final int"], ["C","FLAG_VIBRATE","public static final int"], ["C","RINGER_MODE_VIBRATE","public static final int"], ["C","VIBRATE_SETTING_CHANGED_ACTION","public static final String"], ["C","VIBRATE_SETTING_OFF","public static final int"], ["C","VIBRATE_SETTING_ON","public static final int"], ["C","VIBRATE_SETTING_ONLY_SILENT","public static final int"], ["C","VIBRATE_TYPE_NOTIFICATION","public static final int"], ["C","VIBRATE_TYPE_RINGER","public static final int"], ["F","getRingerMode()","public int"], ["F","getVibrateSetting(int)","public int"], ["F","setRingerMode(int)","public void"], ["F","setVibrateSetting(int, int)","public void"], ["F","shouldVibrate(int)","public boolean"], ], }, "GLOBAL_SEARCH" : { "android.app.SearchManager" : [ ["C","EXTRA_SELECT_QUERY","public static final String"], ["C","INTENT_ACTION_GLOBAL_SEARCH","public static final String"], ], }, "BROADCAST_STICKY" : { "android.content.Context" : [ ["F","removeStickyBroadcast(android.content.Intent)","public abstract void"], ["F","sendStickyBroadcast(android.content.Intent)","public abstract void"], ], "android.content.ContextWrapper" : [ ["F","removeStickyBroadcast(android.content.Intent)","public void"], ["F","sendStickyBroadcast(android.content.Intent)","public void"], ], }, "KILL_BACKGROUND_PROCESSES" : { "android.app.ActivityManager" : [ ["F","killBackgroundProcesses(java.lang.String)","public void"], ], }, "SET_TIME_ZONE" : { "android.app.AlarmManager" : [ ["F","setTimeZone(java.lang.String)","public void"], ], }, "BLUETOOTH_ADMIN" : { "android.bluetooth.BluetoothAdapter" : [ ["F","cancelDiscovery()","public boolean"], ["F","disable()","public boolean"], ["F","enable()","public boolean"], ["F","setName(java.lang.String)","public boolean"], ["F","startDiscovery()","public boolean"], ], }, "CAMERA" : { "android.hardware.Camera.ErrorCallback" : [ ["F","onError(int, android.hardware.Camera)","public abstract void"], ], "android.view.KeyEvent" : [ ["C","KEYCODE_CAMERA","public static final int"], ], "android.bluetooth.BluetoothClass.Device" : [ ["C","AUDIO_VIDEO_VIDEO_CAMERA","public static final int"], ], "android.provider.MediaStore" : [ ["C","INTENT_ACTION_STILL_IMAGE_CAMERA","public static final String"], ["C","INTENT_ACTION_VIDEO_CAMERA","public static final String"], ], "android.hardware.Camera.CameraInfo" : [ ["C","CAMERA_FACING_BACK","public static final int"], ["C","CAMERA_FACING_FRONT","public static final int"], ["C","facing","public int"], ], "android.provider.ContactsContract.StatusColumns" : [ ["C","CAPABILITY_HAS_CAMERA","public static final int"], ], "android.hardware.Camera.Parameters" : [ ["F","setRotation(int)","public void"], ], "android.media.MediaRecorder.VideoSource" : [ ["C","CAMERA","public static final int"], ], "android.content.Intent" : [ ["C","IntentResolution","public static final String"], ["C","ACTION_CAMERA_BUTTON","public static final String"], ], "android.content.pm.PackageManager" : [ ["C","FEATURE_CAMERA","public static final String"], ["C","FEATURE_CAMERA_AUTOFOCUS","public static final String"], ["C","FEATURE_CAMERA_FLASH","public static final String"], ["C","FEATURE_CAMERA_FRONT","public static final String"], ], "android.hardware.Camera" : [ ["C","CAMERA_ERROR_SERVER_DIED","public static final int"], ["C","CAMERA_ERROR_UNKNOWN","public static final int"], ["F","setDisplayOrientation(int)","public final void"], ], }, "SET_WALLPAPER" : { "android.content.Intent" : [ ["C","IntentResolution","public static final String"], ["C","ACTION_SET_WALLPAPER","public static final String"], ], "android.app.WallpaperManager" : [ ["C","WALLPAPER_PREVIEW_META_DATA","public static final String"], ], }, "WAKE_LOCK" : { "android.net.sip.SipAudioCall" : [ ["F","startAudio()","public void"], ], "android.media.MediaPlayer" : [ ["F","setWakeMode(android.content.Context, int)","public void"], ], "android.os.PowerManager" : [ ["C","ACQUIRE_CAUSES_WAKEUP","public static final int"], ["C","FULL_WAKE_LOCK","public static final int"], ["C","ON_AFTER_RELEASE","public static final int"], ["C","PARTIAL_WAKE_LOCK","public static final int"], ["C","SCREEN_BRIGHT_WAKE_LOCK","public static final int"], ["C","SCREEN_DIM_WAKE_LOCK","public static final int"], ["F","newWakeLock(int, java.lang.String)","public PowerManager.WakeLock"], ], }, "MANAGE_ACCOUNTS" : { "android.accounts.AccountManager" : [ ["F","addAccount(java.lang.String, java.lang.String, java.lang.String[], android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","clearPassword(android.accounts.Account)","public void"], ["F","confirmCredentials(android.accounts.Account, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","editProperties(java.lang.String, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","getAuthTokenByFeatures(java.lang.String, java.lang.String, java.lang.String[], android.app.Activity, android.os.Bundle, android.os.Bundle, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","invalidateAuthToken(java.lang.String, java.lang.String)","public void"], ["F","removeAccount(android.accounts.Account, android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler)","public AccountManagerFuture"], ["F","updateCredentials(android.accounts.Account, java.lang.String, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ], }, "NFC" : { "android.inputmethodservice.InputMethodService" : [ ["C","SoftInputView","public static final int"], ["C","CandidatesView","public static final int"], ["C","FullscreenMode","public static final int"], ["C","GeneratingText","public static final int"], ], "android.nfc.tech.NfcA" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","get(android.nfc.Tag)","public static NfcA"], ["F","transceive(byte[])","public byte[]"], ], "android.nfc.tech.NfcB" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","get(android.nfc.Tag)","public static NfcB"], ["F","transceive(byte[])","public byte[]"], ], "android.nfc.NfcAdapter" : [ ["C","ACTION_TECH_DISCOVERED","public static final String"], ["F","disableForegroundDispatch(android.app.Activity)","public void"], ["F","disableForegroundNdefPush(android.app.Activity)","public void"], ["F","enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])","public void"], ["F","enableForegroundNdefPush(android.app.Activity, android.nfc.NdefMessage)","public void"], ["F","getDefaultAdapter()","public static NfcAdapter"], ["F","getDefaultAdapter(android.content.Context)","public static NfcAdapter"], ["F","isEnabled()","public boolean"], ], "android.nfc.tech.NfcF" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","get(android.nfc.Tag)","public static NfcF"], ["F","transceive(byte[])","public byte[]"], ], "android.nfc.tech.NdefFormatable" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","format(android.nfc.NdefMessage)","public void"], ["F","formatReadOnly(android.nfc.NdefMessage)","public void"], ], "android.app.Activity" : [ ["C","Fragments","public static final int"], ["C","ActivityLifecycle","public static final int"], ["C","ConfigurationChanges","public static final int"], ["C","StartingActivities","public static final int"], ["C","SavingPersistentState","public static final int"], ["C","Permissions","public static final int"], ["C","ProcessLifecycle","public static final int"], ], "android.nfc.tech.MifareClassic" : [ ["C","KEY_NFC_FORUM","public static final byte[]"], ["F","authenticateSectorWithKeyA(int, byte[])","public boolean"], ["F","authenticateSectorWithKeyB(int, byte[])","public boolean"], ["F","close()","public void"], ["F","connect()","public void"], ["F","decrement(int, int)","public void"], ["F","increment(int, int)","public void"], ["F","readBlock(int)","public byte[]"], ["F","restore(int)","public void"], ["F","transceive(byte[])","public byte[]"], ["F","transfer(int)","public void"], ["F","writeBlock(int, byte[])","public void"], ], "android.nfc.Tag" : [ ["F","getTechList()","public String[]"], ], "android.app.Service" : [ ["C","WhatIsAService","public static final int"], ["C","ServiceLifecycle","public static final int"], ["C","Permissions","public static final int"], ["C","ProcessLifecycle","public static final int"], ["C","LocalServiceSample","public static final int"], ["C","RemoteMessengerServiceSample","public static final int"], ], "android.nfc.NfcManager" : [ ["F","getDefaultAdapter()","public NfcAdapter"], ], "android.nfc.tech.MifareUltralight" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","readPages(int)","public byte[]"], ["F","transceive(byte[])","public byte[]"], ["F","writePage(int, byte[])","public void"], ], "android.nfc.tech.NfcV" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","get(android.nfc.Tag)","public static NfcV"], ["F","transceive(byte[])","public byte[]"], ], "android.nfc.tech.TagTechnology" : [ ["F","close()","public abstract void"], ["F","connect()","public abstract void"], ], "android.preference.PreferenceActivity" : [ ["C","SampleCode","public static final String"], ], "android.content.pm.PackageManager" : [ ["C","FEATURE_NFC","public static final String"], ], "android.content.Context" : [ ["C","NFC_SERVICE","public static final String"], ], "android.nfc.tech.Ndef" : [ ["C","NFC_FORUM_TYPE_1","public static final String"], ["C","NFC_FORUM_TYPE_2","public static final String"], ["C","NFC_FORUM_TYPE_3","public static final String"], ["C","NFC_FORUM_TYPE_4","public static final String"], ["F","close()","public void"], ["F","connect()","public void"], ["F","getType()","public String"], ["F","isWritable()","public boolean"], ["F","makeReadOnly()","public boolean"], ["F","writeNdefMessage(android.nfc.NdefMessage)","public void"], ], "android.nfc.tech.IsoDep" : [ ["F","close()","public void"], ["F","connect()","public void"], ["F","setTimeout(int)","public void"], ["F","transceive(byte[])","public byte[]"], ], }, "ACCESS_FINE_LOCATION" : { "android.telephony.TelephonyManager" : [ ["F","getCellLocation()","public CellLocation"], ], "android.location.LocationManager" : [ ["C","GPS_PROVIDER","public static final String"], ["C","NETWORK_PROVIDER","public static final String"], ["C","PASSIVE_PROVIDER","public static final String"], ["F","addGpsStatusListener(android.location.GpsStatus.Listener)","public boolean"], ["F","addNmeaListener(android.location.GpsStatus.NmeaListener)","public boolean"], ], }, "REORDER_TASKS" : { "android.app.ActivityManager" : [ ["F","moveTaskToFront(int, int)","public void"], ], }, "MODIFY_AUDIO_SETTINGS" : { "android.net.sip.SipAudioCall" : [ ["F","setSpeakerMode(boolean)","public void"], ], "android.media.AudioManager" : [ ["F","startBluetoothSco()","public void"], ["F","stopBluetoothSco()","public void"], ], }, "READ_PHONE_STATE" : { "android.telephony.TelephonyManager" : [ ["C","ACTION_PHONE_STATE_CHANGED","public static final String"], ["F","getDeviceId()","public String"], ["F","getDeviceSoftwareVersion()","public String"], ["F","getLine1Number()","public String"], ["F","getSimSerialNumber()","public String"], ["F","getSubscriberId()","public String"], ["F","getVoiceMailAlphaTag()","public String"], ["F","getVoiceMailNumber()","public String"], ], "android.telephony.PhoneStateListener" : [ ["C","LISTEN_CALL_FORWARDING_INDICATOR","public static final int"], ["C","LISTEN_CALL_STATE","public static final int"], ["C","LISTEN_DATA_ACTIVITY","public static final int"], ["C","LISTEN_MESSAGE_WAITING_INDICATOR","public static final int"], ["C","LISTEN_SIGNAL_STRENGTH","public static final int"], ], "android.os.Build.VERSION_CODES" : [ ["C","DONUT","public static final int"], ], }, "BIND_WALLPAPER" : { "android.service.wallpaper.WallpaperService" : [ ["C","SERVICE_INTERFACE","public static final String"], ], }, "DUMP" : { "android.os.Debug" : [ ["F","dumpService(java.lang.String, java.io.FileDescriptor, java.lang.String[])","public static boolean"], ], "android.os.IBinder" : [ ["C","DUMP_TRANSACTION","public static final int"], ], }, "USE_CREDENTIALS" : { "android.accounts.AccountManager" : [ ["F","blockingGetAuthToken(android.accounts.Account, java.lang.String, boolean)","public String"], ["F","getAuthToken(android.accounts.Account, java.lang.String, android.os.Bundle, android.app.Activity, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","getAuthToken(android.accounts.Account, java.lang.String, boolean, android.accounts.AccountManagerCallback<android.os.Bundle>, android.os.Handler)","public AccountManagerFuture"], ["F","invalidateAuthToken(java.lang.String, java.lang.String)","public void"], ], }, "ACCESS_COARSE_LOCATION" : { "android.telephony.TelephonyManager" : [ ["F","getCellLocation()","public CellLocation"], ], "android.telephony.PhoneStateListener" : [ ["C","LISTEN_CELL_LOCATION","public static final int"], ], "android.location.LocationManager" : [ ["C","NETWORK_PROVIDER","public static final String"], ], }, "RECEIVE_BOOT_COMPLETED" : { "android.content.Intent" : [ ["C","ACTION_BOOT_COMPLETED","public static final String"], ], }, "SET_ALARM" : { "android.provider.AlarmClock" : [ ["C","ACTION_SET_ALARM","public static final String"], ["C","EXTRA_HOUR","public static final String"], ["C","EXTRA_MESSAGE","public static final String"], ["C","EXTRA_MINUTES","public static final String"], ["C","EXTRA_SKIP_UI","public static final String"], ], }, "PROCESS_OUTGOING_CALLS" : { "android.content.Intent" : [ ["C","ACTION_NEW_OUTGOING_CALL","public static final String"], ], }, "GET_TASKS" : { "android.app.ActivityManager" : [ ["F","getRecentTasks(int, int)","public List"], ["F","getRunningTasks(int)","public List"], ], }, "SET_TIME" : { "android.app.AlarmManager" : [ ["F","setTime(long)","public void"], ["F","setTimeZone(java.lang.String)","public void"], ], }, "ACCESS_WIFI_STATE" : { "android.net.sip.SipAudioCall" : [ ["F","startAudio()","public void"], ], }, "READ_HISTORY_BOOKMARKS" : { "android.provider.Browser" : [ ["C","BOOKMARKS_URI","public static final Uri"], ["C","SEARCHES_URI","public static final Uri"], ["F","addSearchUrl(android.content.ContentResolver, java.lang.String)","public static final void"], ["F","canClearHistory(android.content.ContentResolver)","public static final boolean"], ["F","getAllBookmarks(android.content.ContentResolver)","public static final Cursor"], ["F","getAllVisitedUrls(android.content.ContentResolver)","public static final Cursor"], ["F","requestAllIcons(android.content.ContentResolver, java.lang.String, android.webkit.WebIconDatabase.IconListener)","public static final void"], ["F","truncateHistory(android.content.ContentResolver)","public static final void"], ["F","updateVisitedHistory(android.content.ContentResolver, java.lang.String, boolean)","public static final void"], ], }, "STATUS_BAR" : { "android.view.View.OnSystemUiVisibilityChangeListener" : [ ["F","onSystemUiVisibilityChange(int)","public abstract void"], ], "android.view.View" : [ ["C","STATUS_BAR_HIDDEN","public static final int"], ["C","STATUS_BAR_VISIBLE","public static final int"], ], "android.view.WindowManager.LayoutParams" : [ ["C","TYPE_STATUS_BAR","public static final int"], ["C","TYPE_STATUS_BAR_PANEL","public static final int"], ["C","systemUiVisibility","public int"], ["C","type","public int"], ], }, "READ_LOGS" : { "android.os.DropBoxManager" : [ ["C","ACTION_DROPBOX_ENTRY_ADDED","public static final String"], ["F","getNextEntry(java.lang.String, long)","public DropBoxManager.Entry"], ], }, "BLUETOOTH" : { "android.os.Process" : [ ["C","BLUETOOTH_GID","public static final int"], ], "android.content.pm.PackageManager" : [ ["C","FEATURE_BLUETOOTH","public static final String"], ], "android.media.AudioManager" : [ ["C","ROUTE_BLUETOOTH","public static final int"], ["C","ROUTE_BLUETOOTH_A2DP","public static final int"], ["C","ROUTE_BLUETOOTH_SCO","public static final int"], ], "android.provider.Settings.System" : [ ["C","AIRPLANE_MODE_RADIOS","public static final String"], ["C","BLUETOOTH_DISCOVERABILITY","public static final String"], ["C","BLUETOOTH_DISCOVERABILITY_TIMEOUT","public static final String"], ["C","BLUETOOTH_ON","public static final String"], ["C","RADIO_BLUETOOTH","public static final String"], ["C","VOLUME_BLUETOOTH_SCO","public static final String"], ], "android.provider.Settings" : [ ["C","ACTION_BLUETOOTH_SETTINGS","public static final String"], ], "android.bluetooth.BluetoothAdapter" : [ ["C","ACTION_CONNECTION_STATE_CHANGED","public static final String"], ["C","ACTION_DISCOVERY_FINISHED","public static final String"], ["C","ACTION_DISCOVERY_STARTED","public static final String"], ["C","ACTION_LOCAL_NAME_CHANGED","public static final String"], ["C","ACTION_REQUEST_DISCOVERABLE","public static final String"], ["C","ACTION_REQUEST_ENABLE","public static final String"], ["C","ACTION_SCAN_MODE_CHANGED","public static final String"], ["C","ACTION_STATE_CHANGED","public static final String"], ["F","cancelDiscovery()","public boolean"], ["F","disable()","public boolean"], ["F","enable()","public boolean"], ["F","getAddress()","public String"], ["F","getBondedDevices()","public Set"], ["F","getName()","public String"], ["F","getScanMode()","public int"], ["F","getState()","public int"], ["F","isDiscovering()","public boolean"], ["F","isEnabled()","public boolean"], ["F","listenUsingInsecureRfcommWithServiceRecord(java.lang.String, java.util.UUID)","public BluetoothServerSocket"], ["F","listenUsingRfcommWithServiceRecord(java.lang.String, java.util.UUID)","public BluetoothServerSocket"], ["F","setName(java.lang.String)","public boolean"], ["F","startDiscovery()","public boolean"], ], "android.bluetooth.BluetoothProfile" : [ ["F","getConnectedDevices()","public abstract List"], ["F","getConnectionState(android.bluetooth.BluetoothDevice)","public abstract int"], ["F","getDevicesMatchingConnectionStates(int[])","public abstract List"], ], "android.bluetooth.BluetoothHeadset" : [ ["C","ACTION_AUDIO_STATE_CHANGED","public static final String"], ["C","ACTION_CONNECTION_STATE_CHANGED","public static final String"], ["C","ACTION_VENDOR_SPECIFIC_HEADSET_EVENT","public static final String"], ["F","getConnectedDevices()","public List"], ["F","getConnectionState(android.bluetooth.BluetoothDevice)","public int"], ["F","getDevicesMatchingConnectionStates(int[])","public List"], ["F","isAudioConnected(android.bluetooth.BluetoothDevice)","public boolean"], ["F","startVoiceRecognition(android.bluetooth.BluetoothDevice)","public boolean"], ["F","stopVoiceRecognition(android.bluetooth.BluetoothDevice)","public boolean"], ], "android.bluetooth.BluetoothDevice" : [ ["C","ACTION_ACL_CONNECTED","public static final String"], ["C","ACTION_ACL_DISCONNECTED","public static final String"], ["C","ACTION_ACL_DISCONNECT_REQUESTED","public static final String"], ["C","ACTION_BOND_STATE_CHANGED","public static final String"], ["C","ACTION_CLASS_CHANGED","public static final String"], ["C","ACTION_FOUND","public static final String"], ["C","ACTION_NAME_CHANGED","public static final String"], ["F","createInsecureRfcommSocketToServiceRecord(java.util.UUID)","public BluetoothSocket"], ["F","createRfcommSocketToServiceRecord(java.util.UUID)","public BluetoothSocket"], ["F","getBluetoothClass()","public BluetoothClass"], ["F","getBondState()","public int"], ["F","getName()","public String"], ], "android.provider.Settings.Secure" : [ ["C","BLUETOOTH_ON","public static final String"], ], "android.bluetooth.BluetoothA2dp" : [ ["C","ACTION_CONNECTION_STATE_CHANGED","public static final String"], ["C","ACTION_PLAYING_STATE_CHANGED","public static final String"], ["F","getConnectedDevices()","public List"], ["F","getConnectionState(android.bluetooth.BluetoothDevice)","public int"], ["F","getDevicesMatchingConnectionStates(int[])","public List"], ["F","isA2dpPlaying(android.bluetooth.BluetoothDevice)","public boolean"], ], "android.bluetooth.BluetoothAssignedNumbers" : [ ["C","BLUETOOTH_SIG","public static final int"], ], }, "WRITE_HISTORY_BOOKMARKS" : { "android.provider.Browser" : [ ["C","BOOKMARKS_URI","public static final Uri"], ["C","SEARCHES_URI","public static final Uri"], ["F","addSearchUrl(android.content.ContentResolver, java.lang.String)","public static final void"], ["F","clearHistory(android.content.ContentResolver)","public static final void"], ["F","clearSearches(android.content.ContentResolver)","public static final void"], ["F","deleteFromHistory(android.content.ContentResolver, java.lang.String)","public static final void"], ["F","deleteHistoryTimeFrame(android.content.ContentResolver, long, long)","public static final void"], ["F","truncateHistory(android.content.ContentResolver)","public static final void"], ["F","updateVisitedHistory(android.content.ContentResolver, java.lang.String, boolean)","public static final void"], ], }, "ACCOUNT_MANAGER" : { "android.accounts.AccountManager" : [ ["C","KEY_ACCOUNT_MANAGER_RESPONSE","public static final String"], ], }, "GET_ACCOUNTS" : { "android.accounts.AccountManager" : [ ["F","getAccounts()","public Account[]"], ["F","getAccountsByType(java.lang.String)","public Account[]"], ["F","getAccountsByTypeAndFeatures(java.lang.String, java.lang.String[], android.accounts.AccountManagerCallback<android.accounts.Account[]>, android.os.Handler)","public AccountManagerFuture"], ["F","hasFeatures(android.accounts.Account, java.lang.String[], android.accounts.AccountManagerCallback<java.lang.Boolean>, android.os.Handler)","public AccountManagerFuture"], ], }, "WRITE_EXTERNAL_STORAGE" : { "android.os.Build.VERSION_CODES" : [ ["C","DONUT","public static final int"], ], "android.app.DownloadManager.Request" : [ ["F","setDestinationUri(android.net.Uri)","public DownloadManager.Request"], ], }, "REBOOT" : { "android.os.RecoverySystem" : [ ["F","installPackage(android.content.Context, java.io.File)","public static void"], ["F","rebootWipeUserData(android.content.Context)","public static void"], ], "android.content.Intent" : [ ["C","IntentResolution","public static final String"], ["C","ACTION_REBOOT","public static final String"], ], "android.os.PowerManager" : [ ["F","reboot(java.lang.String)","public void"], ], }, }
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2010, Anthony Desnos <desnos at t0t0.org> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import os, sys, re, string from dvm_permissions_unformatted import PERMISSIONS from permissions_by_hand import PERMISSIONS_BY_HAND BASIC_TYPES = { "byte" : "B", "char" : "C", "double" : "D", "float" : "F", "int" : "I", "long" : "J", "short" : "S", "boolean" : "B", "void" : "V", } ADVANCED_TYPES = { "String" : "Ljava/lang/String;", "List" : "Ljava/util/List;", "AccountManagerFuture" : "Landroid/accounts/AccountManagerFuture;", "CellLocation" : "Landroid/telephony/CellLocation;", "Uri" : "Landroid/net/Uri;", "Cursor" : "Landroid/database/Cursor;", "Set" : "Ljava/util/Set;", "BluetoothServerSocket" : "Landroid/bluetooth/BluetoothServerSocket;", "BluetoothSocket" : "Landroid/bluetooth/BluetoothSocket;", "DownloadManager.Request" : "Landroid/app/DownloadManager/Request;", "PendingIntent" : "Landroid/app/PendingIntent;", "SmsManager" : "Landroid/telephony/SmsManager;", "Bitmap" : "Landroid/graphics/Bitmap;", "IBinder" : "Landroid/os/IBinder;", } def translateDescParams( desc_params ) : desc_params = desc_params.replace(" ", "") buff = "" for elem in desc_params.split(",") : if elem != "" : tab = "" if "[" in elem : tab = "[" * string.count(elem, "[") elem = elem[ : tab.find("[") - 2 ] if elem not in BASIC_TYPES : if elem in ADVANCED_TYPES : buff += tab + ADVANCED_TYPES[ elem ] + " " else : buff += tab + "L" + elem.replace(".", "/") + "; " else : buff += tab + BASIC_TYPES[ elem ] + " " buff = buff[:-1] return buff def translateDescReturn( desc_return ) : buff = "" for elem in desc_return.split(" ") : tab = "" if "[" in elem : tab = "[" * string.count(elem, "[") elem = elem[ : tab.find("[") - 2 ] if elem in BASIC_TYPES : buff += tab + BASIC_TYPES[ elem ] + " " else : if elem in ADVANCED_TYPES : buff += tab + ADVANCED_TYPES[ elem ] + " " else : if "." in elem : buff += tab + "L" + elem.replace(".", "/") + "; " buff = buff[:-1] return buff def translateToCLASS( desc_params, desc_return ) : print desc_params, desc_return, buff = "(" + translateDescParams( desc_params[ desc_params.find("(") + 1 : -1 ] ) + ")" + translateDescReturn( desc_return ) print "----->", buff return [ desc_params[ : desc_params.find("(") ], buff ] def translateToCLASS2( constant_name, desc_return ): return [ constant_name, translateDescReturn( desc_return ) ] PERMISSIONS.update( PERMISSIONS_BY_HAND ) for perm in PERMISSIONS : for package in PERMISSIONS[perm] : for element in PERMISSIONS[perm][package] : if element[0] == "F" : element.extend( translateToCLASS( element[1], element[2] ) ) elif element[0] == "C" : element.extend( translateToCLASS2( element[1], element[2] ) ) fd = open("./core/bytecodes/api_permissions.py", "w") fd.write("DVM_PERMISSIONS_BY_PERMISSION = {\n") for perm in PERMISSIONS : fd.write("\"%s\" : {\n" % perm) for package in PERMISSIONS[perm] : fd.write("\t\"L%s;\" : [\n" % package.replace(".", "/")) for element in PERMISSIONS[perm][package] : fd.write("\t\t(\"%s\", \"%s\", \"%s\"),\n" % (element[0], element[-2], element[-1]) ) fd.write("\t],\n") fd.write("},\n") fd.write("}\n\n") fd.write("DVM_PERMISSIONS_BY_ELEMENT = { \n") for perm in PERMISSIONS : for package in PERMISSIONS[perm] : for element in PERMISSIONS[perm][package] : fd.write("\t\"L%s;-%s-%s\" : \"%s\",\n" % (package.replace(".", "/"), element[-2], element[-1], perm)) fd.write("}\n") fd.close()
Python
#!/usr/bin/env python import sys, hashlib PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.androgen import AndroguardS from androguard.core.analysis import analysis #TEST = 'examples/java/test/orig/Test1.class' #TEST = 'examples/java/Demo1/orig/DES.class' #TEST = 'examples/java/Demo1/orig/Util.class' TEST = 'examples/android/TestsAndroguard/bin/classes.dex' #TEST = 'examples/android/Hello_Kitty/classes.dex' a = AndroguardS( TEST ) x = analysis.VMAnalysis( a.get_vm() ) # CFG for method in a.get_methods() : g = x.hmethods[ method ] # Display only methods with exceptions if method.get_code().tries_size.get_value() <= 0 : continue print method.get_class_name(), method.get_name(), method.get_descriptor(), method.get_code().get_length(), method.get_code().registers_size.get_value() idx = 0 for i in g.basic_blocks.get() : print "\t %s %x %x" % (i.name, i.start, i.end), i.ins[-1].get_name(), '[ CHILDS = ', ', '.join( "%x-%x-%s" % (j[0], j[1], j[2].get_name()) for j in i.childs ), ']', '[ FATHERS = ', ', '.join( j[2].get_name() for j in i.fathers ), ']', i.free_blocks_offsets for ins in i.get_ins() : print "\t\t %x" % idx, ins.get_name(), ins.get_output() idx += ins.get_length() print "" for i in g.exceptions.gets() : print '%x %x %s' % (i.start, i.end, i.exceptions)
Python
#!/usr/bin/env python import sys, os import cProfile # http://code.activestate.com/recipes/286222-memory-usage/ _proc_status = '/proc/%d/status' % os.getpid() _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, 'KB': 1024.0, 'MB': 1024.0*1024.0} def _VmB(VmKey): global _proc_status, _scale # get pseudo file /proc/<pid>/status try: t = open(_proc_status) v = t.read() t.close() except: return 0.0 # non-Linux? # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' i = v.index(VmKey) v = v[i:].split(None, 3) # whitespace if len(v) < 3: return 0.0 # invalid format? # convert Vm value to bytes return float(v[1]) * _scale[v[2]] def memory(since=0.0): '''Return memory usage in bytes. ''' return _VmB('VmSize:') - since def resident(since=0.0): '''Return resident memory usage in bytes. ''' return _VmB('VmRSS:') - since def stacksize(since=0.0): '''Return stack size in bytes. ''' return _VmB('VmStk:') - since PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "./") import androguard, analysis # a directory with apks files" TEST = "./apks/" l = [] for i in os.walk( TEST ) : for j in i[2] : l.append( i[0] + j ) print len(l), l _a = androguard.Androguard( l ) print "MEMORY : ", memory() / _scale["MB"], "RESIDENT ", resident() / _scale["MB"], "STACKSIZE ", stacksize() / _scale["MB"]
Python
#!/usr/bin/env python import sys, random, string PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "/core") sys.path.append(PATH_INSTALL + "/core/bytecodes") import jvm TEST = "./examples/java/test/orig/Test1.class" TEST_REF = "./examples/java/Hello.class" TEST_OUTPUT = "./examples/java/test/new/Test1.class" j = jvm.JVMFormat( open(TEST).read() ) j2 = jvm.JVMFormat( open(TEST_REF).read() ) # Insert a method with java dependances methods/class j.insert_direct_method( "toto2", j2.get_method("test5")[0] ) # SAVE CLASS fd = open( TEST_OUTPUT, "w" ) fd.write( j.save() ) fd.close()
Python
#!/usr/bin/env python import sys PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "./") from androguard.core.androgen import AndroguardS TEST = [ './examples/java/Hello.class' ] _a = AndroguardS( TEST[0] ) _a.show() for field in _a.gets("fields") : print field.get_name(), field.get_descriptor() for method in _a.get("method", "test") : print method.get_name(), method.get_descriptor() method, _ =_a.get_method_descriptor("Hello", "test", "([B)[B") print method.get_name() for method in _a.gets("methods") : print method.get_name()
Python
#!/usr/bin/env python import hashlib import sys PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "./") from androguard.core.androgen import Androguard def hexdump(src, length=8, off=0): result = [] digits = 4 if isinstance(src, unicode) else 2 for i in xrange(0, len(src), length): s = src[i:i+length] hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s]) text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s]) result.append( b"%04X %-*s %s" % (i+off, length*(digits + 1), hexa, text) ) return b'\n'.join(result) TEST_TYPE = 0 TYPE_JVM = 1 TYPE_DVM = 2 if len(sys.argv) == 1 : TEST_TYPE = TYPE_JVM + TYPE_DVM elif len(sys.argv) == 2 : if sys.argv[1] == "JVM" : TEST_TYPE = TYPE_JVM elif sys.argv[1] == "DVM" : TEST_TYPE = TYPE_DVM TEST = [] ### JAVA TEST ### BASE_TEST = "./examples/java/Demo1/orig/" BASE_MAIN_TEST = "./examples/java/Demo1/orig_main/" FILES = [ ("BaseCipher.class", 0), ("DES.class", 0), ("DES$Context.class", 0), ("IBlockCipher.class", 0), ("IBlockCipherSpi.class", 0), ("Properties$1.class", 0), ("Properties.class", 0), ("Registry.class", 0), ("Util.class", 0), ("WeakKeyException.class", 0), ("Demo1Main.class", 1) ] if TEST_TYPE & TYPE_JVM : TEST.append( "./examples/java/test/orig/Test1.class" ) #for i in FILES : # if i[1] == 0 : # TEST.append( BASE_TEST + i[0] ) #else : # TEST.append( BASE_MAIN_TEST + i[0] ) ### DALVIK TEST ### FILES = [ "examples/android/Demo1/bin/classes.dex", "examples/dalvik/test/bin/classes.dex" ] if TEST_TYPE & TYPE_DVM : for i in FILES : TEST.append( i ) ### ALL ### print TEST a = Androguard( TEST ) i = 0 while i < len(TEST) : b1 = open(TEST[i]).read() _a = a.get("file", TEST[i]) b2 = _a.save() if hashlib.md5( b1 ).hexdigest() != hashlib.md5( b2 ).hexdigest() : print "HASH %s NO GO" % TEST[i] j = 0 end = max(len(b1), len(b2)) while j < end : if j >= len(b1) : print "OUT OF B1 @ OFFSET 0x%x(%d)" % (j,j) break if j >= len(b2) : print "OUT OF B2 @ OFFSET 0x%x(%d)" % (j,j) break if b1[j] != b2[j] : print "BEGIN @ OFFSET 0x%x" % j print "ORIG : " print hexdump(b1[j - 2: j + 10], off=j-2) + "\n" print "NEW : " print hexdump(b2[j - 2: j + 10], off=j-2) + "\n" j += 1 else : print "HASH %s GO" % TEST[i] i += 1
Python
#!/usr/bin/env python import sys, random, string PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "/core") sys.path.append(PATH_INSTALL + "/core/bytecodes") import jvm TEST = "./examples/java/test/orig/Test1.class" TEST_REF = "./examples/java/Hello.class" TEST_OUTPUT = "./examples/java/test/new/Test1.class" j = jvm.JVMFormat( open(TEST).read() ) j2 = jvm.JVMFormat( open(TEST_REF).read() ) # Insert a craft method :) j.insert_craft_method( "toto", [ "ACC_PUBLIC", "[B", "[B" ], [ [ "aconst_null" ], [ "areturn" ] ] ) # Insert a method with no dependances methods j.insert_direct_method( "toto2", j2.get_method("test3")[0] ) # SAVE CLASS fd = open( TEST_OUTPUT, "w" ) fd.write( j.save() ) fd.close()
Python
#!/usr/bin/env python import sys import hashlib import pyDes PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "./") sys.path.append(PATH_INSTALL + "/core") sys.path.append(PATH_INSTALL + "/core/bytecodes") sys.path.append(PATH_INSTALL + "/core/analysis") from androguard import * import analysis TEST = "./geinimi/geinimi.apk" _a = AndroguardS( TEST ) _x = analysis.VMAnalysis( _a.get_vm() ) #print _a.get_strings() KEY = "\x01\x02\x03\x04\x05\x06\x07\x08" _des = pyDes.des( KEY ) #_x.tainted_packages.export_call_graph("toto.dot", "Lcom/swampy/sexpos/pos") tainted_string = _x.tainted_variables.get_string( "DES" ) if tainted_string != None : print "\t -->", tainted_string.get_info() for path in tainted_string.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % ( path.get_bb().start + path.get_idx() ) tainted_field = _x.tainted_variables.get_field( "Lcom/swampy/sexpos/pos/e/k;", "b", "[B" ) if tainted_field != None : print "\t -->", tainted_field.get_info() for path in tainted_field.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) tainted_field = _x.tainted_variables.get_field( "Lcom/swampy/sexpos/pos/e/p;", "a", "[[B" ) if tainted_field != None : print "\t -->", tainted_field.get_info() for path in tainted_field.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) if path.get_access_flag() == "W" : b = "" for ins in path.get_method().get_code().get_bc().get() : if ins.get_name() == "FILL-ARRAY-DATA" : b += ins.get_data() print repr( _des.decrypt( b ) ) tainted_field = _x.tainted_variables.get_field( "Lcom/swampy/sexpos/pos/a;", "g", "Ljava/lang/String;" ) if tainted_field != None : print "\t -->", tainted_field.get_info() for path in tainted_field.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) tainted_method = _x.tainted_packages.get_method( "Lcom/swampy/sexpos/pos/e/q;", "a", "(Ljava/lang/String;)Ljava/lang/String;" ) for path in tainted_method : print path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() )
Python
#!/usr/bin/env python import sys, hashlib PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "./") from androguard.core.androgen import AndroguardS from androguard.core.analysis import analysis OUTPUT = "./output/" #TEST = 'examples/java/test/orig/Test1.class' #TEST = 'examples/java/Demo1/orig/DES.class' #TEST = 'examples/java/Demo1/orig/Util.class' #TEST = "apks/DroidDream/tmp/classes.dex" TEST = "./examples/android/TCDiff/bin/classes.dex" #TEST = "apks/iCalendar.apk" #TEST = "apks/adrd/5/8370959.dex" def display_CFG(a, x, classes) : for method in a.get_methods() : g = x.get_method( method ) print method.get_class_name(), method.get_name(), method.get_descriptor() for i in g.basic_blocks.get() : print "\t %s %x %x" % (i.name, i.start, i.end), i.ins[-1].get_name(), '[ CHILDS = ', ', '.join( "%x-%x-%s" % (j[0], j[1], j[2].get_name()) for j in i.childs ), ']', '[ FATHERS = ', ', '.join( j[2].get_name() for j in i.fathers ), ']', i.free_blocks_offsets def display_STRINGS(a, x, classes) : print "STRINGS" for s, _ in x.tainted_variables.get_strings() : print "String : ", repr(s.get_info()) for path in s.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) def display_FIELDS(a, x, classes) : print "FIELDS" for f, _ in x.tainted_variables.get_fields() : print "field : ", repr(f.get_info()) for path in f.get_paths() : print "\t\t =>", path.get_access_flag(), path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) def display_PACKAGES(a, x, classes) : print "CREATED PACKAGES" for m, _ in x.tainted_packages.get_packages() : print "package : ", repr(m.get_info()) for path in m.get_paths() : if path.get_access_flag() == analysis.TAINTED_PACKAGE_CREATE : print "\t\t =>", path.get_method().get_class_name(), path.get_method().get_name(), path.get_method().get_descriptor(), path.get_bb().get_name(), "%x" % (path.get_bb().start + path.get_idx() ) def display_PACKAGES_II(a, x, classes) : # Internal Methods -> Internal Methods print "Internal --> Internal" for j in x.tainted_packages.get_internal_packages() : print "\t %s %s %s %x ---> %s %s %s" % (j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor(), \ j.get_bb().start + j.get_idx(), \ j.get_class_name(), j.get_name(), j.get_descriptor()) def display_PACKAGES_IE(a, x, classes) : # Internal Methods -> External Methods print "Internal --> External" for j in x.tainted_packages.get_external_packages() : print "\t %s %s %s %x ---> %s %s %s" % (j.get_method().get_class_name(), j.get_method().get_name(), j.get_method().get_descriptor(), \ j.get_bb().start + j.get_idx(), \ j.get_class_name(), j.get_name(), j.get_descriptor()) def display_SEARCH_PACKAGES(a, x, classes, package_name) : print "Search package", package_name analysis.show_Path( x.tainted_packages.search_packages( package_name ) ) def display_SEARCH_METHODS(a, x, classes, package_name, method_name, descriptor) : print "Search method", package_name, method_name, descriptor analysis.show_Path( x.tainted_packages.search_methods( package_name, method_name, descriptor) ) def display_PERMISSION(a, x, classes) : # Show methods used by permission perms_access = x.tainted_packages.get_permissions( [] ) for perm in perms_access : print "PERM : ", perm analysis.show_PathP( perms_access[ perm ] ) def display_OBJECT_CREATED(a, x, class_name) : print "Search object", class_name analysis.show_Path( x.tainted_packages.search_objects( class_name ) ) a = AndroguardS( TEST ) x = analysis.VMAnalysis( a.get_vm(), code_analysis=True ) print a.get_vm().get_strings() print a.get_vm().get_regex_strings( "access" ) print a.get_vm().get_regex_strings( "(long).*2" ) print a.get_vm().get_regex_strings( ".*(t\_t).*" ) classes = a.get_vm().get_classes_names() display_CFG( a, x, classes ) display_PACKAGES( a, x, classes ) display_PACKAGES_IE( a, x, classes ) display_PACKAGES_II( a, x, classes ) display_PERMISSION( a, x, classes ) display_SEARCH_PACKAGES( a, x, classes, "Landroid/telephony/" ) display_SEARCH_PACKAGES( a, x, classes, "Ljavax/crypto/" ) display_SEARCH_METHODS( a, x, classes, "Ljavax/crypto/", "generateSecret", "." ) display_OBJECT_CREATED( a, x, "." )
Python
#!/usr/bin/env python import sys, hashlib PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.androgen import AndroguardS from androguard.core.analysis import analysis #TEST = 'examples/java/test/orig/Test1.class' #TEST = 'examples/java/Demo1/orig/DES.class' #TEST = 'examples/java/Demo1/orig/Util.class' #TEST = 'examples/android/Test/bin/classes.dex' TEST = 'examples/android/TestsAndroguard/bin/classes.dex' #TEST = 'examples/android/TC/bin/classes.dex' #TEST = 'examples/android/Hello_Kitty/classes.dex' a = AndroguardS( TEST ) x = analysis.VMAnalysis( a.get_vm() ) # CFG for method in a.get_methods() : g = x.hmethods[ method ] print method.get_class_name(), method.get_name(), method.get_descriptor(), method.get_code().get_length(), method.get_code().registers_size.get_value() idx = 0 for i in g.basic_blocks.get() : print "\t %s %x %x" % (i.name, i.start, i.end), i.ins[-1].get_name(), '[ CHILDS = ', ', '.join( "%x-%x-%s" % (j[0], j[1], j[2].get_name()) for j in i.childs ), ']', '[ FATHERS = ', ', '.join( j[2].get_name() for j in i.fathers ), ']', i.free_blocks_offsets for ins in i.get_ins() : print "\t\t %x" % idx, ins.get_name(), ins.get_output() idx += ins.get_length() print ""
Python
#!/usr/bin/env python import sys PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.bytecodes import dvm from androguard.core.analysis import analysis TEST = "examples/android/TestsAndroguard/bin/classes.dex" j = dvm.DalvikVMFormat( open(TEST).read() ) x = analysis.VMAnalysis( j ) j.set_vmanalysis( x ) # SHOW CLASSES (verbose and pretty) j.pretty_show() # SHOW METHODS for i in j.get_methods() : i.pretty_show( )
Python
#!/usr/bin/env python # This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Androguard is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Androguard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Androguard. If not, see <http://www.gnu.org/licenses/>. import sys, os PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.binaries import idapipe PATH_IDA = os.path.expanduser("~") + "/ida-6.2/idal" PATH_WRAPPER = "./androguard/core/binaries/idawrapper.py" ip = idapipe.IDAPipe( PATH_IDA, PATH_WRAPPER, "./elsim/examples/x86/elf/polarssl/libpolarssl.so" ) #ip = idapipe.IDAPipe( "/media/truecrypt1/ida/6.2/ida-6.2/idal", "examples/x86/pe/win32k-5.1.2600.6119.sys" ) try : f = ip.get_quick_functions() # print len(f) idapipe.display_function( f[ 15344 ] ) #ip.get_raw() #ip.get_functions() #ip.get_function_name( "aes_gen_tables" ) ip.quit() except : import traceback traceback.print_exc() ip.quit()
Python
#!/usr/bin/env python import sys, random, string PATH_INSTALL = "./" sys.path.append(PATH_INSTALL + "/core") sys.path.append(PATH_INSTALL + "/core/bytecodes") import jvm TEST = "./examples/java/test/orig/Test1.class" TEST_OUTPUT = "./examples/java/test/new/Test1.class" j = jvm.JVMFormat( open(TEST).read() ) # Modify the name of each field for field in j.get_fields() : field.set_name( random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) ) # Modify the name of each method (minus the constructor (<init>) and a extern called method (go)) for method in j.get_methods() : if method.get_name() != "go" and method.get_name() != "<init>" : method.set_name( random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) ) # SAVE CLASS fd = open( TEST_OUTPUT, "w" ) fd.write( j.save() ) fd.close()
Python