code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from django.db import models
from django.contrib.auth.models import User
import nltk
import textutil
import datetime
# make email addresses be 75 characters like usernames
User._meta.get_field_by_name('username')[0].max_length=75
class Receiver(models.Model):
user = models.ForeignKey(User, unique=True)
digest = models.BooleanField(default = False)
recommend = models.BooleanField(default = True)
settings_seed = models.IntegerField(default = 0)
term_vector_dirty = models.BooleanField(default = False)
feed_only = models.BooleanField(default = False)
def tokenize(self):
"""Creates a FreqDist representing all the posts shared
with this person"""
text = u''
posts = []
received_posts = Post.objects.filter( \
sharedpost__sharedpostreceiver__receiver = self)
for received_post in received_posts:
posts.append(textutil.clean_html(received_post.title))
posts.append(textutil.clean_html(received_post.contents))
posts.append(textutil.clean_html(received_post.feed.title))
text = u" ".join(posts)
tokens = nltk.word_tokenize(text)
porter = nltk.PorterStemmer()
stopwords = nltk.corpus.stopwords.words('english')
words = []
for w in tokens:
w = w.lower()
if w not in stopwords and w.isalpha():
words.append(porter.stem(w))
frequency_dist = nltk.FreqDist(words)
return frequency_dist
def __unicode__(self):
return unicode(self.user)
class Sharer(models.Model):
user = models.ForeignKey(User, unique=True)
cc_me = models.BooleanField("CC me on e-mails when I share a post", default = True)
blacklist = models.ManyToManyField(Receiver)
def __unicode__(self):
return self.name()
def name(self):
if self.user.first_name != u'' or self.user.last_name != u'':
return self.user.first_name + u' ' + self.user.last_name
else:
return self.user.email
def get_study_participant(self):
try:
study_participant = StudyParticipant.objects.get(sharer = self)
# check to see if study participant assignment is over
assignment = StudyParticipantAssignment.objects.filter(study_participant = study_participant).order_by('-start_time')[0]
if assignment.end_time < datetime.datetime.now():
study_participant = None
except StudyParticipant.DoesNotExist:
study_participant = None
return study_participant
class Feed(models.Model):
rss_url = models.TextField(unique=True) # the rss feed url
title = models.TextField()
def __unicode__(self):
return self.rss_url;
class Post(models.Model):
url = models.TextField()
feed = models.ForeignKey(Feed)
title = models.TextField()
contents = models.TextField()
def get_term_vector(self):
"Returns a QuerySet term vector for this post"
return TermVectorCell.objects.filter(post=self);
def tokenize(self):
"""Returns a tokenized frequency distribution of the post contents
Each item in the list has [0] = the string, and [1] = the count
"""
text = textutil.clean_html(self.title) + u' ' + \
textutil.clean_html(self.contents) + u' ' + \
textutil.clean_html(self.feed.title)
tokens = nltk.word_tokenize(text)
porter = nltk.PorterStemmer()
stopwords = nltk.corpus.stopwords.words('english')
words = []
for w in tokens:
w = w.lower()
if w not in stopwords and w.isalpha():
words.append(porter.stem(w))
frequency_dist = nltk.FreqDist(words)
return frequency_dist
def __unicode__(self):
return self.title + ": " + self.url;
class Meta:
unique_together = ("url", "feed")
class SharedPost(models.Model):
post = models.ForeignKey(Post)
sharer = models.ForeignKey(Sharer)
comment = models.TextField()
bookmarklet = models.BooleanField(default = False)
client = models.TextField(default = "greader")
thanks = models.IntegerField(default = 0)
clickthroughs = models.IntegerField(default = 0)
referrer = models.TextField()
def __unicode__(self):
return unicode(self.sharer) + u' post: ' + unicode(self.post);
class SharedPostReceiver(models.Model):
shared_post = models.ForeignKey(SharedPost)
receiver = models.ForeignKey(Receiver)
time = models.DateTimeField(auto_now_add=True)
sent = models.BooleanField(default = False)
digest = models.BooleanField(default = False)
def __unicode__(self):
return u'receiver: ' + unicode(self.receiver) + u' sender: ' + unicode(self.shared_post);
class Term(models.Model):
term = models.CharField(max_length=255, unique=True)
def __unicode__(self):
return unicode(self.term);
class TermVectorCell(models.Model):
term = models.ForeignKey(Term)
count = models.FloatField()
receiver = models.ForeignKey('Receiver')
def __unicode__(self):
return unicode(self.term) + u': ' + unicode(self.count);
# For Logging
class ViewedPost(models.Model):
post = models.ForeignKey(Post)
sharer = models.ForeignKey(Sharer)
time = models.DateTimeField(auto_now_add=True)
expanded_view = models.BooleanField()
link_clickthrough = models.BooleanField(default = False)
class ViewedPostRecommendation(models.Model):
receiver = models.ForeignKey(Receiver)
viewed_post = models.ForeignKey(ViewedPost)
cosine_distance = models.FloatField()
recommendation_order = models.IntegerField()
class LoggedIn(models.Model):
sharer = models.ForeignKey(Sharer)
time = models.DateTimeField(auto_now_add=True)
class StudyParticipant(models.Model):
sharer = models.ForeignKey(Sharer, unique=True)
user_interface = models.BooleanField()
social_features = models.BooleanField()
study_group = models.CharField(max_length = 20)
def __unicode__(self):
return self.sharer.name() + u"---" + self.sharer.user.email
class StudyParticipantAssignment(models.Model):
study_participant = models.ForeignKey(StudyParticipant)
user_interface = models.BooleanField()
social_features = models.BooleanField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
def __unicode__(self):
return "%s: %s, ui=%s, social=%s, start=%s, end=%s" % ( \
unicode(self.study_participant), \
self.study_participant.study_group, \
str(self.user_interface), \
str(self.social_features), \
unicode(self.start_time), \
unicode(self.end_time) \
)
| Python |
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
@login_required
def logged_in(request):
return HttpResponse('<span id="success">You are logged in</span>.')
| Python |
from django.http import HttpResponse
from django.utils import simplejson
from django.contrib.auth.models import User
from models import *
from django.contrib.auth.decorators import login_required
@login_required
def recommendation_list(request):
posts = Post.objects.filter(sharedpost__sharedpostreceiver__receiver__user = request.user)
if 'feed_url' in request.REQUEST:
posts = posts.filter(feed__rss_url = request.REQUEST['feed_url'])
if 'limit' in request.REQUEST:
posts = posts.order_by('-sharedpost__sharedpostreceiver__time')
posts = posts[:int(request.REQUEST['limit'])]
urls = []
for post in posts:
urls.append(post.url)
response = simplejson.dumps(urls)
response = "%s(%s);" % (request.REQUEST['callback'], response);
return HttpResponse(response, \
mimetype='application/json')
| Python |
from django.contrib.syndication.feeds import Feed, FeedDoesNotExist
from django.core.exceptions import ObjectDoesNotExist
from models import Sharer, SharedPost, Receiver, SharedPostReceiver
class PostFeed(Feed):
def title(self, obj):
return "FeedMe: Items Shared with %s" % obj.user.email
def link(self, obj):
if not obj:
raise FeedDoesNotExist
return "/feeds/posts/%s/%d/" % (obj.user.email, obj.settings_seed)
def description(self, obj):
return "Items recently shared with %s" % obj.user.email
author_name = "FeedMe"
author_email = "feedme@csail.mit.edu"
author_link = "http://feedme.csail.mit.edu/"
"""Returns the 5 SharedPosts most recently shared with the receiver"""
def items(self, obj):
def get_post(spr): return spr.shared_post
return map(get_post, SharedPostReceiver.objects.filter(receiver=obj).order_by('-time')[:5])
"""Looks for the receiver who corresponds to the feed url"""
def get_object(self, bits):
if len(bits) != 2:
raise ObjectDoesNotExist
receiver = Receiver.objects.get(user__email=bits[0])
"""Check to make sure correct number is in feed url"""
if receiver.settings_seed != long(bits[1]):
raise ObjectDoesNotExist
return receiver
def item_link(self, item):
return item.post.url
def item_pubdate(self, item):
"""There can be multiple SharedPostReceivers for the same SharedPost"""
return SharedPostReceiver.objects.filter(shared_post=item)[0].time
class ShareFeed(Feed):
def title(self, obj):
return "FeedMe: Items Shared by %s" % obj.user.email
def link(self, obj):
if not obj:
raise FeedDoesNotExist
return "/feeds/shares/%s/%d/" % (obj.user.email, obj.settings_seed)
def description(self, obj):
return "Items recently shared by %s" % obj.user.email
author_name = "FeedMe"
author_email = "feedme@csail.mit.edu"
author_link = "http://feedme.csail.mit.edu/"
title_template = "feeds/posts_title.html"
description_template = "feeds/posts_description.html"
"""Returns the 10 SharedPosts most recently shared by the user"""
def items(self, obj):
sharer = Sharer.objects.get(user=obj.user)
def get_post(spr): return spr.shared_post
return map(get_post, SharedPostReceiver.objects.filter(shared_post__sharer=sharer).order_by('-time')[:5])
"""Looks for the receiver who corresponds to the feed url
(user receiver instead of sharer because of settings_seed field)"""
def get_object(self, bits):
if len(bits) != 2:
raise ObjectDoesNotExist
receiver = Receiver.objects.get(user__email=bits[0])
"""Check to make sure correct number is in feed url"""
if receiver.settings_seed != long(bits[1]):
raise ObjectDoesNotExist
return receiver
def item_link(self, item):
return item.post.url
def item_pubdate(self, item):
"""There can be multiple SharedPostReceivers for the same SharedPost"""
return SharedPostReceiver.objects.filter(shared_post=item)[0].time
| Python |
from django.shortcuts import render_to_response
from models import *
import codecs, sys
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def study(request):
return render_to_response('study.html')
| Python |
from django.shortcuts import render_to_response
from models import *
import codecs, sys
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def bar(request):
return render_to_response('bar.html')
| Python |
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(name='removehttp')
@stringfilter
def removehttp(value):
if value.startswith('http://'):
return value.partition('http://')[2]
elif value.startswith('https://'):
return value.partition('https://')[2]
else:
return value
| Python |
from django import template
from django.template.defaultfilters import stringfilter
from server.feedme import textutil
register = template.Library()
@register.filter(name='clean_html')
@stringfilter
def clean_html(value):
return textutil.clean_html(value)
| Python |
from models import *
import codecs, sys
from django.http import HttpResponseRedirect
from django.http import Http404
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def clickthrough(request, sharedpost_pk):
try:
shared_post = SharedPost.objects.get(pk = sharedpost_pk)
except SharedPost.DoesNotExist:
raise Http404
shared_post.clickthroughs += 1
shared_post.save()
return HttpResponseRedirect(shared_post.post.url)
| Python |
from models import *
import codecs, sys
from django.http import HttpResponse
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.db import transaction
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
@login_required
@transaction.commit_manually
def reader_click(request):
"""Logs that a GReader user clicked through on a link in a post"""
feed_url = request.POST['feed_url']
post_url = request.POST['post_url']
# If the /recommend/ call hasn't returned yet, the objects won't be
# available to this transaction. We keep looping until they are
keep_looping = True
while keep_looping:
try:
sharer = Sharer.objects.get(user = request.user)
if sharer.get_study_participant() is None: # they're not a study participant
script_output = "{\"response\": \"ok\"}"
return HttpResponse(script_output, mimetype='application/json')
else:
viewed_posts = ViewedPost.objects \
.filter(post__feed__rss_url = feed_url) \
.filter(post__url=post_url) \
.filter(sharer = sharer) \
.order_by('-time')
if viewed_posts.count() == 0:
transaction.rollback()
else:
keep_looping = False
except Sharer.DoesNotExist:
transaction.rollback()
viewed_post = viewed_posts[0]
viewed_post.link_clickthrough = True
viewed_post.save()
transaction.commit()
script_output = "{\"response\": \"ok\"}"
return HttpResponse(script_output, mimetype='application/json')
| Python |
from django.http import HttpResponse
from django.utils import simplejson
from django.contrib.auth.models import User
from models import *
from django.contrib.auth.decorators import login_required
from recommend import create_user_json
@login_required
def seen_it(request):
feed_objects = get_feed_objects(request.POST['post_url'],
request.POST['feed_url'],
request.POST['recipient'],
request.user)
received_query = SharedPostReceiver.objects \
.filter(shared_post__post = feed_objects['post']) \
.filter(receiver = feed_objects['receiver']) \
.count()
# who has already viewed it in GReader?
viewed_query = ViewedPost.objects \
.filter(post = feed_objects['post']) \
.filter(sharer__user = feed_objects['receiver'].user) \
.count()
# Have we sent it to them before?
sent_query = SharedPostReceiver.objects \
.filter(shared_post__post = feed_objects['post']) \
.filter(receiver = feed_objects['receiver']) \
.filter(shared_post__sharer = feed_objects['sharer']) \
.count()
has_seen_it = set()
sent = set()
if received_query > 0 or viewed_query > 0:
has_seen_it.add(feed_objects['receiver'].user)
if sent_query > 0:
sent.add(feed_objects['receiver'].user)
user_info = create_user_json([ feed_objects['receiver'].user ],
has_seen_it, sent)
# little tweaks since that method wasn't meant for this purpose
user_info[0]['posturl'] = request.POST['post_url']
user_info_json = simplejson.dumps(user_info[0])
return HttpResponse(user_info_json, mimetype='application/json')
def get_feed_objects(post_url, feed_url, recipient_email, sharer_user):
feed_objects = dict()
# get the post
post = Post.objects.filter(feed__rss_url = feed_url).get(url=post_url)
feed_objects['post'] = post
try:
user_receiver = User.objects.get(email = recipient_email)
except User.DoesNotExist:
# Create a user with that username, email and password.
user_receiver = User.objects.create_user(recipient_email, \
recipient_email, \
recipient_email)
user_receiver.save()
try:
receiver = Receiver.objects.get(user=user_receiver)
except Receiver.DoesNotExist:
receiver = Receiver(user=user_receiver)
receiver.save()
feed_objects['receiver'] = receiver
sharer = Sharer.objects.get(user=sharer_user)
feed_objects['sharer'] = sharer
return feed_objects
| Python |
from django.shortcuts import render_to_response
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader
from django.contrib.auth.decorators import login_required
from models import *
import codecs, sys
from django.conf import settings
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def thanks(request, sharedpost_pk):
shared_post = SharedPost.objects.get(pk = sharedpost_pk)
shared_post.thanks += 1
print 'now ' + str(shared_post.thanks) + ' thanks for this post'
shared_post.save()
send_thanks_email(shared_post)
receiver_info = get_receiver_info(shared_post.sharer)
context = {'shared_post': shared_post, 'receiver_info': receiver_info}
return render_to_response('thanks.html', context)
@login_required
def stats(request):
sharer = Sharer.objects.get(user=request.user)
receiver_info = get_receiver_info(sharer)
context = {'sharer': sharer, 'receiver_info': receiver_info}
return render_to_response('thanks.html', context)
def send_thanks_email(shared_post):
"""Sends a thank-you note to the sharer"""
post = shared_post.post
subject = u"Thanks: [FeedMe] " + post.title.strip().replace("\n"," ")
sharer = shared_post.sharer.user
if sharer.first_name != u'' or sharer.last_name != u'':
to_email = sharer.first_name + u' ' + sharer.last_name + \
u' <' + sharer.email + u'>'
else:
to_email = shared_post.sharer.user.email
to_emails = [ to_email ]
from_email = settings.DEFAULT_FROM_EMAIL
# receivers = [spr.receiver.user.email for spr in shared_post.sharedpostreceiver_set.all() ]
# if len(receivers) == 1:
# receiver_string = receivers[0]
# receiver_string += " says "
# elif len(receivers) == 2:
# receiver_string = u" and ".join(receivers)
# receiver_string += " say "
# else:
# receiver_string = u", ".join(receivers[:-1])
# receiver_string += u" and " + receivers[-1]
# receiver_string += " say "
context = Context({"shared_post": shared_post, \
"thanks": True})
template = loader.get_template("thanks_email.html")
html_content = template.render(context)
plaintext_template = loader.get_template("thanks_email_plaintext.html")
text_content = plaintext_template.render(context)
text_content = nltk.clean_html(text_content)
email = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
email.attach_alternative(html_content, "text/html")
email.send()
def get_receiver_info(sharer):
"""Prepares the dictionary for the template"""
receiver_info = []
receivers = Receiver.objects.filter(sharedpostreceiver__shared_post__sharer = sharer).distinct()
for receiver in receivers:
thanks = SharedPost.objects \
.filter(sharedpostreceiver__receiver = receiver) \
.filter(sharer = sharer) \
.filter(thanks__gt = 0)
count = thanks.count()
if count > 0:
receiver_info.append( { 'receiver': receiver, 'count': count, 'barwidth': 10*count})
receiver_info.sort(key=lambda x: x['count'], reverse=True)
return receiver_info
| Python |
from server.feedme.models import *
from django.contrib import admin
# user gets registered by models.py because of the ForeignKey relation
# admin.site.register(User)
admin.site.register(Sharer)
admin.site.register(Receiver)
admin.site.register(Feed)
admin.site.register(Post)
admin.site.register(SharedPost)
admin.site.register(SharedPostReceiver)
admin.site.register(Term)
admin.site.register(TermVectorCell)
admin.site.register(ViewedPost)
admin.site.register(ViewedPostRecommendation)
admin.site.register(LoggedIn)
admin.site.register(StudyParticipant)
admin.site.register(StudyParticipantAssignment)
| Python |
from django.http import HttpResponse
from django.core import serializers
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.mail import EmailMultiAlternatives
from django.utils import html
from django.template import Context, loader
from models import *
import re
import nltk
import codecs, sys
import term_vector
import time
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
@login_required
def share_jsonp(request):
recipient_emails = request.REQUEST['recipients'].split(",")
response = get_share_json(request, recipient_emails)
response = "%s(%s);" % (request.REQUEST['callback'], response)
return HttpResponse(response, \
mimetype='application/json')
@login_required
def share(request):
recipient_emails = request.REQUEST.getlist('recipients')
return HttpResponse(get_share_json(request, recipient_emails), \
mimetype='application/json')
def get_share_json(request, recipient_emails):
feed_url = request.REQUEST['feed_url']
post_url = request.REQUEST['post_url']
digest = (request.REQUEST['digest'] == 'true')
send_individually = False
if 'send_individually' in request.REQUEST:
send_individually = (request.REQUEST['send_individually'] == 'true')
comment = request.REQUEST['comment']
if 'bookmarklet' in request.REQUEST:
bookmarklet = request.REQUEST['bookmarklet'] == 'true' or request.REQUEST['bookmarklet'] == '1'
else:
bookmarklet = False
client = 'greader'
if 'client' in request.REQUEST:
client = request.REQUEST['client']
referrer = ''
if 'referrer' in request.REQUEST:
referrer = request.REQUEST['referrer']
shared_post = create_shared_post(request.user, \
post_url, feed_url, \
recipient_emails, comment, \
digest, bookmarklet, \
client, referrer)
receivers = Receiver.objects \
.filter(sharedpostreceiver__shared_post = shared_post) \
.filter(sharedpostreceiver__sent = False).distinct()
for receiver in receivers:
receiver.term_vector_dirty = True
receiver.save()
print "preparing to send post"
send_post(shared_post, send_individually)
script_output = "{\"response\": \"ok\"}"
return script_output
def create_shared_post(user_sharer, post_url, feed_url, \
recipient_emails, comment, digest, bookmarklet, \
client, referrer):
"""Create all necessary objects to perform the sharing action"""
# get the recipients, creating Users if necessary
try:
sharer = Sharer.objects.get(user=user_sharer)
except Sharer.DoesNotExist:
sharer = Sharer(user=user_sharer)
sharer.save()
# get the post
post = Post.objects.filter(feed__rss_url = feed_url).get(url=post_url)
shared_post = SharedPost(post = post, sharer = sharer, \
comment = comment, bookmarklet = bookmarklet, \
client = client, referrer = referrer)
shared_post.save()
# get or create the recipients' User, Recipient and SharedPostRecipient
# objects
for recipient_email in recipient_emails:
try:
user_receiver = User.objects.get(email = recipient_email)
except User.DoesNotExist:
# Create a user with that username, email and password.
user_receiver = User.objects.create_user(recipient_email, \
recipient_email, \
recipient_email)
user_receiver.save()
try:
receiver = Receiver.objects.get(user=user_receiver)
except Receiver.DoesNotExist:
receiver = Receiver(user=user_receiver)
receiver.save()
# always create a new SharedPostReceiver, because we always
# treat this as a new action and send a new email
shared_post_receiver = SharedPostReceiver( \
shared_post=shared_post, receiver=receiver, digest = digest, \
sent = False)
# if the receiver has elected to only receive digests...
if receiver.digest is True:
shared_post_receiver.digest = True
shared_post_receiver.save()
return shared_post
def send_post(post_to_send, send_individually):
receivers = SharedPostReceiver.objects \
.filter(shared_post = post_to_send) \
.filter(digest = False) \
.filter(sent = False)
if len(receivers) == 0:
print 'No receivers, escaping'
return
if send_individually:
for receiver in receivers:
send_post_email(post_to_send, [receiver])
else:
send_post_email(post_to_send, receivers)
for receiver in receivers:
receiver.sent = True
receiver.save()
def send_post_email(shared_post, receivers):
"""Sends the post in an email to the recipient"""
post = shared_post.post
subject = u"[FeedMe] " + post.title.strip().replace("\n"," ")
sharer = shared_post.sharer.user
if sharer.first_name != u'' or sharer.last_name != u'':
from_email = sharer.first_name + u' ' + sharer.last_name + \
u' <' + sharer.email + u'>'
else:
from_email = shared_post.sharer.user.email
"""Don't send emails to users who choose to subscribe to RSS only"""
to_emails = []
for receiver in receivers:
if not receiver.receiver.feed_only:
to_emails.append(receiver.receiver.user.email)
if shared_post.sharer.cc_me:
to_emails.append(from_email)
try:
thanks = StudyParticipant.objects.get(sharer = shared_post.sharer) \
.social_features
except StudyParticipant.DoesNotExist:
thanks = True
context = Context({"shared_post": shared_post, "thanks": thanks})
template = loader.get_template("share_email.html")
html_content = template.render(context)
print (u'sending ' + subject + u' to ' + unicode(to_emails)).encode('ascii', 'backslashreplace')
plaintext_template = loader.get_template("share_email_plaintext.html")
text_content = plaintext_template.render(context)
text_content = nltk.clean_html(text_content)
email = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
email.attach_alternative(html_content, "text/html")
email.send()
| Python |
from django.shortcuts import render_to_response
import random
from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives
from models import *
from django.conf import settings
def get_settings_url(request):
if not 'email' in request.POST:
return get_email_template("Enter an email address for which to " \
+ "change settings:")
try:
receiver_email = request.POST['email']
user_receiver = User.objects.get(email = receiver_email)
receiver = Receiver.objects.get(user = user_receiver)
reset_seed(receiver)
email_settings_url(receiver_email, receiver.settings_seed)
receiver.save()
return get_email_template("We have emailed you with information "
+ "on changing your subscription settings")
except User.DoesNotExist:
return get_email_template('That email address does not exist')
except Receiver.DoesNotExist:
return get_email_template('That email address has never received mail')
def get_email_template(message):
return render_to_response('get_receiver_email.html', \
{'message' : message})
def reset_seed(receiver):
'''To ensure consistency for feed access, only reset seed if it has never
been set'''
if receiver.settings_seed == 0:
receiver.settings_seed = random.randrange(1,1000000)
def email_settings_url(receiver_email, settings_seed):
subject = u'[FeedMe] Subscription settings information for FeedMe'
from_email = settings.DEFAULT_FROM_EMAIL
to_emails = [receiver_email]
message = u"""
You are receiving this message because you requested to change your
subscription settings on FeedMe.
To modify your settings, go here:
http://feedme.csail.mit.edu/receiver/settings/%s/%d/
Thank you! Feel free to email us at feedme@csail.mit.edu with any comments.
""" % (receiver_email, settings_seed)
email = EmailMultiAlternatives(subject, message, from_email, to_emails)
email.send()
def change_receiver_settings(request, user_email, settings_seed):
(error, message, receiver) = \
settings_access_allowed(request, user_email, settings_seed)
if (not error) and request.POST:
receiver.recommend = (request.POST['recommend'] == u'True')
receiver.digest = (request.POST['digest'] == u'True')
receiver.feed_only = (request.POST['feed_only'] == u'True')
reset_seed(receiver)
email_settings_changed(user_email, receiver.settings_seed)
receiver.save()
message = 'Your settings have been changed'
template_arguments = {
'error' : error,
'message' : message,
}
if not error:
template_arguments['recommend'] = receiver.recommend
template_arguments['digest'] = receiver.digest
template_arguments['user_email'] = user_email
template_arguments['settings_seed'] = settings_seed
template_arguments['feed_only'] = receiver.feed_only
return render_to_response('change_settings.html', template_arguments)
def settings_access_allowed(request, user_email, settings_seed):
try:
user_receiver = User.objects.get(email = user_email)
receiver = Receiver.objects.get(user = user_receiver)
except User.DoesNotExist:
return (True, 'That email address does not exist.', None)
except Receiver.DoesNotExist:
return (True, 'That email address has never received mail.', None)
if not str(receiver.settings_seed) == settings_seed:
return (True,
'Invalid settings key. Check your email for the correct URL.',
None)
return (False, None, receiver)
def email_settings_changed(receiver_email, settings_seed):
subject = u'[FeedMe] Subscription settings changed for FeedMe'
from_email = settings.DEFAULT_FROM_EMAIL
to_emails = [receiver_email]
message = u"""
Your settings for FeedMe have changed. If you are receiving
this email in error and wish to verify your settings, please visit
http://feedme.csail.mit.edu/receiver/settings/%s/%d/
Thank you! Feel free to email us at feedme@csail.mit.edu with any comments.
""" % (receiver_email, settings_seed)
email = EmailMultiAlternatives(subject, message, from_email, to_emails)
email.send()
| Python |
# Create your views here.
| Python |
from django.forms import ModelForm, CheckboxSelectMultiple
from server.feedme.models import *
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.forms.models import modelformset_factory, inlineformset_factory
class SharerForm(ModelForm):
class Meta:
model = Sharer
exclude = ['user']
def __init__(self, *args, **kwargs):
super(SharerForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['blacklist'].label = "Do not show these email addresses in my recommendations"
self.fields['blacklist'].widget = CheckboxSelectMultiple()
self.fields['blacklist'].queryset = Receiver.objects \
.filter(sharedpostreceiver__shared_post__sharer = self.instance) \
.filter(recommend = True) \
.distinct() \
.order_by('user__email')
self.fields['blacklist'].required = False
@login_required
def sharer_settings(request):
sharer = Sharer.objects.get(user = request.user)
posted = request.method == 'POST'
if posted:
form = SharerForm(request.POST, instance = sharer)
if form.is_valid():
print 'updating user'
form.save()
else:
form = SharerForm(instance = sharer)
sp_receivers = SharedPostReceiver.objects.filter(shared_post__sharer = sharer).order_by('time').reverse()[:10]
return render_to_response("sharer_settings.html", RequestContext(request, \
{ "form": form, "done": posted, "sp_receivers": sp_receivers, 'user_email': request.user.email, 'settings_seed': Receiver.objects.get(user=request.user).settings_seed }))
| Python |
from django.http import HttpResponse
from django.utils import simplejson
from django.contrib.auth.models import User
from models import *
def check_logged_in_jsonp(request):
response = check_logged_in_impl(request)
response = "%s(%s);" % (request.REQUEST['callback'], response)
return HttpResponse(response, \
mimetype='application/json')
def check_logged_in(request):
return HttpResponse(check_logged_in_impl(request), mimetype='application/json')
def check_logged_in_impl(request):
response = dict()
response['logged_in'] = request.user.is_authenticated()
response['user_interface'] = True
response['social_features'] = True
if response['logged_in']:
try:
sharer = Sharer.objects.get(user = request.user)
except Sharer.DoesNotExist:
sharer = Sharer(user = request.user)
sharer.save()
log = LoggedIn(sharer = sharer)
log.save()
try:
# personalized UI
study_participant = StudyParticipant.objects.get(sharer = sharer)
response['user_interface'] = study_participant.user_interface
response['social_features'] = study_participant.social_features
except StudyParticipant.DoesNotExist:
print 'not a study participant'
response_json = simplejson.dumps(response)
return response_json
| Python |
from django.http import HttpResponse
from django.utils import simplejson
from django.contrib.auth.models import User
from models import *
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.db import transaction
from django.forms.fields import email_re
import math
import operator
import datetime
import time
from django.core.cache import cache
NUM_RECOMMENDATIONS = 21
@transaction.commit_manually
def recommend_jsonp(request):
response = get_recommendation_json(request)
response = "%s(%s);" % (request.REQUEST['callback'], response)
return HttpResponse(response, \
mimetype='application/json')
def recommend(request):
return HttpResponse(get_recommendation_json(request), \
mimetype='application/json')
def get_recommendation_json(request):
total_time = time.time()
sharer_user = request.user
if not sharer_user.is_authenticated():
response = dict()
response['auth_error'] = True
return simplejson.dumps(response)
feed_title = request.REQUEST['feed_title']
feed_url = request.REQUEST['feed_url']
post_url = request.REQUEST['post_url']
post_title = request.REQUEST['post_title']
post_contents = request.REQUEST['post_contents']
expanded_view = (request.REQUEST['expanded_view'] == 'true')
# If the feed or post or other items are viewed in two transactions at
# the same time, one will fail with an IntegrityError. We'll keep
# looping until we either load them or create them in new transactions
keep_looping = True
num_loops = 0
while keep_looping:
num_loops += 1
try:
post_objects = get_post_objects(feed_url=feed_url, post_url=post_url, \
post_title=post_title, \
post_contents=post_contents, \
sharer_user = sharer_user, \
feed_title = feed_title, \
expanded_view = expanded_view)
keep_looping = False
except IntegrityError:
if num_loops <= 100:
transaction.rollback()
else:
raise
feed = post_objects['feed']
post = post_objects['post']
sharer = post_objects['sharer']
shared_posts = post_objects['shared_posts']
shared_post_receivers = post_objects['shared_post_receivers']
shared_users = post_objects['shared_users']
viewed_post = post_objects['viewed_post']
study_participant = post_objects['study_participant']
if study_participant is None or study_participant.user_interface:
recommendations, sorted_friends = n_best_friends(post, sharer)
else:
recommendations = []
sorted_friends = []
seen_it = who_has_seen_it(recommendations, post)
if viewed_post:
log_recommendations(viewed_post, sorted_friends)
response = dict()
response['posturl'] = post.url
response['users'] = create_user_json(recommendations, seen_it, shared_users)
response_json = simplejson.dumps(response)
transaction.commit()
print "total time for recommendation: " + str(time.time() - total_time)
return response_json
def create_user_json(recommendations, seen_it, sent_already):
"""Turns a list of users into a list of dicts with important properties
for the Greasemonkey script exposed. To be sent to simplejson.dumps
to create a json object to return"""
rec_list = []
for recommendation in recommendations:
person = dict()
person['email'] = recommendation.email
midnight_today = datetime.datetime.combine(datetime.date.today(), \
datetime.time(0, 0))
shared_today = SharedPostReceiver.objects \
.filter(receiver__user = recommendation) \
.filter(digest = False) \
.filter(time__gte = midnight_today) \
.count()
person['shared_today'] = shared_today
person['seen_it'] = recommendation in seen_it
person['sent'] = recommendation in sent_already
rec_list.append(person)
return rec_list
def who_has_seen_it(recommendations, post):
"""who has already seen the link?"""
received_query = SharedPostReceiver.objects \
.filter(shared_post__post = post) \
.filter(receiver__user__in = recommendations) \
.select_related('receiver__user')
received_it = [spr.receiver.user for spr in received_query]
# who has already viewed it in GReader?
viewed_query = ViewedPost.objects \
.filter(post = post) \
.filter(sharer__user__in = recommendations) \
.select_related('sharer__user')
viewed_it = [vp.sharer.user for vp in viewed_query]
return set(received_it + viewed_it)
def get_post_objects(feed_title, feed_url, post_url, post_title, \
post_contents, sharer_user, expanded_view):
# create objects if we need to
try:
feed = Feed.objects.get(rss_url=feed_url)
if feed.title != feed_title:
feed.title = feed_title
feed.save()
except Feed.DoesNotExist:
feed = Feed(rss_url=feed_url, title = feed_title)
feed.save()
try:
post = Post.objects.filter(feed = feed).get(url=post_url)
except Post.DoesNotExist:
post = Post(url=post_url, feed=feed, title=post_title,
contents=post_contents)
post.save()
try:
sharer = Sharer.objects.get(user=sharer_user)
except Sharer.DoesNotExist:
sharer = Sharer(user=sharer_user)
sharer.save()
# returns none if study participant is not active
study_participant = sharer.get_study_participant()
# find out if we've already shared it with anyone
shared_posts = SharedPost.objects.filter(post=post, sharer=sharer)
shared_post_receivers = SharedPostReceiver.objects \
.filter(shared_post__in = shared_posts)
shared_users = []
for shared_user in shared_post_receivers:
shared_users.append(shared_user.receiver.user)
viewed = None
# only log the view for active study participants
if study_participant:
viewed = ViewedPost(post=post, sharer=sharer, \
expanded_view = expanded_view)
viewed.save()
post_objects = dict()
post_objects['feed'] = feed
post_objects['post'] = post
post_objects['sharer'] = sharer
post_objects['shared_posts'] = shared_posts
post_objects['shared_post_receivers'] = shared_post_receivers
post_objects['shared_users'] = shared_users
post_objects['viewed_post'] = viewed
post_objects['study_participant'] = study_participant
return post_objects
def n_best_friends(post, sharer):
friends = Receiver.objects \
.filter(sharedpostreceiver__shared_post__sharer=sharer) \
.filter(recommend = True) \
.distinct()
blacklist = sharer.blacklist.all()
shared_posts = Post.objects \
.filter(sharedpost__sharer=sharer)
total_shared = shared_posts.count()
#pseudocode
# get freqdist (not term vector) for post
#for each friend
#get their term vector ordered by term
# do 'merge-dot' on vectors:
# keep post_counter and person_counter
# increment whichever one has the strcmp lesser
# if they match, multiply (for dotting) and increment both
# at the end divide sum of dots by norm of person vector
# (norm of post vector is constant across all people, so we can ignore term)
scores = []
freq_dist_counts = post.tokenize()
freq_dist = sorted(freq_dist_counts)
for receiver in friends:
# skip people who aren't real email addresses or who are in blacklist
if email_re.match(receiver.user.email) is None or receiver in blacklist:
continue
# concat usernames to create key for cache
num_shared_key = "numshared:" + sharer.user.username + receiver.user.username
num_shared = cache.get(num_shared_key)
if num_shared is None:
num_shared = shared_posts.filter(sharedpost__sharedpostreceiver__receiver=receiver).count()
cache.set(num_shared_key, num_shared)
term_vector = TermVectorCell.objects.filter(receiver = receiver) \
.order_by('term__term').select_related('term')
if len(term_vector) > 0:
post_cosine_distance = cosine_distance(term_vector, freq_dist, freq_dist_counts)
frequency_weight = (num_shared) / float(total_shared)
score = {}
score['receiver'] = receiver
score['score'] = post_cosine_distance * frequency_weight
score['fw'] = frequency_weight
scores.append(score)
# now find the top NUM_RECOMMENDATIONS
sorted_friends = sorted(
scores, key=operator.itemgetter('score'), reverse=True)
if len(sorted_friends) > NUM_RECOMMENDATIONS:
sorted_friends = sorted_friends[0:NUM_RECOMMENDATIONS]
return map(lambda friend:friend['receiver'].user, sorted_friends), sorted_friends
def log_recommendations(viewed_post, recommendations):
for i in range( len(recommendations) ):
receiver = recommendations[i]['receiver']
score = recommendations[i]['score']
vp_rec = ViewedPostRecommendation(receiver=receiver, \
viewed_post = viewed_post, \
recommendation_order = i, \
cosine_distance = score)
vp_rec.save()
def cosine_distance(term_vector, freq_dist, freq_dist_counts):
friend_vector_norm = 0.0
dot_product = 0.0
freq_dist_i = 0 # start looking at the first alphabetical entry
# do the merge-dot-product
for term_cell in term_vector:
# summing squared values for the norm
friend_vector_norm += math.pow(term_cell.count, 2)
# move the counter forward until we catch up alphabetwise
while freq_dist_i < len(freq_dist) and \
freq_dist[freq_dist_i] < term_cell.term.term:
freq_dist_i += 1
# now, if we're not past the edge, check to see if we have a matching
# term
if freq_dist_i >= len(freq_dist):
break
else:
term = freq_dist[freq_dist_i]
if term == term_cell.term.term:
# dot product -- multiply counts together
dot_product += freq_dist_counts[term] * term_cell.count
# now normalize the dot product by the norm of the friend's vector
if friend_vector_norm == 0:
return 0
friend_vector_norm = math.sqrt(friend_vector_norm)
cosine_distance = dot_product / friend_vector_norm
return cosine_distance
def vector_norm(term_vectors):
norm = 0
for term_element in term_vectors:
norm += math.pow(term_element.count, 2)
return math.sqrt(norm)
| Python |
from django.shortcuts import render_to_response
import versionutils
def tutorial(request):
return render_to_response('tutorial_index.html')
def firefox(request):
return render_to_response('tutorial_firefox.html')
def greasemonkey(request):
return render_to_response('tutorial_greasemonkey.html')
def feedme(request):
return render_to_response('tutorial_feedme.html',
{'url' : versionutils.latest_url()})
def login(request):
return render_to_response('tutorial_login.html')
def readpost(request):
return render_to_response('tutorial_readpost.html')
def recommendations(request):
return render_to_response('tutorial_recommendations.html')
def bookmarklet(request):
return render_to_response('tutorial_bookmarklet.html')
def exercise(request):
return render_to_response('tutorial_exercise.html')
| Python |
import nltk
from HTMLParser import HTMLParseError
def clean_html(str):
try:
return nltk.clean_html(str)
except HTMLParseError:
return ""
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
import datetime
import participant_info
from django.db import transaction
from server.feedme.models import *
@transaction.commit_manually
def create_participants():
participants = zip(participant_info.people, participant_info.groups)
for person, group in participants:
print u"saving " + person
sharer = Sharer.objects.get(user__email = person)
sp = StudyParticipant(sharer = sharer, study_group = group)
sp.save()
user_interface = True
social_features = True
if 'noui' in group:
user_interface = False
if 'nosocial' in group:
social_features = False
spa = StudyParticipantAssignment(study_participant = sp, user_interface = user_interface, social_features = social_features, start_time = datetime.datetime.now(), end_time = datetime.datetime.now())
sp.user_interface = spa.user_interface
sp.social_features = spa.social_features
sp.save()
spa.save()
transaction.commit()
try:
create_participants()
except Exception:
transaction.rollback()
| Python |
from django.conf.urls.defaults import *
from feedme.feeds import *
import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
feeds = {
'posts': PostFeed,
'shares': ShareFeed
}
urlpatterns = patterns('',
# Example:
# (r'^server/', include('server.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
#(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/(.*)', admin.site.root, name="admin"),
url(r'^accounts/', include('registration.urls')),
url(r'^address_book/', 'server.feedme.address_book.address_book', \
name='address book'),
url(r'^recommend/', 'server.feedme.recommend.recommend', name='recommend'),
url(r'^recommend_jsonp/', 'server.feedme.recommend.recommend_jsonp', name='recommend_jsonp'),
url(r'^recommendation_list/', 'server.feedme.recommendation_list.recommendation_list', name='recommendation_list'),
url(r'^loggedin/', 'server.feedme.loggedin.logged_in', name='logged in'),
url(r'^check_logged_in/', 'server.feedme.check_logged_in.check_logged_in', name='check login'),
url(r'^check_logged_in_jsonp/', 'server.feedme.check_logged_in.check_logged_in_jsonp', name='check login'),
url(r'^share/', 'server.feedme.share.share', name='share'),
url(r'^share_jsonp/', 'server.feedme.share.share_jsonp', name='share_jsonp'),
url(r'^receiver/settings/$', 'server.feedme.receiver_settings.get_settings_url', name='get receiver settings url'),
url(r'^receiver/settings/(?P<user_email>\S+)/(?P<settings_seed>\d+)/$', 'server.feedme.receiver_settings.change_receiver_settings', name='change receiver settings'),
url(r'^sharer/settings/$', 'server.feedme.sharer_settings.sharer_settings', name='change sharer settings'),
url(r'^bookmarklet/', 'server.feedme.bookmarklet.bookmarklet', name='bookmarklet'),
url(r'^bookmarklet_install/', 'server.feedme.bookmarklet_install.bookmarklet_install', name='bookmarklet installation'),
url(r'^thanks/(?P<sharedpost_pk>\d+)/$', 'server.feedme.thanks.thanks', name='thanks'),
url(r'^thanks/$', 'server.feedme.thanks.stats', name='thanks stats'),
url(r'^seen_it/$', 'server.feedme.seen_it.seen_it', name='seen it'),
url(r'^tutorial/$', 'server.feedme.tutorial.tutorial', name='tutorial start'),
url(r'^tutorial/firefox/$', 'server.feedme.tutorial.firefox', name='firefox tutorial'),
url(r'^tutorial/greasemonkey/$', 'server.feedme.tutorial.greasemonkey', name='greasemonkey tutorial'),
url(r'^tutorial/feedme/$', 'server.feedme.tutorial.feedme', name='feedme install tutorial'),
url(r'^tutorial/login/$', 'server.feedme.tutorial.login', name='feedme login tutorial'),
url(r'^tutorial/readpost/$', 'server.feedme.tutorial.readpost', name='feedme readpost tutorial'),
url(r'^tutorial/recommendations/$', 'server.feedme.tutorial.recommendations', name='feedme recommendations tutorial'),
url(r'^tutorial/bookmarklet/$', 'server.feedme.tutorial.bookmarklet', name='feedme bookmarklet tutorial'),
url(r'^tutorial/exercise/$', 'server.feedme.tutorial.exercise', name='feedme exercise'),
# logging infrastructure
url(r'^clickthrough/(?P<sharedpost_pk>\d+)/.*$', 'server.feedme.clickthrough.clickthrough', name='clickthrough'),
url(r'^reader_click/', 'server.feedme.reader_click.reader_click', name='greader clickthrough'),
url(r'^^study/', 'server.feedme.study.study', name='study'),
url(r'^^bar/', 'server.feedme.bar.bar', name='bar'),
url(r'^$', 'server.feedme.homepage.homepage', name='homepage'),
url(r'^robots.txt$', 'server.feedme.robots.robots', name='robots'),
# rss feeds
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
# static content
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
import datetime
import participant_info
from django.db import transaction
from server.feedme.models import *
import traceback
@transaction.commit_manually
def switch_participants():
try:
emails = participant_info.people
print emails
for email in emails:
sharer = Sharer.objects.get(user__email = email)
sp = StudyParticipant.objects.get(sharer = sharer)
assignments = StudyParticipantAssignment.objects \
.filter(study_participant = sp)
num_assignments = assignments.count()
if num_assignments > 1:
print "%s has %d assignments, not processing more" \
% (email, num_assignments)
continue
print "%s has at most one assignment---switching assignment" % (email)
# end the user's current assignment by setting its end_date
if num_assignments == 1:
print "---changed end time of the current study"
assignment = assignments.get(study_participant = sp)
assignment.end_time = datetime.datetime.now()
assignment.save()
# switch the user's UI configuration
sp.user_interface = not sp.user_interface
sp.save()
print "---group is %s, new ui setting is %s" \
% (sp.study_group, str(sp.user_interface))
# add a new assignment entry starting now
spa = StudyParticipantAssignment(study_participant = sp, user_interface = sp.user_interface, social_features = sp.social_features, start_time = datetime.datetime.now(), end_time = datetime.datetime(2009, 9, 1))
print "---adding assignment: %s" % (unicode(spa))
spa.save()
except Exception, ex:
traceback.print_exc()
transaction.rollback()
else:
transaction.commit()
if __name__ == '__main__':
switch_participants()
| Python |
# Django settings for server project.
import os.path
from private_settings import *
ADMINS = (
('FeedMe Team', 'feedme@lists.csail.mit.edu'),
)
MANAGERS = ADMINS
# Database info is in private_settings.py
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Our sessions last 8 weeks
SESSION_COOKIE_AGE = 4838400
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = 'static/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Secret key is in private_settings.py
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
# Order is important here
# TransactionMiddleware cascades transaction support to all middleware
# below it on this list
# (http://docs.djangoproject.com/en/dev/topics/db/transactions/)
)
ROOT_URLCONF = 'server.urls'
# Template_Dirs is in private_settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
#'django.contrib.admindocs',
'django.contrib.humanize',
'server.feedme',
'registration',
'email_usernames'
)
AUTHENTICATION_BACKENDS = (
# Our custom auth backend that allows email addresses to be used as
# usernames.
'email_usernames.backends.EmailOrUsernameModelBackend',
# Default auth backend that handles everything else.
'django.contrib.auth.backends.ModelBackend',
)
# app-specific settings
ACCOUNT_ACTIVATION_DAYS = 14
REGISTER_COMPLETE_URL = '/accounts/register/complete/'
LOGIN_REDIRECT_URL = '/accounts/login/complete/'
DEFAULT_FROM_EMAIL = 'FeedMe <feedme-owner@lists.csail.mit.edu>'
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
| Python |
"""
Forms and validation code for user registration.
"""
# Necessary for our logic that says that receivers can sign up to become
# sharers
from feedme.models import Sharer
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary. If/when Django ticket #3515
# lands in trunk, this will no longer be necessary.
attrs_dict = { 'class': 'required' }
class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should either preserve the base ``save()`` or implement
a ``save()`` method which returns a ``User``.
"""
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_(u'username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_(u'email address'))
first_name = forms.CharField(min_length = 1, max_length=30, label=_(u'first name'))
last_name = forms.CharField(min_length = 1, max_length=30, label=_(u'last name'))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password'))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'password (again)'))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
# If the user exists but is not a sharer, we don't want to stop
# them from becoming one.
sharer = Sharer.objects.get(user=user)
except User.DoesNotExist:
return self.cleaned_data['username']
except Sharer.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))
def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_(u'You must type the same password each time'))
return self.cleaned_data
def save(self):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User`` (by calling
``RegistrationProfile.objects.create_inactive_user()``).
"""
new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
first_name=self.cleaned_data['first_name'],
last_name=self.cleaned_data['last_name'])
return new_user
class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
label=_(u'I have read and agree to the Terms of Service'),
error_messages={ 'required': u"You must agree to the terms to register" })
class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
try:
user = User.objects.get(email__iexact=self.cleaned_data['email'])
# If the user exists but is not a sharer, we don't want to stop
# them from becoming one.
sharer = Sharer.objects.get(user=user)
except User.DoesNotExist:
return self.cleaned_data['email']
except Sharer.DoesNotExist:
return self.cleaned_data['email']
raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this form and
override the attribute ``bad_domains``.
"""
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com']
def clean_email(self):
"""
Check the supplied email address against a list of known free
webmail domains.
"""
email_domain = self.cleaned_data['email'].split('@')[1]
if email_domain in self.bad_domains:
raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.'))
return self.cleaned_data['email']
| Python |
import datetime
import random
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db import models
from django.db import transaction
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
from django.utils.translation import ugettext_lazy as _
from feedme.models import *
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
"""
Custom manager for the ``RegistrationProfile`` model.
The methods defined here provide shortcuts for account creation
and activation (including generation and emailing of activation
keys), and for cleaning out expired inactive accounts.
"""
def activate_user(self, activation_key):
"""
Validate an activation key and activate the corresponding
``User`` if valid.
If the key is valid and has not expired, return the ``User``
after activating.
If the key is not valid or has expired, return ``False``.
If the key is valid but the ``User`` is already active,
return ``False``.
To prevent reactivation of an account which has been
deactivated by site administrators, the activation key is
reset to the string constant ``RegistrationProfile.ACTIVATED``
after successful activation.
To execute customized logic when a ``User`` is activated,
connect a function to the signal
``registration.signals.user_activated``; this signal will be
sent (with the ``User`` as the value of the keyword argument
``user``) after a successful activation.
"""
from registration.signals import user_activated
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.save()
sharer = Sharer(user = user)
sharer.save()
profile.activation_key = self.model.ACTIVATED
profile.save()
user_activated.send(sender=self.model, user=user)
return user
return False
def create_inactive_user(self, username, password, email,
first_name='', last_name='',
send_email=True):
"""
Create a new, inactive ``User``, generate a
``RegistrationProfile`` and email its activation key to the
``User``, returning the new ``User``.
To disable the email, call with ``send_email=False``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. It receives one context variable, ``site``, which
is the currently-active
``django.contrib.sites.models.Site`` instance. Because it
is used as the subject line of an email, this template's
output **must** be only a single line of text; output
longer than one line will be forcibly joined into only a
single line.
``registration/activation_email.txt``
This template will be used for the body of the email. It
will receive three context variables: ``activation_key``
will be the user's activation key (for use in constructing
a URL to activate the account), ``expiration_days`` will
be the number of days for which the key will be valid and
``site`` will be the currently-active
``django.contrib.sites.models.Site`` instance.
To execute customized logic once the new ``User`` has been
created, connect a function to the signal
``registration.signals.user_registered``; this signal will be
sent (with the new ``User`` as the value of the keyword
argument ``user``) after the ``User`` and
``RegistrationProfile`` have been created, and the email (if
any) has been sent..
"""
from registration.signals import user_registered
from datetime import datetime
try:
new_user = User.objects.get(email = email)
new_user.set_password(password)
new_user.date_joined = datetime.now()
except User.DoesNotExist:
new_user = User.objects.create_user(username, email, password)
new_user.first_name = first_name
new_user.last_name = last_name
new_user.is_active = False
new_user.save()
try:
registration_profile = self.get(user = new_user)
except self.model.DoesNotExist:
registration_profile = self.create_profile(new_user)
if send_email:
from django.core.mail import send_mail
current_site = Site.objects.get_current()
subject = render_to_string('registration/activation_email_subject.txt',
{ 'site': current_site })
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email.txt',
{ 'activation_key': registration_profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': current_site })
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
user_registered.send(sender=self.model, user=new_user)
return new_user
create_inactive_user = transaction.commit_on_success(create_inactive_user)
def create_profile(self, user):
"""
Create a ``RegistrationProfile`` for a given
``User``, and return the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a
SHA1 hash, generated from a combination of the ``User``'s
username and a random salt.
"""
salt = sha_constructor(str(random.random())).hexdigest()[:5]
activation_key = sha_constructor(salt+user.username).hexdigest()
return self.create(user=user,
activation_key=activation_key)
def delete_expired_users(self):
"""
Remove expired instances of ``RegistrationProfile`` and their
associated ``User``s.
Accounts to be deleted are identified by searching for
instances of ``RegistrationProfile`` with expired activation
keys, and then checking to see if their associated ``User``
instances have the field ``is_active`` set to ``False``; any
``User`` who is both inactive and has an expired activation
key will be deleted.
It is recommended that this method be executed regularly as
part of your routine site maintenance; this application
provides a custom management command which will call this
method, accessible as ``manage.py cleanupregistration``.
Regularly clearing out accounts which have never been
activated serves two useful purposes:
1. It alleviates the ocasional need to reset a
``RegistrationProfile`` and/or re-send an activation email
when a user does not receive or does not act upon the
initial activation email; since the account will be
deleted, the user will be able to simply re-register and
receive a new activation key.
2. It prevents the possibility of a malicious user registering
one or more accounts and never activating them (thus
denying the use of those usernames to anyone else); since
those accounts will be deleted, the usernames will become
available for use again.
If you have a troublesome ``User`` and wish to disable their
account while keeping it in the database, simply delete the
associated ``RegistrationProfile``; an inactive ``User`` which
does not have an associated ``RegistrationProfile`` will not
be deleted.
"""
for profile in self.all():
if profile.activation_key_expired() and len(profile.user.receiver_set.all()) == 0:
user = profile.user
if not user.is_active:
user.delete()
class RegistrationProfile(models.Model):
"""
A simple profile which stores an activation key for use during
user account registration.
Generally, you will not want to interact directly with instances
of this model; the provided manager includes methods
for creating and activating new accounts, as well as for cleaning
out accounts which have never been activated.
While it is possible to use this model as the value of the
``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
so. This model's sole purpose is to store data temporarily during
account registration and activation.
"""
ACTIVATED = u"ALREADY_ACTIVATED"
user = models.ForeignKey(User, unique=True, verbose_name=_('user'))
activation_key = models.CharField(_('activation key'), max_length=40)
objects = RegistrationManager()
class Meta:
verbose_name = _('registration profile')
verbose_name_plural = _('registration profiles')
def __unicode__(self):
return u"Registration information for %s" % self.user
def activation_key_expired(self):
"""
Determine whether this ``RegistrationProfile``'s activation
key has expired, returning a boolean -- ``True`` if the key
has expired.
Key expiration is determined by a two-step process:
1. If the user has already activated, the key will have been
reset to the string constant ``ACTIVATED``. Re-activating
is not permitted, and so this method returns ``True`` in
this case.
2. Otherwise, the date the user signed up is incremented by
the number of days specified in the setting
``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
days after signup during which a user is allowed to
activate their account); if the result is less than or
equal to the current date, the key has expired and this
method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key == self.ACTIVATED or \
(self.user.date_joined + expiration_date <= datetime.datetime.now())
activation_key_expired.boolean = True
| Python |
"""
Unit tests for django-registration.
These tests assume that you've completed all the prerequisites for
getting django-registration running in the default setup, to wit:
1. You have ``registration`` in your ``INSTALLED_APPS`` setting.
2. You have created all of the templates mentioned in this
application's documentation.
3. You have added the setting ``ACCOUNT_ACTIVATION_DAYS`` to your
settings file.
4. You have URL patterns pointing to the registration and activation
views, with the names ``registration_register`` and
``registration_activate``, respectively, and a URL pattern named
'registration_complete'.
"""
import datetime
import sha
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core import management
from django.core.urlresolvers import reverse
from django.test import TestCase
from registration import forms
from registration.models import RegistrationProfile
from registration import signals
class RegistrationTestCase(TestCase):
"""
Base class for the test cases; this sets up two users -- one
expired, one not -- which are used to exercise various parts of
the application.
"""
def setUp(self):
self.sample_user = RegistrationProfile.objects.create_inactive_user(username='alice',
password='secret',
email='alice@example.com')
self.expired_user = RegistrationProfile.objects.create_inactive_user(username='bob',
password='swordfish',
email='bob@example.com')
self.expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
self.expired_user.save()
class RegistrationModelTests(RegistrationTestCase):
"""
Tests for the model-oriented functionality of django-registration,
including ``RegistrationProfile`` and its custom manager.
"""
def test_new_user_is_inactive(self):
"""
Test that a newly-created user is inactive.
"""
self.failIf(self.sample_user.is_active)
def test_registration_profile_created(self):
"""
Test that a ``RegistrationProfile`` is created for a new user.
"""
self.assertEqual(RegistrationProfile.objects.count(), 2)
def test_activation_email(self):
"""
Test that user signup sends an activation email.
"""
self.assertEqual(len(mail.outbox), 2)
def test_activation_email_disable(self):
"""
Test that activation email can be disabled.
"""
RegistrationProfile.objects.create_inactive_user(username='noemail',
password='foo',
email='nobody@example.com',
send_email=False)
self.assertEqual(len(mail.outbox), 2)
def test_activation(self):
"""
Test that user activation actually activates the user and
properly resets the activation key, and fails for an
already-active or expired user, or an invalid key.
"""
# Activating a valid user returns the user.
self.failUnlessEqual(RegistrationProfile.objects.activate_user(RegistrationProfile.objects.get(user=self.sample_user).activation_key).pk,
self.sample_user.pk)
# The activated user must now be active.
self.failUnless(User.objects.get(pk=self.sample_user.pk).is_active)
# The activation key must now be reset to the "already activated" constant.
self.failUnlessEqual(RegistrationProfile.objects.get(user=self.sample_user).activation_key,
RegistrationProfile.ACTIVATED)
# Activating an expired user returns False.
self.failIf(RegistrationProfile.objects.activate_user(RegistrationProfile.objects.get(user=self.expired_user).activation_key))
# Activating from a key that isn't a SHA1 hash returns False.
self.failIf(RegistrationProfile.objects.activate_user('foo'))
# Activating from a key that doesn't exist returns False.
self.failIf(RegistrationProfile.objects.activate_user(sha.new('foo').hexdigest()))
def test_account_expiration_condition(self):
"""
Test that ``RegistrationProfile.activation_key_expired()``
returns ``True`` for expired users and for active users, and
``False`` otherwise.
"""
# Unexpired user returns False.
self.failIf(RegistrationProfile.objects.get(user=self.sample_user).activation_key_expired())
# Expired user returns True.
self.failUnless(RegistrationProfile.objects.get(user=self.expired_user).activation_key_expired())
# Activated user returns True.
RegistrationProfile.objects.activate_user(RegistrationProfile.objects.get(user=self.sample_user).activation_key)
self.failUnless(RegistrationProfile.objects.get(user=self.sample_user).activation_key_expired())
def test_expired_user_deletion(self):
"""
Test that
``RegistrationProfile.objects.delete_expired_users()`` deletes
only inactive users whose activation window has expired.
"""
RegistrationProfile.objects.delete_expired_users()
self.assertEqual(RegistrationProfile.objects.count(), 1)
def test_management_command(self):
"""
Test that ``manage.py cleanupregistration`` functions
correctly.
"""
management.call_command('cleanupregistration')
self.assertEqual(RegistrationProfile.objects.count(), 1)
def test_signals(self):
"""
Test that the ``user_registered`` and ``user_activated``
signals are sent, and that they send the ``User`` as an
argument.
"""
def receiver(sender, **kwargs):
self.assert_('user' in kwargs)
self.assertEqual(kwargs['user'].username, u'signal_test')
received_signals.append(kwargs.get('signal'))
received_signals = []
expected_signals = [signals.user_registered, signals.user_activated]
for signal in expected_signals:
signal.connect(receiver)
RegistrationProfile.objects.create_inactive_user(username='signal_test',
password='foo',
email='nobody@example.com',
send_email=False)
RegistrationProfile.objects.activate_user(RegistrationProfile.objects.get(user__username='signal_test').activation_key)
self.assertEqual(received_signals, expected_signals)
class RegistrationFormTests(RegistrationTestCase):
"""
Tests for the forms and custom validation logic included in
django-registration.
"""
def test_registration_form(self):
"""
Test that ``RegistrationForm`` enforces username constraints
and matching passwords.
"""
invalid_data_dicts = [
# Non-alphanumeric username.
{
'data':
{ 'username': 'foo/bar',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' },
'error':
('username', [u"Enter a valid value."])
},
# Already-existing username.
{
'data':
{ 'username': 'alice',
'email': 'alice@example.com',
'password1': 'secret',
'password2': 'secret' },
'error':
('username', [u"This username is already taken. Please choose another."])
},
# Mismatched passwords.
{
'data':
{ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'bar' },
'error':
('__all__', [u"You must type the same password each time"])
},
]
for invalid_dict in invalid_data_dicts:
form = forms.RegistrationForm(data=invalid_dict['data'])
self.failIf(form.is_valid())
self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1])
form = forms.RegistrationForm(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failUnless(form.is_valid())
def test_registration_form_tos(self):
"""
Test that ``RegistrationFormTermsOfService`` requires
agreement to the terms of service.
"""
form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failIf(form.is_valid())
self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"])
form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo',
'tos': 'on' })
self.failUnless(form.is_valid())
def test_registration_form_unique_email(self):
"""
Test that ``RegistrationFormUniqueEmail`` validates uniqueness
of email addresses.
"""
form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
'email': 'alice@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failIf(form.is_valid())
self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."])
form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.failUnless(form.is_valid())
def test_registration_form_no_free_email(self):
"""
Test that ``RegistrationFormNoFreeEmail`` disallows
registration with free email addresses.
"""
base_data = { 'username': 'foo',
'password1': 'foo',
'password2': 'foo' }
for domain in ('aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'live.com'):
invalid_data = base_data.copy()
invalid_data['email'] = u"foo@%s" % domain
form = forms.RegistrationFormNoFreeEmail(data=invalid_data)
self.failIf(form.is_valid())
self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."])
base_data['email'] = 'foo@example.com'
form = forms.RegistrationFormNoFreeEmail(data=base_data)
self.failUnless(form.is_valid())
class RegistrationViewTests(RegistrationTestCase):
"""
Tests for the views included in django-registration.
"""
def test_registration_view(self):
"""
Test that the registration view rejects invalid submissions,
and creates a new user and redirects after a valid submission.
"""
# Invalid data fails.
response = self.client.post(reverse('registration_register'),
data={ 'username': 'alice', # Will fail on username uniqueness.
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.assertEqual(response.status_code, 200)
self.failUnless(response.context['form'])
self.failUnless(response.context['form'].errors)
response = self.client.post(reverse('registration_register'),
data={ 'username': 'foo',
'email': 'foo@example.com',
'password1': 'foo',
'password2': 'foo' })
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete'))
self.assertEqual(RegistrationProfile.objects.count(), 3)
def test_activation_view(self):
"""
Test that the activation view activates the user from a valid
key and fails if the key is invalid or has expired.
"""
# Valid user puts the user account into the context.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': RegistrationProfile.objects.get(user=self.sample_user).activation_key }))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['account'].pk, self.sample_user.pk)
# Expired user sets the account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': RegistrationProfile.objects.get(user=self.expired_user).activation_key }))
self.failIf(response.context['account'])
# Invalid key gets to the view, but sets account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': 'foo' }))
self.failIf(response.context['account'])
# Nonexistent key sets the account to False.
response = self.client.get(reverse('registration_activate',
kwargs={ 'activation_key': sha.new('foo').hexdigest() }))
self.failIf(response.context['account'])
| Python |
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user"])
| Python |
"""
URLConf for Django user registration and authentication.
If the default behavior of the registration views is acceptable to
you, simply use a line like this in your root URLConf to set up the
default URLs for registration::
(r'^accounts/', include('registration.urls')),
This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.
But if you'd like to customize the behavior (e.g., by passing extra
arguments to the various views) or split up the URLs, feel free to set
up your own URL patterns for these views instead. If you do, it's a
good idea to use the names ``registration_activate``,
``registration_complete`` and ``registration_register`` for the
various steps of the user-signup process.
"""
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth import views as auth_views
from registration.views import activate
from registration.views import register
from email_usernames.forms import EmailRegistrationForm
from email_usernames.views import email_login
urlpatterns = patterns('',
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
name='registration_activate'),
url(r'^login/$',
email_login,
{'template_name': 'registration/login.html'},
name='email-login'),
url(r'^login/complete/$',
direct_to_template,
{'template': 'registration/login_complete.html'},
name='registration_complete'),
url(r'^logout/$',
auth_views.logout,
{'template_name': 'registration/logout.html'},
name='auth_logout'),
url(r'^password/change/$',
auth_views.password_change,
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
name='auth_password_change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm,
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
name='auth_password_reset_complete'),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
name='auth_password_reset_done'),
url(r'^register/$', register, { 'form_class':EmailRegistrationForm }, name="registration_register"),
url(r'^register/complete/$',
direct_to_template,
{'template': 'registration/registration_complete.html'},
name='registration_complete'),
)
| Python |
from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
| Python |
"""
A management command which deletes expired accounts (e.g.,
accounts which signed up but never activated) from the database.
Calls ``RegistrationProfile.objects.delete_expired_users()``, which
contains the actual logic for determining which accounts are deleted.
"""
from django.core.management.base import NoArgsCommand
from registration.models import RegistrationProfile
class Command(NoArgsCommand):
help = "Delete expired user registrations from the database"
def handle_noargs(self, **options):
RegistrationProfile.objects.delete_expired_users()
| Python |
"""
Views which allow users to create and activate accounts.
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
def activate(request, activation_key,
template_name='registration/activate.html',
extra_context=None):
"""
Activate a ``User``'s account from an activation key, if their key
is valid and hasn't expired.
By default, use the template ``registration/activate.html``; to
change this, pass the name of a template as the keyword argument
``template_name``.
**Required arguments**
``activation_key``
The activation key to validate and use for activating the
``User``.
**Optional arguments**
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``template_name``
A custom template to use.
**Context:**
``account``
The ``User`` object corresponding to the account, if the
activation was successful. ``False`` if the activation was not
successful.
``expiration_days``
The number of days for which activation keys stay valid after
registration.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/activate.html or ``template_name`` keyword argument.
"""
activation_key = activation_key.lower() # Normalize before trying anything with it.
account = RegistrationProfile.objects.activate_user(activation_key)
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
context_instance=context)
def register(request, success_url=None,
form_class=RegistrationForm,
template_name='registration/registration_form.html',
extra_context=None):
"""
Allow a new user to register an account.
Following successful registration, issue a redirect; by default,
this will be whatever URL corresponds to the named URL pattern
``registration_complete``, which will be
``/accounts/register/complete/`` if using the included URLConf. To
change this, point that named pattern at another URL, or pass your
preferred URL as the keyword argument ``success_url``.
By default, ``registration.forms.RegistrationForm`` will be used
as the registration form; to change this, pass a different form
class as the ``form_class`` keyword argument. The form class you
specify must have a method ``save`` which will create and return
the new ``User``.
By default, use the template
``registration/registration_form.html``; to change this, pass the
name of a template as the keyword argument ``template_name``.
**Required arguments**
None.
**Optional arguments**
``form_class``
The form class to use for registration.
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``success_url``
The URL to redirect to on successful registration.
``template_name``
A custom template to use.
**Context:**
``form``
The registration form.
Any extra variables supplied in the ``extra_context`` argument
(see above).
**Template:**
registration/registration_form.html or ``template_name`` keyword
argument.
"""
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
new_user = form.save()
# success_url needs to be dynamically generated here; setting a
# a default value using reverse() will cause circular-import
# problems with the default URLConf for this application, which
# imports this file.
return HttpResponseRedirect(success_url or reverse('registration_complete'))
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'form': form },
context_instance=context)
| Python |
from urllib import urlencode
import httplib
DEFAULT_VER = "v1"
POSTRANK_URL = "api.postrank.com"
RAW = 0
PROCESSED = 1
class PostRank(object):
def __init__(self, version=DEFAULT_VER):
"""
Create a new PostRank object.
'version' version of the api to use. Maps to the api url.
eg. http://api.postrank.com/<version>/postrank
"""
self.version = version
def __call__(self, resource, **kwargs):
"""
Call to the PostRank api.
Use the options outlined at http://postrank.com/api
'resource' the api resource you want to use (feed_id, feed, postrank, etc).
'**kwargs' api fields as per the api document.
eg.
postrank = PostRank()
result = postrank('feed_id', appkey='<your api key>', format='json', url='http://www.postrank.com')
Note:
When using the 'postrank' resource
- url[] is entered as an array of urls
- feed_id[] is entered as an array of feed_id
"""
method="GET"
# unfortunatly, no standard uri change other than this to denote requirement of POST
if (self.version == 'v1' and resource.endswith('postrank')):
method='POST'
postrank_urls = []
postrankfeed_ids = []
# get post args
if kwargs.has_key('url'):
for url in kwargs.pop('url'):
postrank_urls.append(url)
if kwargs.has_key('feed_id'):
for feed_id in kwargs.pop('feed_id'):
postrankfeed_ids.append(feed_id)
if kwargs:
# build api args
args = urlencode(kwargs.items())
c = httplib.HTTPConnection(POSTRANK_URL)
uri = "/%s/%s?%s" %(self.version, resource,args)
try:
if (method == "POST"):
postargs = "%s&%s" %(urlencode({'url[]': postrank_urls}, True), urlencode({'feed_id[]': postrankfeed_ids}, True))
c.request(method, "%s" %(uri), postargs)
else:
c.request(method, "%s" %(uri))
result = c.getresponse()
retVal = []
if (result.status != 200): # HTTP 200
retVal.insert(RAW, None)
retVal.insert(PROCESSED, None)
return retVal
retVal.insert(RAW, result.read())
# process the raw input in the format specified
if (kwargs['format'] == "json"):
try:
import simplejson
retVal.insert(PROCESSED, simplejson.loads(retVal[RAW]))
except ImportError:
raise PostRankException("missing library: simplejson is not installed")
return retVal
finally:
c.close()
class PostRankException(Exception):
pass
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
from datetime import datetime, timedelta
split_delta = timedelta(seconds = 5)
def split_sharedposts():
"""Finds and splits all sharedposts with multiple receivers over a large period of time
into separate sharedposts"""
for sp in SharedPost.objects.all():
splits = generate_splits(sp)
if len(splits) > 1:
print [len(split) for split in splits]
# uncomment the next line to actually make the change
update_splits(sp, splits)
def generate_splits(sp):
sp_receivers = SharedPostReceiver.objects \
.filter(shared_post = sp) \
.order_by('time')
if sp_receivers.count() == 0:
return []
splits = [ set() ] # useful for debugging output
current_shared_post = sp
earliest_time = sp_receivers[0].time
for spr in sp_receivers:
if spr.time - earliest_time >= split_delta:
print 'needs to be split! ' + str(spr.shared_post.id) \
+ ': ' + str(earliest_time) + ' ... ' + str(spr.time)
# start a new set of posts
splits.append( set() )
earliest_time = spr.time
splits[-1].add(spr)
return splits
def update_splits(shared_post, splits):
"""updates the shared post receivers to a new shared post if necessary"""
for i, split in enumerate(splits):
if len(splits) > 1 and i == 0:
print 'split ' + str(i) + ': ' + str(shared_post.id)
if i > 0: # the first group (index 0) can keep the original post
sp_copy = copy_shared_post(shared_post)
sp_copy.save()
for spr in split:
spr.shared_post = sp_copy
spr.save()
print 'split ' + str(i) + ': ' + str(sp_copy.id)
def copy_shared_post(current_shared_post):
new_shared_post = SharedPost( \
post = current_shared_post.post,
sharer = current_shared_post.sharer,
comment = current_shared_post.comment,
bookmarklet = current_shared_post.bookmarklet,
thanks = current_shared_post.thanks,
clickthroughs = current_shared_post.clickthroughs)
return new_shared_post
if __name__ == '__main__':
split_sharedposts()
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
import datetime
import sys
from copy import deepcopy
import numpy
from django.db.models import F
from datetime import datetime, timedelta
import participant_info
def summarize_user(study_participant):
print study_participant.sharer.user.email + ' --------------------------'
spas = StudyParticipantAssignment.objects \
.filter(study_participant = study_participant) \
.order_by('start_time')
for spa in spas:
print 'participant assigment: ' + str(spa.start_time) + ' to ' + str(spa.end_time)
start_midnight = datetime(day = spa.start_time.day,
month = spa.start_time.month,
year = spa.start_time.year)
start_midnight += timedelta(days = 1)
date_points = [ spa.start_time ]
date_cursor = deepcopy(start_midnight)
while(date_cursor < spa.end_time+timedelta(days=3)):
date_points.append(deepcopy(date_cursor))
date_cursor += timedelta(days = 1)
date_points.append(spa.end_time+timedelta(days=3))
for i in range(len(date_points)-1):
start_iter = date_points[i]
end_iter = date_points[i+1]
vps = ViewedPost.objects \
.filter(sharer = study_participant.sharer,
time__gte = start_iter,
time__lt = end_iter)
expanded = "zeroed"
if (vps.count() > 0):
expanded = str(vps[0].expanded_view)
print str(vps.count()) + ' ViewedPosts\t' + str(start_iter) + ' to ' + str(end_iter) + ' expanded: ' + expanded
print
print
print
print
if __name__ == '__main__':
emails = participant_info.people
for email in emails:
sp = StudyParticipant.objects.get(sharer__user__email = email)
summarize_user(sp)
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
import datetime
import sys
import numpy
from django.db.models import F
from datetime import timedelta
# We don't want to show up in statistics
admins = ['msbernst@mit.edu', 'marcua@csail.mit.edu',
'karger@csail.mit.edu']
def generate_statistics(sharers, start_time, end_time):
"""Returns a dictionary of useful statistics for the sharers"""
stats = dict()
# unique sharing events
newposts = SharedPost.objects \
.filter(
sharedpostreceiver__time__gte = start_time,
sharedpostreceiver__time__lt = end_time,
sharer__in = sharers
).distinct()
stats['shared_posts'] = newposts.count()
# emails with clickthroughs
clicked = newposts.all() \
.filter(clickthroughs__gte = 1)
stats['clickthroughs'] = sum([sp.clickthroughs for sp in clicked])
digests = newposts.all() \
.filter(sharedpostreceiver__digest = True)
stats['digests'] = digests.count()
# emails with thanks
thanked = newposts.all() \
.filter(thanks__gte = 1)
stats['thanks'] = sum([sp.thanks for sp in thanked])
# total number of people (not unique) shared with
recipients = Receiver.objects \
.filter(sharedpostreceiver__shared_post__in = newposts.all())
stats['recipients'] = recipients.count()
# unique number of people shared with
unique_recipients = Receiver.objects \
.filter(sharedpostreceiver__shared_post__in = newposts.all()) \
.distinct()
stats['unique_recipients'] = unique_recipients.count()
# times GReader loaded in browser
logins = LoggedIn.objects \
.filter(
time__gte = start_time,
time__lt = end_time,
sharer__in = sharers
).distinct()
stats['logins'] = logins.count()
# number of posts viewed
viewed = ViewedPost.objects \
.filter(
time__gte = start_time,
time__lte = end_time,
sharer__in = sharers
).distinct()
stats['viewed'] = viewed.count()
# number of viewed posts with a link clicked in the greader interface
greader_clicked = viewed.all().filter(link_clickthrough = True)
stats['greader_clicked'] = greader_clicked.count()
num_viewed_expanded = viewed.all().filter(expanded_view = True).count()
num_viewed_list = viewed.all().filter(expanded_view = False).count()
stats['expanded'] = (num_viewed_expanded > num_viewed_list)
return stats
def userstatssince(numdays, participants = StudyParticipant.objects.
exclude(sharer__user__email__in = admins)):
sinceday = datetime.datetime.now() - datetime.timedelta(days = numdays)
now = datetime.datetime.now()
sharers = [sp.sharer for sp in participants]
first = True
keys = dict()
for sharer in sharers:
stats = generate_statistics([sharer], sinceday, now)
if first:
keys = stats.keys()
print "name,email,study_group,ui_on,social_on,%s" % (",".join(keys))
first = False
name = sharer.name()
email = sharer.user.email
participant = StudyParticipant.objects.get(sharer = sharer)
study_group = participant.study_group
ui = (participant.user_interface == 1)
social = (participant.social_features == 1)
stats_str = ",".join([str(stats[key]) for key in keys])
print ("%s,%s,%s,%s,%s,%s" % (name, email, study_group, str(ui), str(social), stats_str)).encode('ascii', 'backslashreplace')
def userstats(participants = StudyParticipant.objects
.exclude(sharer__user__email__in = admins)):
first = True
(assign_keys, keys) = ([], [])
for participant in participants:
keyreport = dict()
spas = StudyParticipantAssignment.objects \
.filter(study_participant = participant) \
.order_by("start_time")
for (order, spa) in enumerate(spas):
stats = generate_statistics([participant.sharer], spa.start_time, spa.end_time)
if first:
(assign_keys, keys) = \
userstats_first(stats)
first = False
keyreport = userstats_updateassignments(spa, order, keyreport)
keyreport = userstats_updatereport(spa.user_interface, keyreport, stats)
userstats_printreport(participant, keyreport, \
[assign_keys, keys])
def userstats_printreport(participant, report, key_lists):
""" Prints a participant row """
sharer = participant.sharer
pk = sharer.user.pk
name = sharer.name()
email = sharer.user.email
participant = StudyParticipant.objects.get(sharer = sharer)
study_group = participant.study_group
social = participant.studyparticipantassignment_set \
.order_by('start_time')[0].social_features
valstrings = [userstats_valstring(report, key_list) for key_list in key_lists]
print ("%d,\"%s\",%s,%s,%s,%s" % \
(pk, name, email, study_group, str(social),",".join(valstrings)) \
).encode('ascii', 'backslashreplace')
def userstats_valstring(report, keys):
vals = [str(report[key]) for key in keys]
return ",".join(vals)
def userstats_uistring(ui):
""" Turns the ui boolean into a human-readable variable """
return "ui" if (ui == 1) else "noui"
def userstats_updateassignments(spa, order, assignments):
"""
Given the assignment in spa, updates and returns the
assignments dictionary
"""
ui = userstats_uistring(spa.user_interface)
assignments['order'] = order
assignments['start_time'] = spa.start_time
assignments['end_time'] = spa.end_time
assignments['ui'] = ui
return assignments
def userstats_updatereport(ui, report, stats):
""" Updates the report with the statistics from stats """
for k, v in stats.items():
report["%s" % (k)] = v
return report
def userstats_first(stats):
""" Called on the very first iteration/user """
keys = stats.keys()
assign_keys = ["order", "start_time", "end_time", "ui"]
print "pk,name,email,study_group,social,%s,%s" % \
( \
",".join(assign_keys), ",".join(keys) \
)
return (assign_keys, keys)
def normalize(to_norm, norm_key):
normalized = dict()
norm_val = to_norm[norm_key] * 1.0
for k, v in to_norm.items():
new_key = "%s_div_%s" % (k, norm_key)
if norm_val != 0:
normalized[new_key] = to_norm[k]/norm_val
else:
normalized[new_key] = ''
return normalized
if __name__ == "__main__":
num_args = len(sys.argv)
if sys.argv[1] == 'user-stats-since':
if len(sys.argv) == 3:
userstatssince(int(sys.argv[2]))
elif len(sys.argv) == 4:
person = StudyParticipant.objects.filter(sharer__user__email = sys.argv[3])
userstatssince(int(sys.argv[2]), person)
elif sys.argv[1] == 'user-stats':
if len(sys.argv) == 2:
userstats()
elif len(sys.argv) == 3:
person = StudyParticipant.objects.filter(sharer__user__email = sys.argv[2])
userstats(person)
else:
print "Arguments: [user-stats|user-stats-since num-days]"
| Python |
# Per reviewer's request, calculate the % of shares that were
# to someone using FeedMe
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
import datetime
import sys
import numpy
from django.db.models import F
from datetime import timedelta
from statistics import admins
from nltk import FreqDist
participants = StudyParticipant.objects \
.exclude(sharer__user__email__in = admins)
def stats_recipients():
total_shared = 0
total_shared_with_user = 0
for participant in participants:
spas = StudyParticipantAssignment.objects \
.filter(study_participant = participant) \
.order_by("start_time")
for (order, spa) in enumerate(spas):
(shared, shared_with_user) = count_shares(spa)
print (shared, shared_with_user)
total_shared = total_shared + shared
total_shared_with_user = total_shared_with_user + shared_with_user
print '\n\n\n'
print str(total_shared) + ' items shared total'
print str(total_shared_with_user) + ' items shared with a FeedMe user'
print str(float(total_shared_with_user) / total_shared)
def count_shares(spa):
receivers = Receiver.objects \
.filter(sharedpostreceiver__shared_post__sharer = \
spa.study_participant.sharer,
sharedpostreceiver__time__gt = spa.start_time,
sharedpostreceiver__time__lte = spa.end_time)
print receivers
receiver_users = receivers.filter( \
user__in = [p.sharer.user for p in participants])
print receiver_users
return (receivers.count(), receiver_users.count())
def recipient_degree():
degree = []
for receiver in Receiver.objects.all():
shared_posts = SharedPost.objects.filter(sharedpostreceiver__receiver = receiver, sharer__studyparticipant__in = participants)
shared_by = Sharer.objects.filter(sharedpost__in = shared_posts).distinct()
if shared_by.count() > 0 and receiver.user.email not in ['msbernst@mit.edu', 'msbernst@csail.mit.edu', 'feedme@csail.mit.edu']:
#print (receiver.user.email + u': ' + unicode(shared_by)).encode('utf-8', 'backslashreplace')
degree.append(shared_by.count())
print shared_by.count()
degree_dist = FreqDist(degree)
print degree_dist
if __name__ == "__main__":
stats_recipients()
recipient_degree()
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.contrib.auth.models import User
from server.feedme.models import *
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader
import sys, codecs
from django.db import transaction
from django.conf import settings
# set stdout to Unicode so we can write Unicode strings to stdout
# todo: create some sort of startup script which calls this
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
def digest_posts():
for receiver in Receiver.objects.all():
digested_posts = SharedPostReceiver.objects \
.filter(receiver = receiver) \
.filter(digest = True) \
.filter(sent = False)
if digested_posts.count() > 0:
send_digest_posts(digested_posts, receiver)
else:
print (receiver.user.username + ' hasn\'t received posts recently').encode('ascii', 'backslashreplace')
# tell the sharers that their posts have been sent
for sharer in Sharer.objects.all():
shared_posts = SharedPost.objects \
.filter(sharer = sharer) \
.filter(sharedpostreceiver__sent = False) \
.filter(sharedpostreceiver__digest = True) \
.distinct()
if shared_posts.count() > 0:
send_digest_report(shared_posts, sharer)
else:
print (sharer.user.username + u' hasn\'t shared digest posts').encode('ascii', 'backslashreplace')
for s_p_receiver in SharedPostReceiver.objects \
.filter(sent = False) \
.filter(digest = True):
s_p_receiver.sent = True
s_p_receiver.save()
def send_digest_posts(posts, receiver):
"""Sends the list of posts in an email to the recipient"""
subject = u"[FeedMe] Personalized Newspaper: " + posts[0].shared_post.post.title.strip().replace("\n"," ")
from_email = settings.DEFAULT_FROM_EMAIL
to_emails = [receiver.user.email]
for post in posts:
post.thanks = True
if post.shared_post.sharer.studyparticipant_set.all().count() == 1:
participant = post.shared_post.sharer.studyparticipant_set.all()[0]
post.thanks = participant.social_features
context = Context({"posts": posts})
template = loader.get_template("digest.html")
html_content = template.render(context)
print (u'sending ' + subject + u' to ' + unicode(to_emails)).encode('ascii', 'backslashreplace')
template_plaintext = loader.get_template("digest_plaintext.html")
text_content = template_plaintext.render(context)
text_content = nltk.clean_html(text_content)
email = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
email.attach_alternative(html_content, "text/html")
email.send()
def pluralize(count):
if count > 1 or count == 0:
return 's'
else:
return ''
def send_digest_report(shared_posts, sharer):
"""Sends an email to the sharer letting him/her know that the digest went out"""
subject = u"[FeedMe] Digest Report: " + \
unicode(shared_posts.count()) + u' post' + \
pluralize(shared_posts.count()) + ' shared'
from_email = settings.DEFAULT_FROM_EMAIL
to_emails = [sharer.user.email]
for shared_post in shared_posts:
shared_post.receivers = []
for shared_post_receiver in SharedPostReceiver.objects \
.filter(shared_post = shared_post) \
.filter(sent = False) \
.filter(digest = True):
shared_post.receivers.append(shared_post_receiver)
context = Context({'shared_posts': shared_posts})
template = loader.get_template("digest_report.html")
html_content = template.render(context)
template_plaintext = loader.get_template("digest_report_plaintext.html")
text_content = template_plaintext.render(context)
text_content = nltk.clean_html(text_content)
print (u'sending ' + subject + u' to ' + unicode(to_emails)).encode('ascii', 'backslashreplace')
email = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
email.attach_alternative(html_content, "text/html")
email.send()
if __name__ == '__main__':
digest_posts()
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
from server.feedme.recommend import n_best_friends
from server.feedme.share import create_shared_post, send_post
from server.term_vector import update_receivers
# sharer for testing
USER_SHARER = User.objects.get(email="margaret.leibovic@gmail.com")
SHARER = Sharer.objects.get(user=USER_SHARER)
# email addresses for new test users
EMAIL_A = "margaret.leibovic+a@gmail.com"
EMAIL_B = "margaret.leibovic+b@gmail.com"
# feed urls for test feeds (feeds already exist in db)
FEED_X = "http://sfbay.craigslist.org/apa/index.rss"
FEED_Y = "http://www.codinghorror.com/blog/index.xml"
# post urls for test posts (posts already exist in db)
POSTS_X = Post.objects.filter(feed=Feed.objects.filter(rss_url=FEED_X))
POSTS_Y = Post.objects.filter(feed=Feed.objects.filter(rss_url=FEED_Y))
def send_test_post(post, feed, test_receiver):
print "RECOMMEND TEST: sending post to", test_receiver, "from feed", feed
shared_post = create_shared_post(USER_SHARER, \
post, feed, \
[test_receiver], "", \
False, False)
receivers = Receiver.objects \
.filter(sharedpostreceiver__shared_post = shared_post)
# update term vectors
update_receivers(receivers)
send_post(shared_post, False)
def clean_up():
print "RECOMMEND TEST: cleaning up"
# delete test users and receivers to clean up before re-running test
user_a = User.objects.get(email=EMAIL_A)
user_b = User.objects.get(email=EMAIL_B)
Receiver.objects.get(user=user_a).delete()
Receiver.objects.get(user=user_b).delete()
user_a.delete()
user_b.delete()
def run_test():
# recommend a post to user A from feed X
send_test_post(POSTS_X[0].url, FEED_X, EMAIL_A)
for post in POSTS_Y:
# recommend a post to user B from feed Y
send_test_post(post.url, FEED_Y, EMAIL_B)
# make a call to n_best_friends with a post from feed X
recommendations, sorted_friends = n_best_friends(POSTS_X[1], SHARER)
# at some point user B's score should be higher than user A's score
# due to an increasing frequency_weight
for friend in sorted_friends:
if friend['receiver'].user.email == EMAIL_A:
print "RECOMMEND TEST: user A score =", friend['score'], ", fw =", friend['fw']
if friend['receiver'].user.email == EMAIL_B:
print "RECOMMEND TEST: user B score =", friend['score'], ", fw =", friend['fw']
clean_up()
if __name__ == '__main__':
run_test()
| Python |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from server.feedme.models import *
import datetime
import sys
import numpy
import participant_info
from django.db import transaction
@transaction.commit_on_success
def close_participants(study_participants):
"""Sets now to be the study assignment end time, and puts them in UI/social condition"""
for study_participant in study_participants:
close_participant(study_participant)
def close_participant(study_participant):
all_assignments = StudyParticipantAssignment.objects.filter(study_participant = study_participant)
if all_assignments.count() != 2:
print (str(study_participant) + ' does not have two study assignments. skipping.') \
.encode('ascii', 'backslashreplace')
return
print ('closing study for ' + unicode(study_participant)).encode('ascii', 'backslashreplace')
current_assignment = all_assignments.order_by('-start_time')[0]
current_assignment.end_time = datetime.datetime.now()
current_assignment.save()
study_participant.user_interface = True
study_participant.social_features = True
study_participant.save()
if __name__ == "__main__":
user_emails = participant_info.people
study_participants = set()
for user_email in user_emails:
try:
participant = StudyParticipant.objects.get(sharer__user__email = user_email)
study_participants.add(participant)
except StudyParticipant.DoesNotExist:
print 'No study participant with e-mail ' + user_email
close_participants(study_participants)
| Python |
import commands
gsl_inc = commands.getoutput('gsl-config --prefix')+"/include"
gsl_libdir = commands.getoutput('gsl-config --prefix')+"/lib"
boost_inc = '/home/ke/usr/include'
boost_libdir = '/home/ke/usr/lib'
DefaultEnvironment(CPPPATH=["#", "#lib", "#classify", "#svmstruct", "#click", "#lowrank", boost_inc, gsl_inc],
CCFLAGS = '-O3 -Wall', CXXFLAGS = '-Wno-deprecated', LIBPATH=["#", boost_libdir, gsl_libdir], LIBS=['gsl', 'gslcblas', 'boost_iostreams-mt'])
matrices = ['#lib/matrices.cpp', '#lib/vectors.cpp']
cart = ['#cart.cpp', '#tree.cpp']
common = ['#rank_common.cpp']
Program('gbrank.exe', ['rank_gbrank.cpp']+matrices+cart+common)
Program('gbtree.exe', ['gbtree.cpp', 'rank_gbtree.cpp']+matrices+cart+common)
| Python |
#!/usr/bin/env python
import os, random
ran = random.Random()
#select n queries from query log
n = 100
line_number = int(os.popen('wc -l query_dist').read().split(' ')[0])
#print 'total number:', line_number
segment_size = line_number / n
#print 'segment size:', segment_size
def randomGet(list):
#random select a query from list without '.' in it
query = '.'
count = 0
while '.' in query:
count += 1
if count > 1000:
return query
query = list[ran.randint(0, len(list) - 1)]
return query
#out = open('selected_queries', 'w')
count = 0
list = []
for line in open('query_dist'):
count += 1
list.append(line.split('\t')[0])
if count == segment_size:
print randomGet(list)
#out.write('%s\n'%(randomGet(list)))
count = 0
list = []
#out.close()
| Python |
#!/usr/bin/env python
import os, gzip
with_clt = True
map = {}
for file in os.listdir('.'):
if file.endswith('.gz'):
print 'starts with file:', file
for line in gzip.open(file):
linebreak = line.split('\t')
if with_clt or linebreak[-1] == '\n':
query = linebreak[1]
if map.has_key(query):
map[query] += 1
else:
map[query] = 1
out = open('query_dist', 'w')
for record in sorted(map.items(), lambda x, y: cmp(y[1], x[1])):
out.write('%s\t%d\n'%record)
out.close()
| Python |
#!/usr/bin/env python
import os, gzip
with_clt = True
map = {}
for file in os.listdir('.'):
if file.endswith('.gz'):
print 'starts with file:', file
for line in gzip.open(file):
linebreak = line.split('\t')
if with_clt or linebreak[-1] == '\n':
query = linebreak[1]
if map.has_key(query):
map[query] += 1
else:
map[query] = 1
out = open('query_dist', 'w')
for record in sorted(map.items(), lambda x, y: cmp(y[1], x[1])):
out.write('%s\t%d\n'%record)
out.close()
| Python |
#!/usr/bin/env python
import os, random
ran = random.Random()
#select n queries from query log
n = 100
line_number = int(os.popen('wc -l query_dist').read().split(' ')[0])
#print 'total number:', line_number
segment_size = line_number / n
#print 'segment size:', segment_size
def randomGet(list):
#random select a query from list without '.' in it
query = '.'
count = 0
while '.' in query:
count += 1
if count > 1000:
return query
query = list[ran.randint(0, len(list) - 1)]
return query
#out = open('selected_queries', 'w')
count = 0
list = []
for line in open('query_dist'):
count += 1
list.append(line.split('\t')[0])
if count == segment_size:
print randomGet(list)
#out.write('%s\n'%(randomGet(list)))
count = 0
list = []
#out.close()
| Python |
#parse kv file, returns [ (K, V), ...]
def parseKVList(f):
lines = [x.strip() for x in open(f) if x.strip() != '']
return [x.split('\t') for x in lines]
import threading
class CommandThread(threading.Thread):
def __init__(self, commandline, outfile):
threading.Thread.__init__(self)
self.commandline = commandline
self.outfile = outfile
def run(self):
import subprocess
out = open(self.outfile + '.out', 'w')
err = open(self.outfile + '.err', 'w')
pipe = subprocess.Popen(
self.commandline,
stdout = out,
stderr = err,
shell = True
)
pipe.wait()
out.close()
err.close()
if __name__ == '__main__':
import sys
import getopt
optlist, args = getopt.getopt(sys.argv[1:], 'l:d:c:o:')
machinelist = ''
dependency = ''
commandline = 'echo hello world!'
outdir = 'outdir'
for k, v in optlist:
if k == '-l':
machinelist = v
elif k == '-d':
dependency = v
elif k == '-c':
commandline = v
elif k == '-o':
outdir = v
import os
os.system('mkdir ' + outdir)
if machinelist == '':
print 'usage: prog -l machinelist [-d dependency] [-c commandline] [-o outdir]'
exit()
#parse machinelist
print 'parsing machine list'
machines = parseKVList(machinelist)
print machines
if len(machines) > 0 and len(machines[0]) == 1:
machines = [(x[0], '') for x in machines]
print 'machine\textra_params'
for m, p in machines:
print m + '\t' + p
print
#processing dependency
if dependency != '':
dependencies = parseKVList(dependency)
for f, t in dependencies:
print f + ' => ' + t
threads = []
for m, p in machines:
threads.append(
CommandThread(
'rsync -rv --size-only %s %s:%s' % (f, m , t),
outdir + '/' + m + '.rsync'
)
)
for th in threads:
th.start()
while True:
print
flag = False
for th in threads:
if th.isAlive():
flag = True
print th.commandline, ' Alive'
if not flag:
break
import time
time.sleep(5)
#executing command
threads = []
for m, p in machines:
threads.append(CommandThread('''ssh %s "%s %s"''' % (m, commandline, p), outdir + '/' + m))
for th in threads:
th.start()
while True:
print
flag = False
for th in threads:
if th.isAlive():
flag = True
print th.commandline, ' Alive'
if not flag:
break
import time
time.sleep(5)
| Python |
# -*- Python -*-
# Copyright 2008 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
# or its licensors, as applicable.
#
# You may not use this file except under the terms of the accompanying license.
#
# 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.
#
# Project: iulib - the open source image understanding library
# File: SConstruct
# Purpose: building iulib
# Responsible: kofler
# Reviewer:
# Primary Repository: http://iulib.googlecode.com/svn/trunk/
# Web Sites: www.iupr.org, www.dfki.de
# hints for make users
#
# make all = scons
# install = scons install
# clean = scons -c
# uninstall = scons -c install
EnsureSConsVersion(0,97)
import glob,os,sys,string,re
### Options exposed via SCons
opts = Variables('custom.py')
opts.Add('opt', 'Compiler flags for optimization/debugging', "-g -O3 -fPIC")
opts.Add('warn', 'Compiler flags for warnings', "-Wall -D__warn_unused_result__=__far__")
opts.Add('prefix', 'The installation root for iulib', "/usr/local")
opts.Add(BoolVariable('sdl', "provide SDL-based graphics routines", "yes"))
opts.Add(BoolVariable('vidio', "provide video I/O functionality", "no"))
opts.Add(BoolVariable('v4l2', "provide v4l2 functionality", "no"))
opts.Add(BoolVariable('test', "Run some tests after the build", "no"))
# opts.Add(BoolVariable('style', 'Check style', "no"))
env = Environment(options=opts, CXXFLAGS=["${opt}","${warn}"])
Help(opts.GenerateHelpText(env))
conf = Configure(env)
if "-DUNSAFE" in env["opt"]:
print "WARNING: compile with -DUNSAFE or high optimization only for production use"
if re.search(r'-O[234]',env["opt"]):
print "compiling with high optimization"
else:
print "compiling for development (slower but safer)"
assert conf.CheckLibWithHeader('png', 'png.h', 'C', 'png_byte;', 1),"please install: libpng12-dev"
assert conf.CheckLibWithHeader('jpeg', 'jconfig.h', 'C', 'jpeg_std_error();', 1),"please install: libjpeg62-dev"
assert conf.CheckLibWithHeader('tiff', 'tiff.h', 'C', 'TIFFHeader;', 1), "please install: libtiff4-dev"
### check for optional parts
if env["sdl"]:
have_sdl = conf.CheckCXXHeader("SDL/SDL_gfxPrimitives.h") and \
conf.CheckCXXHeader("SDL/SDL.h")
assert have_sdl,"SDL requested, but can't find it"
else:
have_sdl = 0
if env["vidio"]:
have_vidio = conf.CheckCXXHeader("libavcodec/avcodec.h") and \
conf.CheckCXXHeader("libavformat/avformat.h")
assert have_vidio,"vidio requested, but can't find it"
else:
have_vidio = 0
if env["v4l2"]:
have_v4l2 = conf.CheckHeader("linux/videodev2.h")
assert have_v4l2,"v4l2 requested, but can't find it"
else:
have_v4l2 = 0
conf.Finish()
### install folders
prefix = "${prefix}"
incdir_iulib = prefix+"/include/iulib"
incdir_colib = prefix+"/include/colib"
libdir = prefix+"/lib"
datadir = prefix+"/share/iulib"
bindir = prefix+"/bin"
### collect sources etc.
env.Prepend(CPPPATH=[".","colib","imglib","imgio","imgbits","utils","components","vidio"])
sources = glob.glob("imglib/img*.cc")
sources += glob.glob("imgbits/img*.cc")
sources += """
imgio/autoinvert.cc imgio/imgio.cc imgio/io_jpeg.cc
imgio/io_pbm.cc imgio/io_png.cc imgio/io_tiff.cc
components/components.cc
""".split()
if have_vidio:
sources += glob.glob("vidio/vidio.cc")
if have_v4l2:
sources += glob.glob("vidio/v4l2cap.cc")
env.Append(LIBS=["v4l2"])
if have_sdl:
sources += ["utils/dgraphics.cc","utils/SDL_lines.cc"]
env.Append(LIBS=["SDL","SDL_gfx","SDL_image"])
else:
sources += ["utils/dgraphics_nosdl.cc"]
libiulib = env.SharedLibrary('libiulib',sources)
env.Append(CXXFLAGS=['-g','-fPIC'])
env.Append(LIBPATH=['.'])
progs = env.Clone()
progs.Append(LIBS=libiulib)
for file in glob.glob("commands/*.cc"):
progs.Program(file[:-3],file)
if have_vidio:
progs.Program("vidio/test-vidio","vidio/test-vidio.cc")
progs.Append(LIBS=["avformat","avcodec"])
if 0 and have_v4l2:
progs.Program("vidio/test-vidcap","vidio/test-vidcap.cc")
env.Install(libdir,libiulib)
for header in glob.glob("*/*.h"):
if "colib/" in header:
env.Install(incdir_colib,header)
else:
env.Install(incdir_iulib,header)
env.Alias('install',[libdir,incdir_iulib,incdir_colib])
test_builder = Builder(action='$SOURCE&&touch $TARGET',
suffix = '.passed',
src_suffix = '')
progs.Append(BUILDERS={'Test':test_builder})
if env["test"]:
for file in glob.glob("*/test-*.cc") + glob.glob("*/*/test-*.cc"):
if not file.startswith('vidio'):
progs.Program(file[:-3],file)
progs.Test(file[:-3])
progs.Alias("test",file[:-3]+".passed")
| Python |
#!/usr/bin/python
# Copyright 2007 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
# or its licensors, as applicable.
#
# You may not use this file except under the terms of the accompanying license.
#
# 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.
#
# Project:
# File:
# Purpose: simple style checker (run from top of project)
# Responsible: tmb
# Reviewer:
# Primary Repository:
# Web Sites: www.iupr.org, www.dfki.de
# FIXME add checks for include file ordering
# FIXME add checks for function length
import os,re,getopt,sys
from os.path import join, getsize
optlist,args = getopt.getopt(sys.argv[1:],'hcsdfor:e:')
options = {}
for k,v in optlist: options[k] = v
linelength = options.has_key("-l")
deprecation = options.has_key("-d")
fixmes = not options.has_key("-f")
suppress = options.has_key("-s")
copyright = options.has_key("-c")
oldstyle = options.has_key("-o")
want_author = options.get("-r",None)
if want_author: want_author = want_author.lower()
want_svnauthor = options.get("-e",None)
if want_svnauthor: want_author = want_svnauthor.lower()
help = """
usage: %s [-c] [-s] [-f] [-o] [-r responsible] [-e last_edited_by] dir...
-l: line length
-c: missing headers/copyrights
-f: FIXME lines
-o: old style C comments
-d: deprecation
-s: report problems despite suppress warning directives (CODE-OK--username)
-r: name: report problems only for files with Responsible: name
-e: name: report problems only for files last checked in by name
(Some options turn on a feature, others turn it off.)
""" %sys.argv[0]
if options.has_key("-h"):
sys.stderr.write(help)
sys.exit(0)
if args==[]:
args = ["."]
for arg in args:
if not os.path.isdir(arg):
sys.stderr.write("%s: not a directory\n"%arg)
sys.stderr.write("\n")
sys.stderr.write(help)
sys.exit(1)
author = None
svnauthor = None
def warn(file,line,message):
print "%s:%d:%s [resp: %s, edit: %s]"%(file,line,message,author,svnauthor)
warned = {}
def warnonce(file,line,message):
if warned.get(file,None): return
warned[file] = 1
print "%s:%d:%s [resp: %s, edit: %s]"%(file,line,message,author,svnauthor)
def check(arg):
global author
global svnauthor
for root,dirs,files in os.walk(arg):
if re.search(r'(/.svn|/EXTERNAL|/ext|/doc|/data|/CLEAN-ME-UP|/.deps)(/|$)',root): continue
if root is '.':
for d in dirs:
if d.startswith('img') or d=='vidio' or d=='colib' or d=="utils":
check(d)
break
#print "checking", root
sources = [file for file in files if re.search("\.(c|cc|cpp|pkg|h)$",file)]
for source in sources:
if re.search(r'(^|/)(test|try|#|.)-',source): continue
if source=="version.cc": continue
path = os.path.join(root,source)
author = None
svnauthor = None
# we do check for english output of svn info
# hence we need to ensure we get it
info = os.popen("LANG=C svn info '%s' 2>&1"%path).read(10000)
m = re.search(r'Last Changed Author:\s+(\S+)',info)
if m: svnauthor = m.group(1)
if os.path.isdir(".svn") and svnauthor==None: continue
if svnauthor: svnauthor = svnauthor.lower()
if want_svnauthor and want_svnauthor!=svnauthor: continue
info = open(path).read(10000)
m = re.search(r'Responsible:\s+([a-zA-Z0-9_-]+)',info)
if m: author = m.group(1).lower()
if want_author and want_author!=author: continue
lnumber = 0
stream = open(path,"r")
copyright = 0
includeguard = 0
includeguard_name = "###"
modeline = 0
info_responsible = 0
for line in stream.readlines():
lnumber += 1
if fixmes:
m = re.search(r'FIXME.*',line)
if m: warn(path,lnumber,m.group(0))
if not deprecation:
m = re.search(r'#if.*DEPRECATE.*',line)
if m: warn(path,lnumber,m.group(0))
m = re.search(r'DEPRECATE *;',line)
if m: warn(path,lnumber,m.group(0))
if not suppress:
if re.search(r'CODE-OK--[a-z]+',line): continue
# formatting
if linelength and len(line)>132:
warn(path,lnumber,"line too long")
if re.search(r'^\s+#',line):
warn(path,lnumber,"preprocessor directive doesn't start at beginning")
if "\t" in line:
warnonce(path,lnumber,'file contains tabs')
# C++ style
if oldstyle:
if not re.search(r'\.pkg$',source) and (re.search(r'^\s*/\*[^*]',line) or re.search(r'^( | )\* ',line)):
warn(path,lnumber,"old style comment")
if re.search(r'^\s*#if\s+0',line):
warnonce(path,lnumber,"dead code")
if re.search(r'^\s*#if\s*\(\s*0\s*\)',line):
warnonce(path,lnumber,"dead code")
if re.search(r'^( | | | | | )({|if|for|while|void|int|float|})',line):
warnonce(path,lnumber,"wrong indentation (should be multiple of 4)")
if re.search(r'[a-z0-9]+\s+\(.*,(?i)',line) and \
re.search(r'^ ',line) and \
not re.search(r'//|"|/\*|printf|\b(if|for|return|while|sizeof)\b',line):
warn(path,lnumber,'space before argument list')
if re.search(r'template\s*[<].*\(.*\).*\{',line):
warn(path,lnumber,'template on same line as function definition')
# headers
if re.search(r'-\*- C\+\+ -\*-',line): modeline = 1
if re.search(r'^\s*#include.*<string>',line): warn(path,lnumber,'consider using strbuf instead of string')
elif re.search(r'^\s*#include.*<limits>',line): warn(path,lnumber,'consider using C99 equivalent')
elif re.search(r'^\s*#include.*<[a-z]*stream>',line): warn(path,lnumber,'use stdio instead of iostream')
elif re.search(r'^\s*#include.*<[a-z]+>',line): warn(path,lnumber,'C++ library reference')
if re.search(r'Copyright [0-9]+ Deutsches Forschungszentrum',line): copyright |= 1
if re.search(r'You may not use this file except under the terms of the accompanying license',line): copyright |= 2
if re.search(r'WITHOUT WARRANTIES',line): copyright |= 4
m = re.search(r'Responsible: (\S*)',line)
if m:
responsible = m.group(1)
if not re.match(r'[a-z][a-z](?i)',responsible):
warnonce(path,lnumber,'no responsible author')
info_responsible = 1
m = re.search(r'#ifndef\s+([a-zA-Z0-9_]+)',line)
if m:
includeguard |= 1
includeguard_name = m.group(1)
if re.search(r'#define\s+'+includeguard_name,line):
includeguard |= 2
stream.close()
if not copyright:
if copyright!=7:
warn(path,1,'insufficient copyright header')
elif not info_responsible:
warn(path,1,'no Responsible: header')
if re.search(r'\.h$',path) and includeguard!=3: warn(path,1,'missing include guard')
for arg in args:
check(arg)
print "all checks completed"
| Python |
#!/usr/bin/python
import glob, os, string as s
print """# Copyright 2008 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
# or its licensors, as applicable.
#
# You may not use this file except under the terms of the accompanying license.
#
# 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.
#
# Project: iulib -- image understanding library
# File: Makefile.am
# Purpose: building iulib
# Responsible: kofler
# Reviewer:
# Primary Repository: http://ocropus.googlecode.com/svn/trunk/
# Web Sites: www.iupr.org, www.dfki.de
AM_CPPFLAGS = -I$(srcdir)/colib -I$(srcdir)/imgio -I$(srcdir)/imglib -I$(srcdir)/imgbits -I$(srcdir)/vidio -I$(srcdir)/utils
includedir = ${prefix}/include/iulib
colibdir = ${prefix}/include/colib
lib_LIBRARIES = libiulib.a
"""
dirs = """
imgio
imglib
imgbits
""".split()
print "libiulib_a_SOURCES = ",
for d in dirs:
print '\\'
for cc in glob.glob(d + "/*.cc"):
if os.path.basename(cc).startswith("test-"): continue
print "$(srcdir)/" + cc,
print
print
print "include_HEADERS = ",
for d in dirs:
print '\\'
for h in glob.glob(d + "/*.h"):
print "$(srcdir)/" + h,
print
print "include_HEADERS += $(srcdir)/utils/dgraphics.h"
print
print "colib_HEADERS = \\"
for h in glob.glob("colib/*.h"):
print "$(srcdir)/" + h,
print
print
# gather all test-* files
tests = glob.glob("colib/tests/test-*.cc")
for d in dirs:
tests += glob.glob(d +"/test-*.cc")
tests += glob.glob(d + "/tests/test-*.cc")
#name the resulting binaries (strip folder and suffix)
print "check_PROGRAMS = " + s.join(" " + os.path.basename(t)[:-3] for t in tests)
for t in tests:
tName = os.path.basename(t)[:-3].replace('-','_')
print tName + "_SOURCES = $(srcdir)/" + t
print tName + "_LDADD = libiulib.a"
print tName + "_CPPFLAGS = -I$(srcdir)/colib -I$(srcdir)/imgio -I$(srcdir)/imglib -I$(srcdir)/imgbits -I$(srcdir)/vidio -I$(srcdir)/utils"
print """
# conditionals
if have_sdl
libiulib_a_SOURCES += $(srcdir)/utils/dgraphics.cc
libiulib_a_SOURCES += $(srcdir)/utils/SDL_lines.cc
include_HEADERS += $(srcdir)/utils/SDL_lines.h
else
libiulib_a_SOURCES += $(srcdir)/utils/dgraphics_nosdl.cc
endif
if have_vidio
libiulib_a_SOURCES += $(srcdir)/vidio/vidio.cc
endif
# We install it always because iulib.h always includes it.
include_HEADERS += $(srcdir)/vidio/vidio.h
if have_v4l2
libiulib_a_SOURCES += $(srcdir)/vidio/v4l2cap.cc
endif
# make installation of colib a separate target
install-colib:
install -d -m 0755 $(DESTDIR)$(colibdir)
install -m 0644 $(colib_HEADERS) $(DESTDIR)$(colibdir)
install: all install-colib
install -d -m 0755 $(DESTDIR)$(includedir)
install -d -m 0755 $(DESTDIR)$(libdir)
install -m 0644 $(include_HEADERS) $(DESTDIR)$(includedir)
install -m 0644 $(lib_LIBRARIES) $(DESTDIR)$(libdir)
"""
print
print "check:"
print ' @echo "# running tests"'
for t in tests:
print " $(srcdir)/" + os.path.basename(t)[:-3]
| Python |
#!/usr/bin/python
# Copyright 2008 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
# or its licensors, as applicable.
#
# You may not use this file except under the terms of the accompanying license.
#
# 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.
#
# Project:
# File: check-am.py
# Purpose: identify files which are not handled in OCRopus automake
# Responsible: kofler
# Reviewer:
# Primary Repository:
# Web Sites: www.iupr.org, www.dfki.de
import os, sys, glob
if not os.path.exists('Makefile.am'):
print >> sys.stderr
print >> sys.stderr, "Makefile.am not found!"
print >> sys.stderr
def output(files, kind=""):
"""
Produce some helpful output for maintaining automake
"""
if len(files) > 0:
print
print "These", kind, "files are not handled:"
for src in files:
print src
print "---"
else:
print
print "OK, all", kind, "files are handled."
# get all cc and h files
ccs = []
for d in ["imgio","imglib","imgbits","utils"]:
ccs += glob.glob(d+"/*.cc")
hs = []
for d in ["colib","imgbits","imglib","imgio","utils"]:
hs += glob.glob(d+"/*.h")
# read automake file
amfile = open('Makefile.am')
am = amfile.read()
amfile.close()
# identify missing cc files, also mains and tests
missingccs = []
missingmains = []
missingtests = []
for src in ccs:
if src not in am:
if "main-" in src:
missingmains.append(src)
elif "test-" in src:
missingtests.append(src)
else:
missingccs.append(src)
# identify missing h files
missinghs = []
for h in hs:
if h not in am:
missinghs.append(h)
print
print "Please remember: This script only checks if files are handled at all."
print "It does NOT check whether they are handled correctly!"
# output maintainance information for cc, h, main- and test- files
output(missingccs, "cc")
output(missinghs, "h")
output(missingmains, "main")
#output(missingtests, "test")
#print "dirs", dirs
#print "ccs", ccs
#print "hs", hs
#print am
| Python |
#!/usr/bin/python2.5
# Copyright 2009-2010 by Ka-Ping Yee
#
# 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.
"""An interactive Python console connected to an app's datastore.
Instead of running this script directly, use the 'console' shell script,
which sets up the PYTHONPATH and other necessary environment variables."""
import code
import getpass
import logging
import optparse
import os
import sys
import urllib
import yaml
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
# Make some useful environment variables available.
APP_DIR = os.environ['APP_DIR']
APPENGINE_DIR = os.environ['APPENGINE_DIR']
PROJECT_DIR = os.environ['PROJECT_DIR']
TOOLS_DIR = os.environ['TOOLS_DIR']
# Set up more useful representations, handy for interactive data manipulation
# and debugging. Unfortunately, the App Engine runtime relies on the specific
# output of repr(), so this isn't safe in production, only debugging.
def key_repr(key):
levels = []
while key:
levels.insert(0, '%s %s' % (key.kind(), key.id() or repr(key.name())))
key = key.parent()
return '<Key: %s>' % '/'.join(levels)
db.Key.__repr__ = key_repr
def model_repr(model):
if model.is_saved():
key = model.key()
return '<%s: %s>' % (key.kind(), key.id() or repr(key.name()))
else:
return '<%s: unsaved>' % model.kind()
db.Model.__repr__ = model_repr
def get_app_id():
"""Gets the app_id from the app.yaml configuration file."""
return yaml.safe_load(open(APP_DIR + '/app.yaml'))['application']
def connect(server, app_id=None, username=None, password=None):
"""Sets up a connection to an app that has the remote_api handler."""
if not app_id:
app_id = get_app_id()
print 'Application ID: %s' % app_id
print 'Server: %s' % server
if not username:
username = raw_input('Username: ')
else:
print 'Username: %s' % username
# Sets up users.get_current_user() inside of the console
os.environ['USER_EMAIL'] = username
if not password:
password = getpass.getpass('Password: ')
remote_api_stub.ConfigureRemoteDatastore(
app_id, '/remote_api', lambda: (username, password), server)
db.Query().count() # force authentication to happen now
if __name__ == '__main__':
default_address = 'localhost'
default_port = 8080
default_app_id = get_app_id()
parser = optparse.OptionParser(usage='''%%prog [options] [server]
Starts an interactive console connected to an App Engine datastore.
The [server] argument is a shorthand for setting the hostname, port
number, and application ID. For example:
%%prog xyz.appspot.com # uses port 80, app ID 'xyz'
%%prog localhost:6789 # uses port 6789, app ID %r''' % default_app_id)
parser.add_option('-a', '--address',
help='appserver hostname (default: localhost)')
parser.add_option('-p', '--port', type='int',
help='appserver port number (default: 8080)')
parser.add_option('-A', '--application',
help='application ID (default: %s)' % default_app_id)
parser.add_option('-u', '--username',
help='username (in the form of an e-mail address)')
parser.add_option('-c', '--command',
help='Python commands to execute')
options, args = parser.parse_args()
# Handle shorthand for address, port number, and app ID.
if args:
default_address, default_port = urllib.splitport(args[0])
default_port = int(default_port or 80)
if default_address != 'localhost':
default_app_id = default_address.split('.')[0]
# Apply defaults. (We don't use optparse defaults because we want to let
# explicit settings override our defaults.)
address = options.address or default_address
port = options.port or default_port
app_id = options.application or default_app_id
username = options.username
password = None
# Use a dummy password when connecting to a development app server.
if address == 'localhost':
password = 'foo'
logging.basicConfig(file=sys.stderr, level=logging.INFO)
connect('%s:%d' % (address, port), app_id, username, password)
if options.command:
exec options.command
else:
code.interact('', None, locals())
| Python |
#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
# Copyright 2010 Joe LaPenna
#
# 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.
#
"""Latitude OAuth client."""
import oauth
import oauth_appengine
class LatitudeOAuthClient(oauth_appengine.OAuthClient):
"""Latitude-specific OAuth client.
Per: http://code.google.com/apis/gdata/articles/oauth.html
"""
REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
AUTHORIZATION_URL = \
'https://www.google.com/latitude/apps/OAuthAuthorizeToken'
SCOPE = 'https://www.googleapis.com/auth/latitude'
def __init__(self, oauth_consumer=None, oauth_token=None):
super(LatitudeOAuthClient, self).__init__(
oauth_consumer=oauth_consumer,
oauth_token=oauth_token,
request_token_url=LatitudeOAuthClient.REQUEST_TOKEN_URL,
access_token_url=LatitudeOAuthClient.ACCESS_TOKEN_URL,
authorization_url=LatitudeOAuthClient.AUTHORIZATION_URL)
self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
class Latitude(object):
"""API access to Latitude."""
REST_URL = 'https://www.googleapis.com/latitude/v1/%s'
def __init__(self, oauth_client):
self.client = oauth_client
def get_current_location(self):
request = oauth.OAuthRequest.from_consumer_and_token(
self.client.get_consumer(),
token=self.client.get_token(),
http_method='GET',
http_url=Latitude.REST_URL % ('currentLocation',),
parameters={'granularity': 'best'})
request.sign_request(
self.client.signature_method,
self.client.get_consumer(),
self.client.get_token())
return self.client.access_resource(request)
| Python |
# Copyright 2010 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.
"""Steps of the OAuth dance implemented for the webapp framework."""
__author__ = 'Ka-Ping Yee <kpy@google.com>'
import oauth
import oauth_appengine
def redirect_to_authorization_page(
handler, oauth_client, callback_url, parameters):
"""Sends the user to an OAuth authorization page."""
# Get a request token.
helper = oauth_appengine.OAuthDanceHelper(oauth_client)
request_token = helper.GetRequestToken(callback_url, parameters)
# Save the request token in cookies so we can pick it up later.
handler.response.headers.add_header(
'Set-Cookie', 'request_key=' + request_token.key)
handler.response.headers.add_header(
'Set-Cookie', 'request_secret=' + request_token.secret)
# Send the user to the authorization page.
handler.redirect(
helper.GetAuthorizationRedirectUrl(request_token, parameters))
def handle_authorization_finished(handler, oauth_client):
"""Handles a callback from the OAuth authorization page and returns
a freshly minted access token."""
# Pick up the request token from the cookies.
request_token = oauth.OAuthToken(
handler.request.cookies['request_key'],
handler.request.cookies['request_secret'])
# Upgrade our request token to an access token, using the verifier.
helper = oauth_appengine.OAuthDanceHelper(oauth_client)
access_token = helper.GetAccessToken(
request_token, handler.request.get('oauth_verifier', None))
# Clear the cookies that contained the request token.
handler.response.headers.add_header('Set-Cookie', 'request_key=')
handler.response.headers.add_header('Set-Cookie', 'request_secret=')
return access_token
| Python |
# Copyright 2010 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.
"""A simple app that performs the OAuth dance and makes a Latitude request."""
__author__ = 'Ka-Ping Yee <kpy@google.com>'
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
import latitude
import oauth
import oauth_webapp
OAUTH_CALLBACK_PATH = '/oauth_callback'
# To set up this application as an OAuth consumer:
# 1. Go to https://www.google.com/accounts/ManageDomains
# 2. Follow the instructions to register and verify your domain
# 3. The administration page for your domain should now show an "OAuth
# Consumer Key" and "OAuth Consumer Secret". Put these values into
# the app's datastore by calling Config.set('oauth_consumer_key', ...)
# and Config.set('oauth_consumer_secret', ...).
class Config(db.Model):
value = db.StringProperty()
@staticmethod
def get(name):
config = Config.get_by_key_name(name)
return config and config.value
@staticmethod
def set(name, value):
Config(key_name=name, value=value).put()
oauth_consumer = oauth.OAuthConsumer(
Config.get('oauth_consumer_key'), Config.get('oauth_consumer_secret'))
class Main(webapp.RequestHandler):
"""This main page immediately redirects to the OAuth authorization page."""
def get(self):
parameters = {
'scope': latitude.LatitudeOAuthClient.SCOPE,
'domain': Config.get('oauth_consumer_key'),
'granularity': 'best',
'location': 'all'
}
oauth_webapp.redirect_to_authorization_page(
self, latitude.LatitudeOAuthClient(oauth_consumer),
self.request.host_url + OAUTH_CALLBACK_PATH, parameters)
class LatitudeOAuthCallbackHandler(webapp.RequestHandler):
"""After the user gives permission, the user is redirected back here."""
def get(self):
access_token = oauth_webapp.handle_authorization_finished(
self, latitude.LatitudeOAuthClient(oauth_consumer))
# Request the user's location
client = latitude.LatitudeOAuthClient(oauth_consumer, access_token)
result = latitude.Latitude(client).get_current_location()
self.response.out.write('Your location is: ' + result.content)
if __name__ == '__main__':
run_wsgi_app(webapp.WSGIApplication([
('/', Main),
(OAUTH_CALLBACK_PATH, LatitudeOAuthCallbackHandler)
]))
| Python |
"""
The MIT License
Copyright (c) 2007 Leah Culver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import cgi
import urllib
import time
import random
import urlparse
import hmac
import binascii
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class OAuthError(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occured.'):
self.message = message
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s, safe='~')
def _utf8_str(s):
"""Convert unicode to utf-8."""
if isinstance(s, unicode):
return s.encode("utf-8")
else:
return str(s)
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class OAuthConsumer(object):
"""Consumer of OAuth authentication.
OAuthConsumer is a data type that represents the identity of the Consumer
via its shared secret with the Service Provider.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
class OAuthToken(object):
"""A data type that represents an End User via either an access
or request token.
key -- the token
secret -- the token secret
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
def __repr__(self):
return 'OAuthToken(%r, %r)' % (self.key, self.secret)
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
def from_string(s):
""" Returns a token from something like:
oauth_token_secret=xxx&oauth_token=xxx
"""
params = cgi.parse_qs(s, keep_blank_values=False)
key = params['oauth_token'][0]
secret = params['oauth_token_secret'][0]
token = OAuthToken(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
from_string = staticmethod(from_string)
def __str__(self):
return self.to_string()
class OAuthRequest(object):
"""OAuthRequest represents the request and can be serialized.
OAuth parameters:
- oauth_consumer_key
- oauth_token
- oauth_signature_method
- oauth_signature
- oauth_timestamp
- oauth_nonce
- oauth_version
- oauth_verifier
... any additional parameters, as defined by the Service Provider.
"""
parameters = None # OAuth parameters.
http_method = HTTP_METHOD
http_url = None
version = VERSION
def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None):
self.http_method = http_method
self.http_url = http_url
self.parameters = parameters or {}
def set_parameter(self, parameter, value):
self.parameters[parameter] = value
def get_parameter(self, parameter):
try:
return self.parameters[parameter]
except:
raise OAuthError('Parameter not found: %s' % parameter)
def _get_timestamp_nonce(self):
return self.get_parameter('oauth_timestamp'), self.get_parameter(
'oauth_nonce')
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
parameters = {}
for k, v in self.parameters.iteritems():
# Ignore oauth parameters.
if k.find('oauth_') < 0:
parameters[k] = v
return parameters
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
auth_header = 'OAuth realm="%s"' % realm
# Add the oauth parameters.
if self.parameters:
for k, v in self.parameters.iteritems():
if k[:6] == 'oauth_':
auth_header += ', %s="%s"' % (k, escape(str(v)))
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \
for k, v in self.parameters.iteritems()])
def to_url(self):
"""Serialize as a URL for a GET request."""
return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata())
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
params = self.parameters
try:
# Exclude the signature if it exists.
del params['oauth_signature']
except:
pass
# Escape key values before sorting.
key_values = [(escape(_utf8_str(k)), escape(_utf8_str(v))) \
for k,v in params.items()]
# Sort lexicographically, first after key, then after value.
key_values.sort()
# Combine key value pairs into a string.
return '&'.join(['%s=%s' % (k, v) for k, v in key_values])
def get_normalized_http_method(self):
"""Uppercases the http method."""
return self.http_method.upper()
def get_normalized_http_url(self):
"""Parses the URL and rebuilds it to be scheme://host/path."""
parts = urlparse.urlparse(self.http_url)
scheme, netloc, path = parts[:3]
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
return '%s://%s%s' % (scheme, netloc, path)
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of build_signature."""
# Set the signature method.
self.set_parameter('oauth_signature_method',
signature_method.get_name())
# Set the signature.
self.set_parameter('oauth_signature',
self.build_signature(signature_method, consumer, token))
def build_signature(self, signature_method, consumer, token):
"""Calls the build signature method within the signature method."""
return signature_method.build_signature(self, consumer, token)
def from_request(http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = OAuthRequest._split_header(auth_header)
parameters.update(header_params)
except:
raise OAuthError('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = OAuthRequest._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = OAuthRequest._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return OAuthRequest(http_method, http_url, parameters)
return None
from_request = staticmethod(from_request)
def from_consumer_and_token(oauth_consumer, token=None,
callback=None, verifier=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': oauth_consumer.key,
'oauth_timestamp': generate_timestamp(),
'oauth_nonce': generate_nonce(),
'oauth_version': OAuthRequest.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.callback:
parameters['oauth_callback'] = token.callback
# 1.0a support for verifier.
if verifier:
parameters['oauth_verifier'] = verifier
elif callback:
# 1.0a support for callback in the request token request.
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_consumer_and_token = staticmethod(from_consumer_and_token)
def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD,
http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return OAuthRequest(http_method, http_url, parameters)
from_token_and_callback = staticmethod(from_token_and_callback)
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
_split_header = staticmethod(_split_header)
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = cgi.parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
_split_url_string = staticmethod(_split_url_string)
class OAuthServer(object):
"""A worker to check the validity of a request against a data store."""
timestamp_threshold = 300 # In seconds, five minutes.
version = VERSION
signature_methods = None
data_store = None
def __init__(self, data_store=None, signature_methods=None):
self.data_store = data_store
self.signature_methods = signature_methods or {}
def set_data_store(self, data_store):
self.data_store = data_store
def get_data_store(self):
return self.data_store
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.get_name()] = signature_method
return self.signature_methods
def fetch_request_token(self, oauth_request):
"""Processes a request_token request and returns the
request token on success.
"""
try:
# Get the request token for authorization.
token = self._get_token(oauth_request, 'request')
except OAuthError:
# No token required for the initial token request.
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
callback = self.get_callback(oauth_request)
except OAuthError:
callback = None # 1.0, no callback specified.
self._check_signature(oauth_request, consumer, None)
# Fetch a new token.
token = self.data_store.fetch_request_token(consumer, callback)
return token
def fetch_access_token(self, oauth_request):
"""Processes an access_token request and returns the
access token on success.
"""
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
try:
verifier = self._get_verifier(oauth_request)
except OAuthError:
verifier = None
# Get the request token.
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
new_token = self.data_store.fetch_access_token(
consumer, token, verifier)
return new_token
def verify_request(self, oauth_request):
"""Verifies an api call and checks all the parameters."""
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# Get the access token.
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
parameters = oauth_request.get_nonoauth_parameters()
return consumer, token, parameters
def authorize_token(self, token, user):
"""Authorize a request token."""
return self.data_store.authorize_request_token(token, user)
def get_callback(self, oauth_request):
"""Get the callback URL."""
return oauth_request.get_parameter('oauth_callback')
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _get_version(self, oauth_request):
"""Verify the correct version request for this server."""
try:
version = oauth_request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise OAuthError('OAuth version %s not supported.' % str(version))
return version
def _get_signature_method(self, oauth_request):
"""Figure out the signature with some defaults."""
try:
signature_method = oauth_request.get_parameter(
'oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise OAuthError('Signature method %s not supported try one of the '
'following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_consumer(self, oauth_request):
consumer_key = oauth_request.get_parameter('oauth_consumer_key')
consumer = self.data_store.lookup_consumer(consumer_key)
if not consumer:
raise OAuthError('Invalid consumer.')
return consumer
def _get_token(self, oauth_request, token_type='access'):
"""Try to find the token for the provided request token key."""
token_field = oauth_request.get_parameter('oauth_token')
token = self.data_store.lookup_token(token_type, token_field)
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token
def _get_verifier(self, oauth_request):
return oauth_request.get_parameter('oauth_verifier')
def _check_signature(self, oauth_request, consumer, token):
timestamp, nonce = oauth_request._get_timestamp_nonce()
self._check_timestamp(timestamp)
self._check_nonce(consumer, token, nonce)
signature_method = self._get_signature_method(oauth_request)
try:
signature = oauth_request.get_parameter('oauth_signature')
except:
raise OAuthError('Missing signature.')
# Validate the signature.
valid_sig = signature_method.check_signature(
oauth_request, consumer, token, signature)
if not valid_sig:
key, base = signature_method.build_signature_base_string(
oauth_request, consumer, token)
raise OAuthError('Invalid signature. Expected signature base '
'string: %s' % base)
built = signature_method.build_signature(
oauth_request, consumer, token)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = abs(now - timestamp)
if lapsed > self.timestamp_threshold:
raise OAuthError(
'Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' %
(timestamp, now, self.timestamp_threshold))
def _check_nonce(self, consumer, token, nonce):
"""Verify that the nonce is uniqueish."""
nonce = self.data_store.lookup_nonce(consumer, token, nonce)
if nonce:
raise OAuthError('Nonce already used: %s' % str(nonce))
class OAuthClient(object):
"""OAuthClient is a worker to attempt to execute a request."""
consumer = None
token = None
def __init__(self, oauth_consumer, oauth_token):
self.consumer = oauth_consumer
self.token = oauth_token
def get_consumer(self):
return self.consumer
def get_token(self):
return self.token
def fetch_request_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_request):
"""-> OAuthToken."""
raise NotImplementedError
def access_resource(self, oauth_request):
"""-> Some protected resource."""
raise NotImplementedError
class OAuthDataStore(object):
"""A database abstraction used to lookup consumers and tokens."""
def lookup_consumer(self, key):
"""-> OAuthConsumer."""
raise NotImplementedError
def lookup_token(self, oauth_consumer, token_type, token_token):
"""-> OAuthToken."""
raise NotImplementedError
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_request_token(self, oauth_consumer, oauth_callback):
"""-> OAuthToken."""
raise NotImplementedError
def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
"""-> OAuthToken."""
raise NotImplementedError
def authorize_request_token(self, oauth_token, user):
"""-> OAuthToken."""
raise NotImplementedError
class OAuthSignatureMethod(object):
"""A strategy class that implements a signature method."""
def get_name(self):
"""-> str."""
raise NotImplementedError
def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token):
"""-> str key, str raw."""
raise NotImplementedError
def build_signature(self, oauth_request, oauth_consumer, oauth_token):
"""-> str."""
raise NotImplementedError
def check_signature(self, oauth_request, consumer, token, signature):
built = self.build_signature(oauth_request, consumer, token)
return built == signature
class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
def get_name(self):
return 'HMAC-SHA1'
def build_signature_base_string(self, oauth_request, consumer, token):
sig = (
escape(oauth_request.get_normalized_http_method()),
escape(oauth_request.get_normalized_http_url()),
escape(oauth_request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def build_signature(self, oauth_request, consumer, token):
"""Builds the base signature string."""
key, raw = self.build_signature_base_string(
oauth_request, consumer, token)
# HMAC object.
try:
import hashlib # 2.5
hashed = hmac.new(key, raw, hashlib.sha1)
except:
import sha # Deprecated
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod):
def get_name(self):
return 'PLAINTEXT'
def build_signature_base_string(self, oauth_request, consumer, token):
"""Concatenates the consumer key and secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def build_signature(self, oauth_request, consumer, token):
key, raw = self.build_signature_base_string(
oauth_request, consumer, token)
return key
| Python |
#!/usr/bin/env python
# Copyright 2009 Joe LaPenna
# Copyright 2009 Google
"""
An appengine OAuthClient based on the oauth-python reference implementation.
"""
import oauth
from google.appengine.api import urlfetch
from google.appengine.ext import db
class OAuthClient(oauth.OAuthClient):
"""A worker to attempt to execute a request (on appengine)."""
def __init__(self, oauth_consumer, oauth_token, request_token_url='',
access_token_url='', authorization_url=''):
super(OAuthClient, self).__init__(oauth_consumer, oauth_token)
self.request_token_url = request_token_url
self.access_token_url = access_token_url
self.authorization_url = authorization_url
def fetch_request_token(self, oauth_request):
"""-> OAuthToken."""
# Using headers or payload varies by service...
response = urlfetch.fetch(
url=self.request_token_url,
method=oauth_request.http_method,
#headers=oauth_request.to_header(),
payload=oauth_request.to_postdata())
return oauth.OAuthToken.from_string(response.content)
def fetch_access_token(self, oauth_request):
"""-> OAuthToken."""
response = urlfetch.fetch(
url=self.access_token_url,
method=oauth_request.http_method,
headers=oauth_request.to_header())
return oauth.OAuthToken.from_string(response.content)
def access_resource(self, oauth_request, deadline=None):
"""-> Some protected resource."""
if oauth_request.http_method == 'GET':
url = oauth_request.to_url()
return urlfetch.fetch(
url=url,
method=oauth_request.http_method)
else:
payload = oauth_request.to_postdata()
return urlfetch.fetch(
url=oauth_request.get_normalized_http_url(),
method=oauth_request.http_method,
payload=payload)
class OAuthDanceHelper(object):
def __init__(self, oauth_client):
self.oauth_client = oauth_client
def GetRequestToken(self, callback, parameters=None):
"""Gets a request token from an OAuth provider."""
request_token_request = oauth.OAuthRequest.from_consumer_and_token(
self.oauth_client.get_consumer(),
token=None,
callback=callback,
http_method='POST',
http_url=self.oauth_client.request_token_url,
parameters=parameters)
# Request a token that we can use to redirect the user to an auth url.
request_token_request.sign_request(
self.oauth_client.signature_method,
self.oauth_client.get_consumer(),
None)
return self.oauth_client.fetch_request_token(request_token_request)
def GetAuthorizationRedirectUrl(self, request_token, parameters=None):
"""Gets the redirection URL for the OAuth authorization page."""
authorization_request = oauth.OAuthRequest.from_token_and_callback(
request_token,
http_method='GET',
http_url=self.oauth_client.authorization_url,
parameters=parameters)
return authorization_request.to_url()
def GetAccessToken(self, request_token, verifier):
"""Upgrades a request token to an access token."""
access_request = oauth.OAuthRequest.from_consumer_and_token(
self.oauth_client.get_consumer(),
token=request_token,
verifier=verifier,
http_url=self.oauth_client.access_token_url)
access_request.sign_request(
self.oauth_client.signature_method,
self.oauth_client.get_consumer(),
request_token)
return self.oauth_client.fetch_access_token(access_request)
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import exceptions
class Error(exceptions.StandardError):
pass
class Warning(exceptions.StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class InternalError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class DataError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import errno
import logging
import re
import time
from net import gorpc
from vtdb import tablet2
from vtdb import dbexceptions
# NOTE(msolomon) this sketchy import allows upstream code to mostly interpret
# our exceptions as if they came from MySQLdb. Good for a cutover, probably
# bad long-term.
import MySQLdb as MySQLErrors
_errno_pattern = re.compile('\(errno (\d+)\)')
# NOTE(msolomon) This mapping helps us mimic the behavior of mysql errors
# even though the relationship between connections and failures is now quite
# different. In general, we map vtocc errors to DatabaseError, unless there
# is a pressing reason to be more precise. Otherwise, these errors can get
# misinterpreted futher up the call chain.
_mysql_error_map = {
1062: MySQLErrors.IntegrityError,
}
# Errors fall into three classes based on recovery strategy.
#
# APP_LEVEL is for routine programmer errors (bad input etc) -- nothing can be
# done here, so just propagate the error upstream.
#
# RETRY means a simple reconnect (and immediate) reconnect to the same
# host will likely fix things. This is usually due vtocc restarting. In general
# this can be handled transparently unless the error is within a transaction.
#
# FATAL indicates that retrying an action on the host is likely to fail.
ERROR_APP_LEVEL = 'app_level'
ERROR_RETRY = 'retry'
ERROR_FATAL = 'fatal'
RECONNECT_DELAY = 0.002
# simple class to trap and re-export only variables referenced from the sql
# statement. bind dictionaries can be *very* noisy.
# this is by-product of converting the mysql %(name)s syntax to vtocc :name
class BindVarsProxy(object):
def __init__(self, bind_vars):
self.bind_vars = bind_vars
self.accessed_keys = set()
def __getitem__(self, name):
self.bind_vars[name]
self.accessed_keys.add(name)
return ':%s' % name
def export_bind_vars(self):
return dict([(k, self.bind_vars[k]) for k in self.accessed_keys])
# Provide compatibility with the MySQLdb query param style and prune bind_vars
class VtOCCConnection(tablet2.TabletConnection):
max_attempts = 2
def dial(self):
tablet2.TabletConnection.dial(self)
try:
response = self.client.call('OccManager.GetSessionId', self.dbname)
self.set_session_id(response.reply)
except gorpc.GoRpcError, e:
raise dbexceptions.OperationalError(*e.args)
def _convert_error(self, exception, *error_hints):
message = str(exception[0]).lower()
# NOTE(msolomon) extract a mysql error code so we can push this up the code
# stack. At this point, this is almost exclusively for handling integrity
# errors from duplicate key inserts.
match = _errno_pattern.search(message)
if match:
err = int(match.group(1))
elif isinstance(exception[0], IOError):
err = exception[0].errno
else:
err = -1
if message.startswith('fatal'):
# Force this error code upstream so MySQL code understands this as a
# permanent failure on this host. Feels a little dirty, but probably the
# most consistent way since this correctly communicates the recovery
# strategy upstream.
raise MySQLErrors.OperationalError(2003, str(exception), self.addr,
*error_hints)
elif message.startswith('retry'):
# Retry means that a trivial redial of this host will fix things. This
# is frequently due to vtocc being restarted independently of the mysql
# instance behind it.
error_type = ERROR_RETRY
elif 'curl error 7' in message:
# Client side error - sometimes the listener is unavailable for a few
# milliseconds during a restart.
error_type = ERROR_RETRY
elif err in (errno.ECONNREFUSED, errno.EPIPE):
error_type = ERROR_RETRY
else:
# Everything else is app level - just process the failure and continue
# to use the existing connection.
error_type = ERROR_APP_LEVEL
if error_type == ERROR_RETRY and self.transaction_id:
# With a transaction, you cannot retry, so just redial. The next action
# will be successful. Masquerade as commands-out-of-sync - an operational
# error that can be reattempted at the app level.
error_type = ERROR_APP_LEVEL
error_hints += ('cannot retry action within a transaction',)
try:
time.sleep(RECONNECT_DELAY)
self.dial()
except Exception, e:
# If this fails now, the code will retry later as the session_id
# won't be valid until the handshake finishes.
logging.warning('error dialing vtocc %s (%s)', self.addr, e)
exc_class = _mysql_error_map.get(err, MySQLErrors.DatabaseError)
return error_type, exc_class(err, str(exception), self.addr,
*error_hints)
def begin(self):
attempt = 0
while True:
try:
return tablet2.TabletConnection.begin(self)
except dbexceptions.OperationalError, e:
error_type, e = self._convert_error(e, 'begin')
if error_type == ERROR_RETRY:
attempt += 1
if attempt < self.max_attempts:
try:
time.sleep(RECONNECT_DELAY)
self.dial()
except dbexceptions.OperationalError, dial_error:
logging.warning('error dialing vtocc on begin %s (%s)',
self.addr, dial_error)
continue
logging.warning('Failing with 2003 on begin')
raise MySQLErrors.OperationalError(2003, str(e), self.addr, 'begin')
raise e
def commit(self):
try:
return tablet2.TabletConnection.commit(self)
except dbexceptions.OperationalError, e:
error_type, e = self._convert_error(e, 'commit')
raise e
def _execute(self, sql, bind_variables):
bind_vars_proxy = BindVarsProxy(bind_variables)
try:
# convert bind style from %(name)s to :name
sql = sql % bind_vars_proxy
except KeyError, e:
raise dbexceptions.InterfaceError(e[0], sql, bind_variables)
sane_bind_vars = bind_vars_proxy.export_bind_vars()
attempt = 0
while True:
try:
return tablet2.TabletConnection._execute(self, sql, sane_bind_vars)
except dbexceptions.OperationalError, e:
error_type, e = self._convert_error(e, sql, sane_bind_vars)
if error_type == ERROR_RETRY:
attempt += 1
if attempt < self.max_attempts:
try:
time.sleep(RECONNECT_DELAY)
self.dial()
except dbexceptions.OperationalError, dial_error:
logging.warning('error dialing vtocc on execute %s (%s)',
self.addr, dial_error)
continue
logging.warning('Failing with 2003 on %s: %s, %s', str(e), sql, sane_bind_vars)
raise MySQLErrors.OperationalError(2003, str(e), self.addr, sql, sane_bind_vars)
raise e
def connect(addr, timeout, dbname=None):
conn = VtOCCConnection(addr, dbname, timeout)
conn.dial()
return conn
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""times module
This module provides some Date and Time interface for vtdb
Use Python datetime module to handle date and time columns."""
from datetime import date, datetime, time, timedelta
from math import modf
from time import localtime
# FIXME(msolomon) what are these aliasesf for?
Date = date
Time = time
TimeDelta = timedelta
Timestamp = datetime
DateTimeDeltaType = timedelta
DateTimeType = datetime
def DateFromTicks(ticks):
"""Convert UNIX ticks into a date instance."""
return date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
"""Convert UNIX ticks into a time instance."""
return time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
"""Convert UNIX ticks into a datetime instance."""
return datetime(*localtime(ticks)[:6])
def DateTimeOrNone(s):
if ' ' in s:
sep = ' '
elif 'T' in s:
sep = 'T'
else:
return DateOrNone(s)
try:
d, t = s.split(sep, 1)
return datetime(*[ int(x) for x in d.split('-')+t.split(':') ])
except:
return DateOrNone(s)
def TimeDeltaOrNone(s):
try:
h, m, s = s.split(':')
td = timedelta(hours=int(h), minutes=int(m), seconds=int(float(s)), microseconds=int(modf(float(s))[0]*1000000))
if h < 0:
return -td
else:
return td
except:
return None
def TimeOrNone(s):
try:
h, m, s = s.split(':')
return time(hour=int(h), minute=int(m), second=int(float(s)), microsecond=int(modf(float(s))[0]*1000000))
except:
return None
def DateOrNone(s):
try: return date(*[ int(x) for x in s.split('-',2)])
except: return None
def DateToString(d):
return d.strftime("%Y-%m-%d")
def DateTimeToString(dt):
return dt.strftime("%Y-%m-%d %H:%M:%S")
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from array import array
import datetime
from decimal import Decimal
from vtdb import times
# These numbers should exactly match values defined in dist/vt-mysql-5.1.52/include/mysql/mysql_com.h
VT_DECIMAL = 0
VT_TINY = 1
VT_SHORT = 2
VT_LONG = 3
VT_FLOAT = 4
VT_DOUBLE = 5
VT_NULL = 6
VT_TIMESTAMP = 7
VT_LONGLONG = 8
VT_INT24 = 9
VT_DATE = 10
VT_TIME = 11
VT_DATETIME = 12
VT_YEAR = 13
VT_NEWDATE = 14
VT_VARCHAR = 15
VT_BIT = 16
VT_NEWDECIMAL = 246
VT_ENUM = 247
VT_SET = 248
VT_TINY_BLOB = 249
VT_MEDIUM_BLOB = 250
VT_LONG_BLOB = 251
VT_BLOB = 252
VT_VAR_STRING = 253
VT_STRING = 254
VT_GEOMETRY = 255
# FIXME(msolomon) intended for MySQL emulation, but seems more dangerous
# to keep this around. This doesn't seem to even be used right now.
def Binary(x):
return array('c', x)
class DBAPITypeObject:
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
return 1
# FIXME(msolomon) why do we have these values if they aren't referenced?
STRING = DBAPITypeObject(VT_ENUM, VT_VAR_STRING, VT_STRING)
BINARY = DBAPITypeObject(VT_TINY_BLOB, VT_MEDIUM_BLOB, VT_LONG_BLOB, VT_BLOB)
NUMBER = DBAPITypeObject(VT_DECIMAL, VT_TINY, VT_SHORT, VT_LONG, VT_FLOAT, VT_DOUBLE, VT_LONGLONG, VT_INT24, VT_YEAR, VT_NEWDECIMAL)
DATETIME = DBAPITypeObject(VT_TIMESTAMP, VT_DATE, VT_TIME, VT_DATETIME, VT_NEWDATE)
ROWID = DBAPITypeObject()
conversions = {
VT_DECIMAL : Decimal,
VT_TINY : int,
VT_SHORT : int,
VT_LONG : long,
VT_FLOAT : float,
VT_DOUBLE : float,
VT_TIMESTAMP : times.DateTimeOrNone,
VT_LONGLONG : long,
VT_INT24 : int,
VT_DATE : times.DateOrNone,
VT_TIME : times.TimeDeltaOrNone,
VT_DATETIME : times.DateTimeOrNone,
VT_YEAR : int,
VT_NEWDATE : times.DateOrNone,
VT_BIT : int,
VT_NEWDECIMAL : Decimal,
}
NoneType = type(None)
# FIXME(msolomon) we could make a SqlLiteral ABC and just type check.
# That doens't seem dramatically better than __sql_literal__ but it might
# be move self-documenting.
def convert_bind_vars(bind_variables):
new_vars = {}
for key, val in bind_variables.iteritems():
if hasattr(val, '__sql_literal__'):
new_vars[key] = val.__sql_literal__()
elif isinstance(val, datetime.datetime):
new_vars[key] = times.DateTimeToString(val)
elif isinstance(val, datetime.date):
new_vars[key] = times.DateToString(val)
elif isinstance(val, (int, long, float, str, NoneType)):
new_vars[key] = val
else:
# NOTE(msolomon) begrudgingly I allow this - we just have too much code
# that relies on this.
# This accidentally solves our hideous dependency on mx.DateTime.
new_vars[key] = str(val)
return new_vars
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from net import mc_bson_request
from vtdb import dbexceptions
class BaseCursor(object):
arraysize = 1
lastrowid = None
rowcount = 0
results = None
connection = None
description = None
index = None
def __init__(self, connection):
self.connection = connection
def close(self):
self.connection = None
self.results = None
# pass kargs here in case higher level APIs need to push more data through
# for instance, a key value for shard mapping
def _execute(self, sql, bind_variables, **kargs):
self.rowcount = 0
self.results = None
self.description = None
self.lastrowid = None
sql_check = sql.strip().lower()
if sql_check == 'begin':
self.connection.begin()
return
elif sql_check == 'commit':
self.connection.commit()
return
elif sql_check == 'rollback':
self.connection.rollback()
return
self.results, self.rowcount, self.lastrowid, self.description = self.connection._execute(sql, bind_variables, **kargs)
self.index = 0
return self.rowcount
def fetchone(self):
if self.results is None:
raise dbexceptions.ProgrammingError('fetch called before execute')
if self.index >= len(self.results):
return None
self.index += 1
return self.results[self.index-1]
def fetchmany(self, size=None):
if self.results is None:
raise dbexceptions.ProgrammingError('fetch called before execute')
if self.index >= len(self.results):
return []
if size is None:
size = self.arraysize
res = self.results[self.index:self.index+size]
self.index += size
return res
def fetchall(self):
if self.results is None:
raise dbexceptions.ProgrammingError('fetch called before execute')
return self.fetchmany(len(self.results)-self.index)
def callproc(self):
raise dbexceptions.NotSupportedError
def executemany(self, *pargs):
raise dbexceptions.NotSupportedError
def nextset(self):
raise dbexceptions.NotSupportedError
def setinputsizes(self, sizes):
pass
def setoutputsize(self, size, column=None):
pass
@property
def rownumber(self):
return self.index
def __iter__(self):
return self
def next(self):
val = self.fetchone()
if val is None:
raise StopIteration
return val
# A simple cursor intended for attaching to a single tablet server.
class TabletCursor(BaseCursor):
def execute(self, sql, bind_variables=None):
return self._execute(sql, bind_variables)
# Standard cursor when connecting to a sharded backend.
class Cursor(BaseCursor):
def execute(self, sql, bind_variables=None, key=None, keys=None):
try:
return self._execute(sql, bind_variables, key=key, keys=keys)
except mc_bson_request.MCBSonException, e:
if str(e) == 'unavailable':
self.connection._load_tablets()
raise
class KeyedCursor(BaseCursor):
def __init__(self, connection, key=None, keys=None):
self.key = key
self.keys = keys
BaseCursor.__init__(self, connection)
def execute(self, sql, bind_variables):
return self._execute(sql, bind_variables, key=self.key, keys=self.keys)
class BatchCursor(BaseCursor):
def __init__(self, connection):
self.exec_list = []
BaseCursor.__init__(self, connection)
def execute(self, sql, bind_variables=None, key=None, keys=None):
self.exec_list.append(BatchQueryItem(sql, bind_variables, key, keys))
def flush(self):
self.rowcount = self.connection._exec_batch(self.exec_list)
self.exec_list = []
# just used for batch items
class BatchQueryItem(object):
def __init__(self, sql, bind_variables, key, keys):
self.sql = sql
self.bind_variables = bind_variables
self.key = key
self.keys = keys
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from itertools import izip
import logging
from net import bsonrpc
from net import gorpc
from vtdb import cursor
from vtdb import dbexceptions
from vtdb import field_types
# A simple, direct connection to the voltron query server.
# This is shard-unaware and only handles the most basic communication.
class TabletConnection(object):
transaction_id = 0
session_id = 0
default_cursorclass = cursor.TabletCursor
def __init__(self, addr, dbname, timeout):
self.addr = addr
self.dbname = dbname
self.timeout = timeout
self.client = bsonrpc.BsonRpcClient(self.uri, self.timeout)
self.cursorclass = self.default_cursorclass
def dial(self):
if self.client:
self.client.close()
self.transaction_id = 0
self.session_id = 0
# You need to obtain and set the session_id for things to work.
def set_session_id(self, session_id):
self.session_id = session_id
@property
def uri(self):
return 'http://%s/_bson_rpc_' % self.addr
def close(self):
self.rollback()
self.client.close()
__del__ = close
def _make_req(self):
return {'TransactionId': self.transaction_id,
'ConnectionId': 0,
'SessionId': self.session_id}
def begin(self):
if self.transaction_id:
raise dbexceptions.NotSupportedError('Nested transactions not supported')
req = self._make_req()
try:
response = self.client.call('SqlQuery.Begin', req)
self.transaction_id = response.reply
except gorpc.GoRpcError, e:
raise dbexceptions.OperationalError(*e.args)
def commit(self):
if not self.transaction_id:
return
req = self._make_req()
# NOTE(msolomon) Unset the transaction_id irrespective of the RPC's
# response. The intent of commit is that no more statements can be made on
# this transaction, so we guarantee that. Transient errors between the
# db and the client shouldn't affect this part of the bookkeeping.
# Do this after fill_session, since this is a critical part.
self.transaction_id = 0
try:
response = self.client.call('SqlQuery.Commit', req)
return response.reply
except gorpc.GoRpcError, e:
raise dbexceptions.OperationalError(*e.args)
def rollback(self):
if not self.transaction_id:
return
req = self._make_req()
# NOTE(msolomon) Unset the transaction_id irrespective of the RPC. If the
# RPC fails, the client will still choose a new transaction_id next time
# and the tablet server will eventually kill the abandoned transaction on
# the server side.
self.transaction_id = 0
try:
response = self.client.call('SqlQuery.Rollback', req)
return response.reply
except gorpc.GoRpcError, e:
raise dbexceptions.OperationalError(*e.args)
def cursor(self, cursorclass=None, **kargs):
return (cursorclass or self.cursorclass)(self, **kargs)
def _execute(self, sql, bind_variables):
new_binds = field_types.convert_bind_vars(bind_variables)
req = self._make_req()
req['Sql'] = sql
req['BindVariables'] = new_binds
fields = []
conversions = []
results = []
try:
response = self.client.call('SqlQuery.Execute', req)
reply = response.reply
for field in reply['Fields']:
fields.append((field['Name'], field['Type']))
conversions.append(field_types.conversions.get(field['Type']))
for row in reply['Rows']:
results.append(tuple(_make_row(row, conversions)))
rowcount = reply['RowsAffected']
lastrowid = reply['InsertId']
except gorpc.GoRpcError, e:
raise dbexceptions.OperationalError(*e.args)
except:
logging.exception('gorpc low-level error')
raise
return results, rowcount, lastrowid, fields
def _make_row(row, conversions):
converted_row = []
for conversion_func, field_data in izip(conversions, row):
if field_data is None:
v = None
elif conversion_func:
v = conversion_func(field_data)
else:
v = field_data
converted_row.append(v)
return converted_row
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
exec_cases = [
# union
[
'select /* union */ eid, id from vtocc_a union select eid, id from vtocc_b', {},
[(1L, 1L), (1L, 2L)],
['select /* union */ eid, id from vtocc_a union select eid, id from vtocc_b'],
],
# distinct
[
'select /* distinct */ distinct * from vtocc_a', {},
[(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')],
['select /* distinct */ distinct * from vtocc_a limit 10001'],
],
# group by
[
'select /* group by */ eid, sum(id) from vtocc_a group by eid', {},
[(1L, 3L)],
['select /* group by */ eid, sum(id) from vtocc_a group by eid limit 10001'],
],
# having
[
'select /* having */ sum(id) from vtocc_a having sum(id) = 3', {},
[(3L,)],
['select /* having */ sum(id) from vtocc_a having sum(id) = 3 limit 10001'],
],
# limit
[
'select /* limit */ eid, id from vtocc_a limit %(a)s', {"a": 1},
[(1L, 1L)],
['select /* limit */ eid, id from vtocc_a limit 1'],
],
# multi-table
[
'select /* multi-table */ a.eid, a.id, b.eid, b.id from vtocc_a as a, vtocc_b as b', {},
[(1L, 1L, 1L, 1L), (1L, 2L, 1L, 1L), (1L, 1L, 1L, 2L), (1L, 2L, 1L, 2L)],
['select /* multi-table */ a.eid, a.id, b.eid, b.id from vtocc_a as a, vtocc_b as b limit 10001'],
],
# multi-table join
[
'select /* multi-table join */ a.eid, a.id, b.eid, b.id from vtocc_a as a join vtocc_b as b on a.eid = b.eid and a.id = b.id', {},
[(1L, 1L, 1L, 1L), (1L, 2L, 1L, 2L)],
['select /* multi-table join */ a.eid, a.id, b.eid, b.id from vtocc_a as a join vtocc_b as b on a.eid = b.eid and a.id = b.id limit 10001'],
],
# complex select list
[
'select /* complex select list */ eid+1, id from vtocc_a', {},
[(2L, 1L), (2L, 2L)],
['select /* complex select list */ eid+1, id from vtocc_a limit 10001'],
],
# *
[
'select /* * */ * from vtocc_a', {},
[(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')],
['select /* * */ * from vtocc_a limit 10001'],
],
# table alias
[
'select /* table alias */ a.eid from vtocc_a as a where a.eid=1', {},
[(1L,), (1L,)],
['select /* table alias */ a.eid from vtocc_a as a where a.eid = 1 limit 10001'],
],
# parenthesised col
[
'select /* parenthesised col */ (eid) from vtocc_a where eid = 1 and id = 1', {},
[(1L,)],
['select /* parenthesised col */ eid from vtocc_a where eid = 1 and id = 1 limit 10001'],
],
# for update
['begin'],
[
'select /* for update */ eid from vtocc_a where eid = 1 and id = 1 for update', {},
[(1L,)],
['select /* for update */ eid from vtocc_a where eid = 1 and id = 1 limit 10001 for update'],
],
['commit'],
# complex where
[
'select /* complex where */ id from vtocc_a where id+1 = 2', {},
[(1L,)],
['select /* complex where */ id from vtocc_a where id+1 = 2 limit 10001'],
],
# complex where (non-value operand)
[
'select /* complex where (non-value operand) */ eid, id from vtocc_a where eid = id', {},
[(1L, 1L)],
['select /* complex where (non-value operand) */ eid, id from vtocc_a where eid = id limit 10001'],
],
# (condition)
[
'select /* (condition) */ * from vtocc_a where (eid = 1)', {},
[(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')],
['select /* (condition) */ * from vtocc_a where (eid = 1) limit 10001'],
],
# inequality
[
'select /* inequality */ * from vtocc_a where id > 1', {},
[(1L, 2L, 'bcde', 'fghi')],
['select /* inequality */ * from vtocc_a where id > 1 limit 10001'],
],
# in
[
'select /* in */ * from vtocc_a where id in (1, 2)', {},
[(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')],
['select /* in */ * from vtocc_a where id in (1, 2) limit 10001'],
],
# between
[
'select /* between */ * from vtocc_a where id between 1 and 2', {},
[(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')],
['select /* between */ * from vtocc_a where id between 1 and 2 limit 10001'],
],
# order
[
'select /* order */ * from vtocc_a order by id desc', {},
[(1L, 2L, 'bcde', 'fghi'), (1L, 1L, 'abcd', 'efgh')],
['select /* order */ * from vtocc_a order by id desc limit 10001'],
],
# simple insert
['begin'],
[
"insert /* simple */ into vtocc_a values (2, 1, 'aaaa', 'bbbb')", {},
[],
["insert /* simple */ into vtocc_a values (2, 1, 'aaaa', 'bbbb')"],
],
['commit'],
['select * from vtocc_a where eid = 2 and id = 1', {}, [(2L, 1L, 'aaaa', 'bbbb')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# qualified insert
['begin'],
[
"insert /* qualified */ into vtocc_a(eid, id, name, foo) values (3, 1, 'aaaa', 'cccc')", {},
[],
["insert /* qualified */ into vtocc_a(eid, id, name, foo) values (3, 1, 'aaaa', 'cccc') /* _stream vtocc_a (eid id ) (3 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 3 and id = 1', {}, [(3L, 1L, 'aaaa', 'cccc')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# bind values
['begin'],
[
"insert /* bind values */ into vtocc_a(eid, id, name, foo) values (%(eid)s, %(id)s, %(name)s, %(foo)s)",
{"eid": 4, "id": 1, "name": "aaaa", "foo": "cccc"},
[],
["insert /* bind values */ into vtocc_a(eid, id, name, foo) values (4, 1, 'aaaa', 'cccc') /* _stream vtocc_a (eid id ) (4 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 4 and id = 1', {}, [(4L, 1L, 'aaaa', 'cccc')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# out of sequence columns
['begin'],
[
"insert into vtocc_a(id, eid, foo, name) values (-1, 5, 'aaa', 'bbb')", {},
[],
["insert into vtocc_a(id, eid, foo, name) values (-1, 5, 'aaa', 'bbb') /* _stream vtocc_a (eid id ) (5 -1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 5 and id = -1', {}, [(5L, -1L, 'bbb', 'aaa')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# numbers as strings
['begin'],
[
"insert into vtocc_a(id, eid, foo, name) values (%(id)s, '6', 111, 222)", { "id": "1"},
[],
["insert into vtocc_a(id, eid, foo, name) values ('1', '6', 111, 222) /* _stream vtocc_a (eid id ) (6 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 6 and id = 1', {}, [(6L, 1L, '222', '111')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# strings as numbers
['begin'],
[
"insert into vtocc_c(name, eid, foo) values (%(name)s, '9', 'aaa')", { "name": "bbb"},
[],
["insert into vtocc_c(name, eid, foo) values ('bbb', '9', 'aaa') /* _stream vtocc_c (eid name ) (9 'bbb' ); */"],
],
['commit'],
['select * from vtocc_c where eid = 9', {}, [(9, 'bbb', 'aaa')]],
['begin'], ['delete from vtocc_c where eid<10'], ['commit'],
# expressions
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (7, 1+1, '', '')", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (7, 1+1, '', '')"],
],
['commit'],
['select * from vtocc_a where eid = 7', {}, [(7L, 2L, '', '')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# no index
['begin'],
[
"insert into vtocc_d(eid, id) values (1, 1)", {},
[],
["insert into vtocc_d(eid, id) values (1, 1)"],
],
['commit'],
['select * from vtocc_d', {}, [(1L, 1L)]],
['begin'], ['delete from vtocc_d'], ['commit'],
# on duplicate key
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update name = 'foo'", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update name = 'foo' /* _stream vtocc_a (eid id ) (8 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 8', {}, [(8L, 1L, '', '')]],
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update name = 'foo'", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update name = 'foo' /* _stream vtocc_a (eid id ) (8 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 8', {}, [(8L, 1L, 'foo', '')]],
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update id = 2", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (8, 1, '', '') on duplicate key update id = 2 /* _stream vtocc_a (eid id ) (8 1 ) (8 2 ); */"],
],
['commit'],
['select * from vtocc_a where eid = 8', {}, [(8L, 2L, 'foo', '')]],
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (8, 2, '', '') on duplicate key update id = 2+1", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (8, 2, '', '') on duplicate key update id = 2+1"],
],
['commit'],
['select * from vtocc_a where eid = 8', {}, [(8L, 3L, 'foo', '')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# subquery
['begin'],
[
"insert /* subquery */ into vtocc_a(eid, id, name, foo) select eid, foo, name, foo from vtocc_c", {},
[],
[
'select eid, foo, name, foo from vtocc_c limit 10001',
"insert /* subquery */ into vtocc_a(eid, id, name, foo) values (10, 20, 'abcd', '20'), (11, 30, 'bcde', '30') /* _stream vtocc_a (eid id ) (10 20 ) (11 30 ); */",
],
],
['commit'],
['select * from vtocc_a where eid in (10, 11)', {}, [(10L, 20L, 'abcd', '20'), (11L, 30L, 'bcde', '30')]],
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) select eid, foo, name, foo from vtocc_c on duplicate key update foo='bar'", {},
[],
[
'select eid, foo, name, foo from vtocc_c limit 10001',
"insert into vtocc_a(eid, id, name, foo) values (10, 20, 'abcd', '20'), (11, 30, 'bcde', '30') on duplicate key update foo = 'bar' /* _stream vtocc_a (eid id ) (10 20 ) (11 30 ); */",
],
],
['commit'],
['select * from vtocc_a where eid in (10, 11)', {}, [(10L, 20L, 'abcd', 'bar'), (11L, 30L, 'bcde', 'bar')]],
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) select eid, foo, name, foo from vtocc_c limit 1 on duplicate key update id = 21", {},
[],
[
'select eid, foo, name, foo from vtocc_c limit 1',
"insert into vtocc_a(eid, id, name, foo) values (10, 20, 'abcd', '20') on duplicate key update id = 21 /* _stream vtocc_a (eid id ) (10 20 ) (10 21 ); */",
],
],
['commit'],
['select * from vtocc_a where eid in (10, 11)', {}, [(10L, 21L, 'abcd', 'bar'), (11L, 30, 'bcde', 'bar')]],
['begin'], ['delete from vtocc_a where eid>1'], ['delete from vtocc_c where eid<10'], ['commit'],
# multi-value
['begin'],
[
"insert into vtocc_a(eid, id, name, foo) values (5, 1, '', ''), (7, 1, '', '')", {},
[],
["insert into vtocc_a(eid, id, name, foo) values (5, 1, '', ''), (7, 1, '', '') /* _stream vtocc_a (eid id ) (5 1 ) (7 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid>1', {}, [(5L, 1L, '', ''), (7L, 1L, '', '')]],
['begin'], ['delete from vtocc_a where eid>1'], ['commit'],
# update
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid = 1 and id = 1", {},
[],
["update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */"]
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ['commit'],
# single in
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid = 1 and id in (1, 2)", {},
[],
["update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id in (1, 2) /* _stream vtocc_a (eid id ) (1 1 ) (1 2 ); */"],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# double in
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid in (1) and id in (1, 2)", {},
[],
[
'select eid, id from vtocc_a where eid in (1) and id in (1, 2) limit 10001 for update',
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 2 /* _stream vtocc_a (eid id ) (1 2 ); */",
],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# double in 2
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid in (1, 2) and id in (1, 2)", {},
[],
[
'select eid, id from vtocc_a where eid in (1, 2) and id in (1, 2) limit 10001 for update',
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 2 /* _stream vtocc_a (eid id ) (1 2 ); */",
],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# tuple in
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where (eid, id) in ((1, 1), (1, 2))", {},
[],
["update /* pk */ vtocc_a set foo = 'bar' where (eid, id) in ((1, 1), (1, 2)) /* _stream vtocc_a (eid id ) (1 1 ) (1 2 ); */"],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# pk change
['begin'],
[
"update vtocc_a set eid = 2 where eid = 1 and id = 1", {},
[],
["update vtocc_a set eid = 2 where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ) (2 1 ); */"],
],
['commit'],
['select eid from vtocc_a where id = 1', {}, [(2L,)]],
['begin'], ["update vtocc_a set eid=1 where id=1"], ['commit'],
# complex pk change
['begin'],
[
"update vtocc_a set eid = 1+1 where eid = 1 and id = 1", {},
[],
["update vtocc_a set eid = 1+1 where eid = 1 and id = 1"],
],
['commit'],
['select eid from vtocc_a where id = 1', {}, [(2L,)]],
['begin'], ["update vtocc_a set eid=1 where id=1"], ['commit'],
# complex where
['begin'],
[
"update vtocc_a set eid = 1+1 where eid = 1 and id = 1+0", {},
[],
["update vtocc_a set eid = 1+1 where eid = 1 and id = 1+0"],
],
['commit'],
['select eid from vtocc_a where id = 1', {}, [(2L,)]],
['begin'], ["update vtocc_a set eid=1 where id=1"], ['commit'],
# partial pk
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where id = 1", {},
[],
[
"select eid, id from vtocc_a where id = 1 limit 10001 for update",
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ['commit'],
# limit
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid = 1 limit 1", {},
[],
[
"select eid, id from vtocc_a where eid = 1 limit 1 for update",
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
],
],
['commit'],
['select foo from vtocc_a where id = 1', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ['commit'],
# order by
['begin'],
[
"update /* pk */ vtocc_a set foo='bar' where eid = 1 order by id desc limit 1", {},
[],
[
"select eid, id from vtocc_a where eid = 1 order by id desc limit 1 for update",
"update /* pk */ vtocc_a set foo = 'bar' where eid = 1 and id = 2 /* _stream vtocc_a (eid id ) (1 2 ); */",
],
],
['commit'],
['select foo from vtocc_a where id = 2', {}, [('bar',)]],
['begin'], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# missing where
['begin'],
[
"update vtocc_a set foo='bar'", {},
[],
[
"select eid, id from vtocc_a limit 10001 for update",
"update vtocc_a set foo = 'bar' where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
"update vtocc_a set foo = 'bar' where eid = 1 and id = 2 /* _stream vtocc_a (eid id ) (1 2 ); */",
],
],
['commit'],
['select * from vtocc_a', {}, [(1L, 1L, 'abcd', 'bar'), (1L, 2L, 'bcde', 'bar')]],
['begin'], ["update vtocc_a set foo='efgh' where id=1"], ["update vtocc_a set foo='fghi' where id=2"], ['commit'],
# no index
['begin'],
["insert into vtocc_d(eid, id) values (1, 1)"],
[
"update vtocc_d set id = 2 where eid = 1", {},
[],
["update vtocc_d set id = 2 where eid = 1"],
],
['commit'],
['select * from vtocc_d', {}, [(1L, 2L)]],
['begin'], ['delete from vtocc_d'], ['commit'],
# delete
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete /* pk */ from vtocc_a where eid = 2 and id = 1", {},
[],
["delete /* pk */ from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */"],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# single in
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete /* pk */ from vtocc_a where eid = 2 and id in (1, 2)", {},
[],
["delete /* pk */ from vtocc_a where eid = 2 and id in (1, 2) /* _stream vtocc_a (eid id ) (2 1 ) (2 2 ); */"],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# double in
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete /* pk */ from vtocc_a where eid in (2) and id in (1, 2)", {},
[],
[
'select eid, id from vtocc_a where eid in (2) and id in (1, 2) limit 10001 for update',
'delete /* pk */ from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */',
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# double in 2
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete /* pk */ from vtocc_a where eid in (2, 3) and id in (1, 2)", {},
[],
[
'select eid, id from vtocc_a where eid in (2, 3) and id in (1, 2) limit 10001 for update',
'delete /* pk */ from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */'
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# tuple in
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete /* pk */ from vtocc_a where (eid, id) in ((2, 1), (3, 2))", {},
[],
["delete /* pk */ from vtocc_a where (eid, id) in ((2, 1), (3, 2)) /* _stream vtocc_a (eid id ) (2 1 ) (3 2 ); */"],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# complex where
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete from vtocc_a where eid = 1+1 and id = 1", {},
[],
[
'select eid, id from vtocc_a where eid = 1+1 and id = 1 limit 10001 for update',
"delete from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */",
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# partial pk
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete from vtocc_a where eid = 2", {},
[],
[
'select eid, id from vtocc_a where eid = 2 limit 10001 for update',
"delete from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */",
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# limit
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete from vtocc_a where eid = 2 limit 1", {},
[],
[
'select eid, id from vtocc_a where eid = 2 limit 1 for update',
"delete from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */",
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# order by
['begin'],
["insert into vtocc_a(eid, id, name, foo) values (2, 1, '', '')"],
[
"delete from vtocc_a order by eid desc limit 1", {},
[],
[
'select eid, id from vtocc_a order by eid desc limit 1 for update',
"delete from vtocc_a where eid = 2 and id = 1 /* _stream vtocc_a (eid id ) (2 1 ); */",
],
],
['commit'],
['select * from vtocc_a where eid=2', {}, []],
# missing where
['begin'],
[
"delete from vtocc_a", {},
[],
[
'select eid, id from vtocc_a limit 10001 for update',
"delete from vtocc_a where eid = 1 and id = 1 /* _stream vtocc_a (eid id ) (1 1 ); */",
"delete from vtocc_a where eid = 1 and id = 2 /* _stream vtocc_a (eid id ) (1 2 ); */",
],
],
['rollback'],
['select * from vtocc_a', {}, [(1L, 1L, 'abcd', 'efgh'), (1L, 2L, 'bcde', 'fghi')]],
# no index
['begin'],
['insert into vtocc_d values (1, 1)'],
[
'delete from vtocc_d where eid =1 and id =1', {},
[],
['delete from vtocc_d where eid = 1 and id = 1'],
],
['commit'],
['select * from vtocc_d', {}, []],
]
| Python |
#!/usr/bin/env python
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import json
import optparse
import os
import subprocess
import sys
import time
import urllib2
import MySQLdb as mysql
from vttest import framework
from vttest import exec_cases
from vtdb import vt_occ2 as db
from vtdb import dbexceptions
parser = optparse.OptionParser(usage="usage: %prog [options]")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False)
parser.add_option("-t", "--testcase", action="store", dest="testcase", default=None,
help="Run a single named test")
parser.add_option("-c", "--dbconfig", action="store", dest="dbconfig", default="dbtest.json",
help="json db config file")
(options, args) = parser.parse_args()
QUERYLOGFILE = "/tmp/vtocc_queries.log"
class TestVtocc(framework.TestCase):
def setUp(self):
vttop = os.getenv("VTTOP")
if vttop is None:
raise Exception("VTTOP not defined")
occpath = vttop+"/go/cmd/vtocc/"
with open(options.dbconfig) as f:
self.cfg = json.load(f)
self.mysql_conn = self.mysql_connect(self.cfg)
mcu = self.mysql_conn.cursor()
self.clean_sqls = []
self.init_sqls = []
clean_mode = False
with open("test_schema.sql") as f:
for line in f:
line = line.rstrip()
if line == "# clean":
clean_mode = True
if line=='' or line.startswith("#"):
continue
if clean_mode:
self.clean_sqls.append(line)
else:
self.init_sqls.append(line)
try:
for line in self.init_sqls:
mcu.execute(line, {})
finally:
mcu.close()
occ_args = [
vttop+"/go/cmd/vtocc/vtocc",
"-config", "occ.json",
"-dbconfig", options.dbconfig,
"-logfile", "/tmp/vtocc.log",
"-querylog", QUERYLOGFILE,
]
with open("/tmp/vtocc_stderr.log", "a+") as vtstderr:
self.vtocc = subprocess.Popen(occ_args, stderr=vtstderr)
for i in range(30):
try:
self.conn = self.connect()
self.querylog = framework.Tailer(open(QUERYLOGFILE, "r"))
return
except dbexceptions.OperationalError:
time.sleep(1)
self.conn = self.connect()
self.querylog = framework.Tailer(open(QUERYLOGFILE, "r"))
def tearDown(self):
try:
mcu = self.mysql_conn.cursor()
for line in self.clean_sqls:
try:
mcu.execute(line, {})
except:
pass
mcu.close()
except:
pass
if getattr(self, "vtocc", None):
self.vtocc.terminate()
def mysql_connect(self, cfg):
return mysql.connect(
host=cfg.get('host', ''),
user=cfg.get('uname', ''),
passwd=cfg.get('pass', ''),
port=cfg.get('port', 0),
db=cfg.get('dbname'),
unix_socket=cfg.get('unix_socket', ''),
charset=cfg.get('charset', ''))
def connect(self):
return db.connect("localhost:9461", 2, dbname=self.cfg.get('dbname', None))
def execute(self, query, binds=None):
if binds is None:
binds = {}
curs = self.conn.cursor()
curs.execute(query, binds)
return curs
def debug_vars(self):
return framework.MultiDict(json.load(urllib2.urlopen("http://localhost:9461/debug/vars")))
def test_data(self):
cu = self.execute("select * from vtocc_test where intval=1")
self.assertEqual(cu.description, [('intval', 3), ('floatval', 4), ('charval', 253), ('binval', 253)])
self.assertEqual(cu.rowcount, 1)
self.assertEqual(cu.fetchone(), (1, 1.12345, "\xc2\xa2", "\x00\xff"))
cu = self.execute("select * from vtocc_test where intval=2")
self.assertEqual(cu.fetchone(), (2, None, '', None))
def test_binary(self):
self.execute("begin")
binary_data = '\x00\'\"\b\n\r\t\x1a\\\x00\x0f\xf0\xff'
self.execute("insert into vtocc_test values(4, null, null, '\\0\\'\\\"\\b\\n\\r\\t\\Z\\\\\x00\x0f\xf0\xff')")
bvar = {}
bvar['bindata'] = binary_data
self.execute("insert into vtocc_test values(5, null, null, %(bindata)s)", bvar)
self.execute("commit")
cu = self.execute("select * from vtocc_test where intval=4")
self.assertEqual(cu.fetchone()[3], binary_data)
cu = self.execute("select * from vtocc_test where intval=5")
self.assertEqual(cu.fetchone()[3], binary_data)
self.execute("begin")
self.execute("delete from vtocc_test where intval in (4,5)")
self.execute("commit")
def test_simple_read(self):
vstart = self.debug_vars()
cu = self.execute("select * from vtocc_test limit 2")
vend = self.debug_vars()
self.assertEqual(cu.rowcount, 2)
self.assertEqual(vstart.mget("Queries.TotalCount", 0)+1, vend.Queries.TotalCount)
self.assertEqual(vstart.mget("Queries.Histograms.PASS_SELECT.Count", 0)+1, vend.Queries.Histograms.PASS_SELECT.Count)
self.assertNotEqual(vend.Voltron.ConnPool.Connections, 0)
def test_commit(self):
vstart = self.debug_vars()
self.execute("begin")
self.assertNotEqual(self.conn.transaction_id, 0)
self.execute("insert into vtocc_test (intval, floatval, charval, binval) values(4, null, null, null)")
self.execute("commit")
cu = self.execute("select * from vtocc_test")
self.assertEqual(cu.rowcount, 4)
self.execute("begin")
self.execute("delete from vtocc_test where intval=4")
self.execute("commit")
cu = self.execute("select * from vtocc_test")
self.assertEqual(cu.rowcount, 3)
vend = self.debug_vars()
# We should have at least one connection
self.assertNotEqual(vend.Voltron.TxPool.Connections, 0)
self.assertEqual(vstart.mget("Transactions.TotalCount", 0)+2, vend.Transactions.TotalCount)
self.assertEqual(vstart.mget("Transactions.Histograms.Completed.Count", 0)+2, vend.Transactions.Histograms.Completed.Count)
self.assertEqual(vstart.mget("Queries.TotalCount", 0)+4, vend.Queries.TotalCount)
self.assertEqual(vstart.mget("Queries.Histograms.PLAN_INSERT_PK.Count", 0)+1, vend.Queries.Histograms.PLAN_INSERT_PK.Count)
self.assertEqual(vstart.mget("Queries.Histograms.DML_PK.Count", 0)+1, vend.Queries.Histograms.DML_PK.Count)
self.assertEqual(vstart.mget("Queries.Histograms.PASS_SELECT.Count", 0)+2, vend.Queries.Histograms.PASS_SELECT.Count)
def test_integrity_error(self):
vstart = self.debug_vars()
self.execute("begin")
try:
self.execute("insert into vtocc_test values(1, null, null, null)")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertEqual(e[0], 1062)
self.assertContains(e[1], "error: Duplicate")
else:
self.assertFail("Did not receive exception")
finally:
self.execute("rollback")
vend = self.debug_vars()
self.assertEqual(vstart.mget("Errors.DupKey", 0)+1, vend.Errors.DupKey)
def test_rollback(self):
vstart = self.debug_vars()
self.execute("begin")
self.assertNotEqual(self.conn.transaction_id, 0)
self.execute("insert into vtocc_test values(4, null, null, null)")
self.execute("rollback")
cu = self.execute("select * from vtocc_test")
self.assertEqual(cu.rowcount, 3)
vend = self.debug_vars()
self.assertNotEqual(vend.Voltron.TxPool.Connections, 0)
self.assertEqual(vstart.mget("Transactions.TotalCount", 0)+1, vend.Transactions.TotalCount)
self.assertEqual(vstart.mget("Transactions.Histograms.Aborted.Count", 0)+1, vend.Transactions.Histograms.Aborted.Count)
def test_nontx_dml(self):
vstart = self.debug_vars()
try:
self.execute("insert into vtocc_test values(4, null, null, null)")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: DMLs")
else:
self.assertFail("Did not receive exception")
vend = self.debug_vars()
self.assertEqual(vstart.mget("Errors.Fail", 0)+1, vend.Errors.Fail)
def test_trailing_comment(self):
vstart = self.debug_vars()
bv={}
bv["ival"] = 1
self.execute("select * from vtocc_test where intval=%(ival)s", bv)
vend = self.debug_vars()
self.assertEqual(vstart.mget("Voltron.QueryCache.Length", 0)+1, vend.Voltron.QueryCache.Length)
# This should not increase the query cache size
self.execute("select * from vtocc_test where intval=%(ival)s /* trailing comment */", bv)
vend = self.debug_vars()
self.assertEqual(vstart.mget("Voltron.QueryCache.Length", 0)+1, vend.Voltron.QueryCache.Length)
def test_for_update(self):
try:
self.execute("select * from vtocc_test where intval=2 for update")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Disallowed")
else:
self.assertFail("Did not receive exception")
# If these throw no exceptions, we're good
self.execute("begin")
self.execute("select * from vtocc_test where intval=2 for update")
self.execute("commit")
# Make sure the row is not locked for read
self.execute("select * from vtocc_test where intval=2")
def test_pool_size(self):
vstart = self.debug_vars()
self.execute("set vt_pool_size=1")
try:
self.execute("select sleep(3) from dual")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError):
pass
else:
self.assertFail("Did not receive exception")
self.execute("select 1 from dual")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ConnPool.Capacity, 1)
self.assertEqual(vstart.mget("Waits.TotalCount", 0)+1, vend.Waits.TotalCount)
self.assertEqual(vstart.mget("Waits.Histograms.ConnPool.Count", 0)+1, vend.Waits.Histograms.ConnPool.Count)
self.execute("set vt_pool_size=16")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ConnPool.Capacity, 16)
def test_transaction_cap(self):
vstart = self.debug_vars()
self.execute("set vt_transaction_cap=1")
co2 = self.connect()
self.execute("begin")
try:
cu2 = co2.cursor()
cu2.execute("begin", {})
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Transaction")
else:
self.assertFail("Did not receive exception")
finally:
cu2.close()
co2.close()
self.execute("commit")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.TxPool.Capacity, 1)
self.assertEqual(vend.Voltron.ActiveTxPool.Capacity, 1)
self.execute("set vt_transaction_cap=20")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.TxPool.Capacity, 20)
self.assertEqual(vend.Voltron.ActiveTxPool.Capacity, 20)
def test_transaction_timeout(self):
vstart = self.debug_vars()
self.execute("set vt_transaction_timeout=1")
self.execute("begin")
time.sleep(2)
try:
self.execute("commit")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Transaction")
else:
self.assertFail("Did not receive exception")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ActiveTxPool.Timeout, 1)
self.assertEqual(vstart.mget("Kills.Transactions", 0)+1, vend.Kills.Transactions)
self.execute("set vt_transaction_timeout=30")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ActiveTxPool.Timeout, 30)
def test_query_cache(self):
vstart = self.debug_vars()
self.execute("set vt_query_cache_size=1")
bv={}
bv["ival1"] = 1
self.execute("select * from vtocc_test where intval=%(ival1)s", bv)
bv["ival2"] = 1
self.execute("select * from vtocc_test where intval=%(ival2)s", bv)
vend = self.debug_vars()
self.assertEqual(vend.Voltron.QueryCache.Length, 1)
self.assertEqual(vend.Voltron.QueryCache.Size, 1)
self.assertEqual(vend.Voltron.QueryCache.Capacity, 1)
self.execute("set vt_query_cache_size=5000")
self.execute("select * from vtocc_test where intval=%(ival1)s", bv)
vend = self.debug_vars()
self.assertEqual(vend.Voltron.QueryCache.Length, 2)
self.assertEqual(vend.Voltron.QueryCache.Size, 2)
self.assertEqual(vend.Voltron.QueryCache.Capacity, 5000)
def test_schema_reload_time(self):
mcu = self.mysql_conn.cursor()
mcu.execute("create table vtocc_temp(intval int)")
self.execute("set vt_schema_reload_time=1")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.SchemaReloadTime, 1)
# This should not throw an exception
try:
for i in range(10):
try:
self.execute("select * from vtocc_temp")
self.execute("set vt_schema_reload_time=600")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.SchemaReloadTime, 600)
break
except db.MySQLErrors.DatabaseError, e:
self.assertContains(e[1], "not found in schema")
time.sleep(1)
finally:
mcu.execute("drop table vtocc_temp")
mcu.close()
def test_max_result_size(self):
self.execute("set vt_max_result_size=2")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.MaxResultSize, 2)
try:
self.execute("select * from vtocc_test")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Row")
else:
self.assertFail("Did not receive exception")
self.execute("set vt_max_result_size=10000")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.MaxResultSize, 10000)
def test_query_timeout(self):
vstart = self.debug_vars()
conn = db.connect("localhost:9461", 5, dbname=self.cfg['dbname'])
cu = conn.cursor()
self.execute("set vt_query_timeout=1")
try:
cu.execute("begin", {})
cu.execute("select sleep(2) from vtocc_test", {})
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Query")
else:
self.assertFail("Did not receive exception")
try:
cu.execute("select 1 from dual", {})
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(e[1], "error: Transaction")
else:
self.assertFail("Did not receive exception")
try:
cu.close()
conn.close()
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError), e:
self.assertContains(str(e), "error: Transaction")
else:
self.assertFail("Did not receive exception")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ActivePool.Timeout, 1)
self.assertEqual(vstart.mget("Kills.Queries", 0)+1, vend.Kills.Queries)
self.execute("set vt_query_timeout=30")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ActivePool.Timeout, 30)
def test_idle_timeout(self):
vstart = self.debug_vars()
self.execute("set vt_idle_timeout=1")
time.sleep(2)
self.execute("select 1 from dual")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ConnPool.IdleTimeout, 1)
self.assertEqual(vend.Voltron.TxPool.IdleTimeout, 1)
self.assertEqual(vstart.mget("Kills.Connections", 0)+1, vend.Kills.Connections)
self.execute("set vt_idle_timeout=1800")
vend = self.debug_vars()
self.assertEqual(vend.Voltron.ConnPool.IdleTimeout, 1800)
self.assertEqual(vend.Voltron.TxPool.IdleTimeout, 1800)
def test_consolidation(self):
vstart = self.debug_vars()
for i in range(2):
try:
self.execute("select sleep(3) from dual")
except (db.MySQLErrors.DatabaseError, db.dbexceptions.OperationalError):
pass
vend = self.debug_vars()
self.assertEqual(vstart.mget("Waits.TotalCount", 0)+1, vend.Waits.TotalCount)
self.assertEqual(vstart.mget("Waits.Histograms.Consolidations.Count", 0)+1, vend.Waits.Histograms.Consolidations.Count)
def test_execution(self):
curs = self.conn.cursor()
error_count = 0
for case in exec_cases.exec_cases:
if len(case) == 1:
curs.execute(case[0])
continue
self.querylog.reset()
curs.execute(case[0], case[1])
if len(case) == 2:
continue
results = []
for row in curs:
results.append(row)
if results != case[2]:
print "Function: test_execution: FAIL: %s:\n%s\n%s"%(case[0], case[2], results)
error_count += 1
if len(case) == 3:
continue
querylog = normalizelog(self.querylog.read())
if querylog != case[3]:
print "Function: test_execution: FAIL: %s:\n%s\n%s"%(case[0], case[3], querylog)
error_count += 1
if error_count != 0:
self.assertFail("test_execution errors: %d"%(error_count))
def normalizelog(data):
lines = data.split("\n")
newlines = []
for line in lines:
pos = line.find("INFO: ")
if pos >= 0:
newlines.append(line[pos+6:])
return newlines
t = TestVtocc(options.testcase, options.verbose)
t.run()
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import traceback
class MultiDict(dict):
def __getattr__(self, name):
v = self[name]
if type(v)==dict:
v=MultiDict(v)
return v
def mget(self, mkey, default=None):
keys = mkey.split(".")
try:
v = self
for key in keys:
v = v[key]
except KeyError:
v = default
if type(v)==dict:
v = MultiDict(v)
return v
class TestException(Exception):
pass
class TestCase(object):
def __init__(self, testcase=None, verbose=False):
self.testcase = testcase
self.verbose = verbose
def run(self):
error_count = 0
try:
self.setUp()
if self.testcase is None:
testlist = [v for k, v in self.__class__.__dict__.iteritems() if k.startswith("test_")]
else:
testlist = [self.__class__.__dict__[self.testcase]]
for testfunc in testlist:
try:
testfunc(self)
except TestException, e:
print e
error_count += 1
except:
error_count += 1
raise
finally:
self.tearDown()
if error_count == 0:
print "GREAT SUCCESS"
else:
print "Errors:", error_count
def assertNotEqual(self, val1, val2):
if val1 == val2:
raise TestException(self._format("FAIL: %s == %s"%(str(val1), str(val2))))
elif self.verbose:
print self._format("PASS")
def assertEqual(self, val1, val2):
if val1 != val2:
raise TestException(self._format("FAIL: %s != %s"%(str(val1), str(val2))))
elif self.verbose:
print self._format("PASS")
def assertFail(self, msg):
raise TestException(self._format("FAIL: %s"%msg))
def assertStartsWith(self, val, prefix):
if not val.startswith(prefix):
raise TestException(self._format("FAIL: %s does not start with %s"%(str(val), str(prefix))))
def assertContains(self, val, substr):
if substr not in val:
raise TestException(self._format("FAIL: %s does not contain %s"%(str(val), str(substr))))
def _format(self, msg):
frame = traceback.extract_stack()[-3]
if self.verbose:
return "Function: %s, Line %d: %s: %s"%(frame[2], frame[1], frame[3], msg)
else:
return "Function: %s, Line %d: %s"%(frame[2], frame[1], msg)
def setUp(self):
pass
def tearDown(self):
pass
class Tailer(object):
def __init__(self, f):
self.f = f
self.reset()
def reset(self):
self.f.seek(0, os.SEEK_END)
self.pos = self.f.tell()
def read(self):
self.f.seek(0, os.SEEK_END)
newpos = self.f.tell()
if newpos < self.pos:
return ""
self.f.seek(self.pos, os.SEEK_SET)
size = newpos-self.pos
self.pos = newpos
return self.f.read(size)
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Go-style RPC client using BSON as the codec.
import bson
try:
# use optimized cbson which has slightly different API
import cbson
decode_document = cbson.decode_next
except ImportError:
from bson import codec
decode_document = codec.decode_document
from net import gorpc
# Field name used for wrapping simple values as bson documents
# FIXME(msolomon) abandon this - too nasty when protocol requires upgrade
WRAPPED_FIELD = '_Val_'
class BsonRpcClient(gorpc.GoRpcClient):
def encode_request(self, req):
try:
if not isinstance(req.body, dict):
# hack to handle simple values
body = {WRAPPED_FIELD: req.body}
else:
body = req.body
return bson.dumps(req.header) + bson.dumps(body)
except Exception, e:
raise gorpc.GoRpcError('encode error', e)
# fill response with decoded data
def decode_response(self, response, data):
try:
offset, response.header = decode_document(data, 0)
offset, response.reply = decode_document(data, offset)
# unpack primitive values
# FIXME(msolomon) remove this hack
response.reply = response.reply.get(WRAPPED_FIELD, response.reply)
except Exception, e:
raise gorpc.GoRpcError('decode error', e)
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class MCBSonException(Exception):
pass
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Handle transport and serialization callbacks for Go-style RPC servers.
#
# This is pretty simple. The client initiates an HTTP CONNECT and then
# hijacks the socket. The client is synchronous, but implements deadlines.
import errno
import socket
import struct
import time
import urlparse
_len = len
_join = ''.join
class GoRpcError(Exception):
pass
class TimeoutError(GoRpcError):
pass
# Error field from response raised as an exception
class AppError(GoRpcError):
pass
def make_header(method, sequence_id):
return {'ServiceMethod': method,
'Seq': sequence_id}
class GoRpcRequest(object):
header = None # standard fields that route the request on the server side
body = None # the actual request object - usually a dictionary
def __init__(self, header, args):
self.header = header
self.body = args
@property
def sequence_id(self):
return self.header['Seq']
class GoRpcResponse(object):
# the request header is echoed back to detect error and out-of-sequence bugs
# {'ServiceMethod': method,
# 'Seq': sequence_id,
# 'Error': error_string}
header = None
reply = None # the decoded object - usually a dictionary
@property
def error(self):
return self.header['Error']
@property
def sequence_id(self):
return self.header['Seq']
# FIXME(msolomon) This is a bson-ism, fix for future protocols.
len_struct = struct.Struct('<i')
unpack_length = len_struct.unpack_from
len_struct_size = len_struct.size
default_read_buffer_size = 8192
# A single socket wrapper to handle request/response conversation for this
# protocol. Internal, use GoRpcClient instead.
class _GoRpcConn(object):
def __init__(self, timeout):
self.conn = None
self.timeout = timeout
self.start_time = None
def dial(self, uri):
parts = urlparse.urlparse(uri)
netloc = parts.netloc.split(':')
# NOTE(msolomon) since the deadlines are approximate in the code, set
# timeout to oversample to minimize waiting in the extreme failure mode.
socket_timeout = self.timeout / 10.0
self.conn = socket.create_connection((netloc[0], int(netloc[1])),
socket_timeout)
self.conn.sendall('CONNECT %s HTTP/1.0\n\n' % parts.path)
while True:
data = self.conn.recv(1024)
if not data:
raise GoRpcError('Unexpected EOF in handshake')
if '\n\n' in data:
return
def close(self):
if self.conn:
self.conn.close()
self.conn = None
def _check_deadline_exceeded(self):
if (time.time() - self.start_time) > self.timeout:
raise socket.timeout('deadline exceeded')
return False
def write_request(self, request_data):
self.start_time = time.time()
self.conn.sendall(request_data)
# FIXME(msolomon) This makes a couple of assumptions from bson encoding.
def read_response(self):
if self.start_time is None:
raise GoRpcError('no request pending')
try:
buf = []
buf_write = buf.append
data, data_len = _read_more(self.conn, buf, buf_write)
# must read at least enough to get the length
while data_len < len_struct_size and not self._check_deadline_exceeded():
data, data_len = _read_more(self.conn, buf, buf_write)
# header_len is the size of the entire header including the length
# add on an extra len_struct_size to get enough of the body to read size
header_len = unpack_length(data)[0]
while (data_len < (header_len + len_struct_size) and
not self._check_deadline_exceeded()):
data, data_len = _read_more(self.conn, buf, buf_write)
# body_len is the size of the entire body - same as above
body_len = unpack_length(data, header_len)[0]
total_len = header_len + body_len
while data_len < total_len and not self._check_deadline_exceeded():
data, data_len = _read_more(self.conn, buf, buf_write)
return data
finally:
self.start_time = None
def _read_more(conn, buf, buf_write):
try:
data = conn.recv(default_read_buffer_size)
if not data:
# We only read when we expect data - if we get nothing this probably
# indicates that the server hung up. This exception ensure the client
# tears down properly.
raise socket.error(errno.EPIPE, 'unexpected EOF in read')
except socket.timeout:
# catch the timeout and return empty data for now - this breaks the call
# and lets the deadline get caught with reasonable precision.
data = ''
if buf:
buf_write(data)
data = _join(buf)
else:
buf_write(data)
return data, _len(data)
class GoRpcClient(object):
def __init__(self, uri, timeout):
self.uri = uri
self.timeout = timeout
# FIXME(msolomon) make this random initialized?
self.seq = 0
self._conn = None
@property
def conn(self):
if not self._conn:
self._conn = _GoRpcConn(self.timeout)
self._conn.dial(self.uri)
return self._conn
def close(self):
if self._conn:
self._conn.close()
self._conn = None
def next_sequence_id(self):
self.seq += 1
return self.seq
# return encoded request data, including header
def encode_request(self, req):
raise NotImplementedError
# fill response with decoded data
def decode_response(self, response, data):
raise NotImplementedError
# Perform an rpc, raising a GoRpcError, on errant situations.
# Pass in a response object if you don't want a generic one created.
def call(self, method, request, response=None):
try:
h = make_header(method, self.next_sequence_id())
req = GoRpcRequest(h, request)
self.conn.write_request(self.encode_request(req))
data = self.conn.read_response()
if response is None:
response = GoRpcResponse()
self.decode_response(response, data)
except socket.timeout, e:
# tear down - can't guarantee a clean conversation
self.close()
raise TimeoutError(e, self.timeout, method)
except socket.error, e:
# tear down - better chance of recovery by reconnecting
self.close()
raise GoRpcError(e, method)
if response.error:
raise AppError(response.error, method)
if response.sequence_id != req.sequence_id:
# tear down - off-by-one error in the connection somewhere
self.close()
raise GoRpcError('request sequence mismatch', response.sequence_id,
req.sequence_id, method)
return response
| Python |
# Copyright 2012, Google Inc.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 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("&","&")
s = s.replace('"',""")
s = s.replace("'","'")
s = s.replace("<","<")
s = s.replace(">",">")
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 |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.