text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Remove accents from characters in the given string.
<END_TASK>
<USER_TASK:>
Description:
def remove_accents(value):
"""
Remove accents from characters in the given string.
""" |
search = 'ΆΈΉΊΌΎΏάέήίόύώΪϊΐϋΰ'
replace = 'ΑΕΗΙΟΥΩαεηιουωΙιιυυ'
def replace_accented_character(match):
matched = match.group(0)
if matched in search:
return replace[search.find(matched)]
return matched
return re.sub(r'[{0}]+'.format(search), replace_accented_character, value) |
<SYSTEM_TASK:>
Calculates and returns a control digit for given list of digits basing on REGON standard.
<END_TASK>
<USER_TASK:>
Description:
def regon_checksum(digits):
"""
Calculates and returns a control digit for given list of digits basing on REGON standard.
""" |
weights_for_check_digit = [8, 9, 2, 3, 4, 5, 6, 7]
check_digit = 0
for i in range(0, 8):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 11
if check_digit == 10:
check_digit = 0
return check_digit |
<SYSTEM_TASK:>
Calculates and returns a control digit for given list of digits basing on local REGON standard.
<END_TASK>
<USER_TASK:>
Description:
def local_regon_checksum(digits):
"""
Calculates and returns a control digit for given list of digits basing on local REGON standard.
""" |
weights_for_check_digit = [2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8]
check_digit = 0
for i in range(0, 13):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 11
if check_digit == 10:
check_digit = 0
return check_digit |
<SYSTEM_TASK:>
Calculates and returns a control digit for given list of digits basing on NIP standard.
<END_TASK>
<USER_TASK:>
Description:
def company_vat_checksum(digits):
"""
Calculates and returns a control digit for given list of digits basing on NIP standard.
""" |
weights_for_check_digit = [6, 5, 7, 2, 3, 4, 5, 6, 7]
check_digit = 0
for i in range(0, 9):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 11
return check_digit |
<SYSTEM_TASK:>
Returns a dictionary.
<END_TASK>
<USER_TASK:>
Description:
def pydict(self, nb_elements=10, variable_nb_elements=True, *value_types):
"""
Returns a dictionary.
:nb_elements: number of elements for dictionary
:variable_nb_elements: is use variable number of elements for dictionary
:value_types: type of dictionary values
""" |
if variable_nb_elements:
nb_elements = self.randomize_nb_elements(nb_elements, min=1)
return dict(zip(
self.generator.words(nb_elements),
self._pyiterable(nb_elements, False, *value_types),
)) |
<SYSTEM_TASK:>
Calculate and return control digit for given list of digits based on
<END_TASK>
<USER_TASK:>
Description:
def checksum(digits):
"""
Calculate and return control digit for given list of digits based on
ISO7064, MOD 11,10 standard.
""" |
remainder = 10
for digit in digits:
remainder = (remainder + digit) % 10
if remainder == 0:
remainder = 10
remainder = (remainder * 2) % 11
control_digit = 11 - remainder
if control_digit == 10:
control_digit = 0
return control_digit |
<SYSTEM_TASK:>
Calculate checksum of Estonian personal identity code.
<END_TASK>
<USER_TASK:>
Description:
def checksum(digits):
"""Calculate checksum of Estonian personal identity code.
Checksum is calculated with "Modulo 11" method using level I or II scale:
Level I scale: 1 2 3 4 5 6 7 8 9 1
Level II scale: 3 4 5 6 7 8 9 1 2 3
The digits of the personal code are multiplied by level I scale and summed;
if remainder of modulo 11 of the sum is less than 10, checksum is the
remainder.
If remainder is 10, then level II scale is used; checksum is remainder if
remainder < 10 or 0 if remainder is 10.
See also https://et.wikipedia.org/wiki/Isikukood
""" |
sum_mod11 = sum(map(operator.mul, digits, Provider.scale1)) % 11
if sum_mod11 < 10:
return sum_mod11
sum_mod11 = sum(map(operator.mul, digits, Provider.scale2)) % 11
return 0 if sum_mod11 == 10 else sum_mod11 |
<SYSTEM_TASK:>
Optionally center the coord and pick a point within radius.
<END_TASK>
<USER_TASK:>
Description:
def coordinate(self, center=None, radius=0.001):
"""
Optionally center the coord and pick a point within radius.
""" |
if center is None:
return Decimal(str(self.generator.random.randint(-180000000, 180000000) / 1000000.0)).quantize(
Decimal(".000001"),
)
else:
center = float(center)
radius = float(radius)
geo = self.generator.random.uniform(center - radius, center + radius)
return Decimal(str(geo)).quantize(Decimal(".000001")) |
<SYSTEM_TASK:>
Calculates and returns a control digit for given list of digits basing on PESEL standard.
<END_TASK>
<USER_TASK:>
Description:
def checksum(digits):
"""
Calculates and returns a control digit for given list of digits basing on PESEL standard.
""" |
weights_for_check_digit = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
check_digit = 0
for i in range(0, 10):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 10
return check_digit |
<SYSTEM_TASK:>
Calculates and returns a month number basing on PESEL standard.
<END_TASK>
<USER_TASK:>
Description:
def calculate_month(birth_date):
"""
Calculates and returns a month number basing on PESEL standard.
""" |
year = int(birth_date.strftime('%Y'))
month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20
return month |
<SYSTEM_TASK:>
Returns a random integer between two values.
<END_TASK>
<USER_TASK:>
Description:
def random_int(self, min=0, max=9999, step=1):
"""
Returns a random integer between two values.
:param min: lower bound value (inclusive; default=0)
:param max: upper bound value (inclusive; default=9999)
:param step: range step (default=1)
:returns: random integer between min and max
""" |
return self.generator.random.randrange(min, max + 1, step) |
<SYSTEM_TASK:>
Returns a list of random, non-unique elements from a passed object.
<END_TASK>
<USER_TASK:>
Description:
def random_choices(self, elements=('a', 'b', 'c'), length=None):
"""
Returns a list of random, non-unique elements from a passed object.
If `elements` is a dictionary, the value will be used as
a weighting element. For example::
random_element({"{{variable_1}}": 0.5, "{{variable_2}}": 0.2, "{{variable_3}}": 0.2, "{{variable_4}}": 0.1})
will have the following distribution:
* `variable_1`: 50% probability
* `variable_2`: 20% probability
* `variable_3`: 20% probability
* `variable_4`: 10% probability
""" |
return self.random_elements(elements, length, unique=False) |
<SYSTEM_TASK:>
Returns a list of random unique elements for the specified length.
<END_TASK>
<USER_TASK:>
Description:
def random_sample(self, elements=('a', 'b', 'c'), length=None):
"""
Returns a list of random unique elements for the specified length.
Multiple occurrences of the same value increase its probability to be in the output.
""" |
return self.random_elements(elements, length, unique=True) |
<SYSTEM_TASK:>
Returns a random value near number.
<END_TASK>
<USER_TASK:>
Description:
def randomize_nb_elements(
self,
number=10,
le=False,
ge=False,
min=None,
max=None):
"""
Returns a random value near number.
:param number: value to which the result must be near
:param le: result must be lower or equal to number
:param ge: result must be greater or equal to number
:returns: a random int near number
""" |
if le and ge:
return number
_min = 100 if ge else 60
_max = 100 if le else 140
nb = int(number * self.generator.random.randint(_min, _max) / 100)
if min is not None and nb < min:
nb = min
if max is not None and nb > min:
nb = max
return nb |
<SYSTEM_TASK:>
Replaces all placeholders with random numbers and letters.
<END_TASK>
<USER_TASK:>
Description:
def bothify(self, text='## ??', letters=string.ascii_letters):
"""
Replaces all placeholders with random numbers and letters.
:param text: string to be parsed
:returns: string with all numerical and letter placeholders filled in
""" |
return self.lexify(self.numerify(text), letters=letters) |
<SYSTEM_TASK:>
Calculate checksum of Norwegian personal identity code.
<END_TASK>
<USER_TASK:>
Description:
def checksum(digits, scale):
"""
Calculate checksum of Norwegian personal identity code.
Checksum is calculated with "Module 11" method using a scale.
The digits of the personal code are multiplied by the corresponding
number in the scale and summed;
if remainder of module 11 of the sum is less than 10, checksum is the
remainder.
If remainder is 0, the checksum is 0.
https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
""" |
chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11)
if chk_nbr == 11:
return 0
return chk_nbr |
<SYSTEM_TASK:>
Returns the century code for a given year
<END_TASK>
<USER_TASK:>
Description:
def _get_century_code(year):
"""Returns the century code for a given year""" |
if 2000 <= year < 3000:
separator = 'A'
elif 1900 <= year < 2000:
separator = '-'
elif 1800 <= year < 1900:
separator = '+'
else:
raise ValueError('Finnish SSN do not support people born before the year 1800 or after the year 2999')
return separator |
<SYSTEM_TASK:>
Returns a 10 digit Swedish SSN, "Personnummer".
<END_TASK>
<USER_TASK:>
Description:
def ssn(self, min_age=18, max_age=90):
"""
Returns a 10 digit Swedish SSN, "Personnummer".
It consists of 10 digits in the form YYMMDD-SSGQ, where
YYMMDD is the date of birth, SSS is a serial number
and Q is a control character (Luhn checksum).
http://en.wikipedia.org/wiki/Personal_identity_number_(Sweden)
""" |
def _luhn_checksum(number):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d * 2))
return checksum % 10
def _calculate_luhn(partial_number):
check_digit = _luhn_checksum(int(partial_number) * 10)
return check_digit if check_digit == 0 else 10 - check_digit
age = datetime.timedelta(
days=self.generator.random.randrange(min_age * 365, max_age * 365))
birthday = datetime.datetime.now() - age
pnr_date = birthday.strftime('%y%m%d')
suffix = str(self.generator.random.randrange(0, 999)).zfill(3)
luhn_checksum = str(_calculate_luhn(pnr_date + suffix))
pnr = '{0}-{1}{2}'.format(pnr_date, suffix, luhn_checksum)
return pnr |
<SYSTEM_TASK:>
Generates a basic profile with personal informations
<END_TASK>
<USER_TASK:>
Description:
def simple_profile(self, sex=None):
"""
Generates a basic profile with personal informations
""" |
SEX = ["F", "M"]
if sex not in SEX:
sex = self.random_element(SEX)
if sex == 'F':
name = self.generator.name_female()
elif sex == 'M':
name = self.generator.name_male()
return {
"username": self.generator.user_name(),
"name": name,
"sex": sex,
"address": self.generator.address(),
"mail": self.generator.free_email(),
"birthdate": self.generator.date_of_birth(),
} |
<SYSTEM_TASK:>
Generates a complete profile.
<END_TASK>
<USER_TASK:>
Description:
def profile(self, fields=None, sex=None):
"""
Generates a complete profile.
If "fields" is not empty, only the fields in the list will be returned
""" |
if fields is None:
fields = []
d = {
"job": self.generator.job(),
"company": self.generator.company(),
"ssn": self.generator.ssn(),
"residence": self.generator.address(),
"current_location": (self.generator.latitude(), self.generator.longitude()),
"blood_group": "".join(self.random_element(list(itertools.product(["A", "B", "AB", "O"], ["+", "-"])))),
"website": [self.generator.url() for _ in range(1, self.random_int(2, 5))],
}
d = dict(d, **self.generator.simple_profile(sex))
# field selection
if len(fields) > 0:
d = {k: v for k, v in d.items() if k in fields}
return d |
<SYSTEM_TASK:>
Generate a safe datetime from a datetime.date or datetime.datetime object.
<END_TASK>
<USER_TASK:>
Description:
def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
""" |
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) |
<SYSTEM_TASK:>
Generate a random United States Taxpayer Identification Number of the specified type.
<END_TASK>
<USER_TASK:>
Description:
def ssn(self, taxpayer_identification_number_type=SSN_TYPE):
""" Generate a random United States Taxpayer Identification Number of the specified type.
If no type is specified, a US SSN is returned.
""" |
if taxpayer_identification_number_type == self.ITIN_TYPE:
return self.itin()
elif taxpayer_identification_number_type == self.EIN_TYPE:
return self.ein()
elif taxpayer_identification_number_type == self.SSN_TYPE:
# Certain numbers are invalid for United States Social Security
# Numbers. The area (first 3 digits) cannot be 666 or 900-999.
# The group number (middle digits) cannot be 00. The serial
# (last 4 digits) cannot be 0000.
area = self.random_int(min=1, max=899)
if area == 666:
area += 1
group = self.random_int(1, 99)
serial = self.random_int(1, 9999)
ssn = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial)
return ssn
else:
raise ValueError("taxpayer_identification_number_type must be one of 'SSN', 'EIN', or 'ITIN'.") |
<SYSTEM_TASK:>
Takes two DateTime objects and returns a random datetime between the two
<END_TASK>
<USER_TASK:>
Description:
def date_time_between_dates(
self,
datetime_start=None,
datetime_end=None,
tzinfo=None):
"""
Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects.
:param datetime_start: DateTime
:param datetime_end: DateTime
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 11:42:52')
:return DateTime
""" |
if datetime_start is None:
datetime_start = datetime.now(tzinfo)
if datetime_end is None:
datetime_end = datetime.now(tzinfo)
timestamp = self.generator.random.randint(
datetime_to_timestamp(datetime_start),
datetime_to_timestamp(datetime_end),
)
try:
if tzinfo is None:
pick = datetime.fromtimestamp(timestamp, tzlocal())
pick = pick.astimezone(tzutc()).replace(tzinfo=None)
else:
pick = datetime.fromtimestamp(timestamp, tzinfo)
except OverflowError:
raise OverflowError(
"You specified an end date with a timestamp bigger than the maximum allowed on this"
" system. Please specify an earlier date.",
)
return pick |
<SYSTEM_TASK:>
Gets a DateTime object for the current century.
<END_TASK>
<USER_TASK:>
Description:
def date_time_this_century(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current century.
:param before_now: include days in current century before today
:param after_now: include days in current century after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:return DateTime
""" |
now = datetime.now(tzinfo)
this_century_start = datetime(
now.year - (now.year % 100), 1, 1, tzinfo=tzinfo)
next_century_start = datetime(
min(this_century_start.year + 100, MAXYEAR), 1, 1, tzinfo=tzinfo)
if before_now and after_now:
return self.date_time_between_dates(
this_century_start, next_century_start, tzinfo)
elif not before_now and after_now:
return self.date_time_between_dates(now, next_century_start, tzinfo)
elif not after_now and before_now:
return self.date_time_between_dates(this_century_start, now, tzinfo)
else:
return now |
<SYSTEM_TASK:>
Gets a DateTime object for the decade year.
<END_TASK>
<USER_TASK:>
Description:
def date_time_this_decade(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the decade year.
:param before_now: include days in current decade before today
:param after_now: include days in current decade after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:return DateTime
""" |
now = datetime.now(tzinfo)
this_decade_start = datetime(
now.year - (now.year % 10), 1, 1, tzinfo=tzinfo)
next_decade_start = datetime(
min(this_decade_start.year + 10, MAXYEAR), 1, 1, tzinfo=tzinfo)
if before_now and after_now:
return self.date_time_between_dates(
this_decade_start, next_decade_start, tzinfo)
elif not before_now and after_now:
return self.date_time_between_dates(now, next_decade_start, tzinfo)
elif not after_now and before_now:
return self.date_time_between_dates(this_decade_start, now, tzinfo)
else:
return now |
<SYSTEM_TASK:>
Gets a DateTime object for the current year.
<END_TASK>
<USER_TASK:>
Description:
def date_time_this_year(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current year.
:param before_now: include days in current year before today
:param after_now: include days in current year after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:return DateTime
""" |
now = datetime.now(tzinfo)
this_year_start = now.replace(
month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
next_year_start = datetime(now.year + 1, 1, 1, tzinfo=tzinfo)
if before_now and after_now:
return self.date_time_between_dates(
this_year_start, next_year_start, tzinfo)
elif not before_now and after_now:
return self.date_time_between_dates(now, next_year_start, tzinfo)
elif not after_now and before_now:
return self.date_time_between_dates(this_year_start, now, tzinfo)
else:
return now |
<SYSTEM_TASK:>
Gets a DateTime object for the current month.
<END_TASK>
<USER_TASK:>
Description:
def date_time_this_month(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current month.
:param before_now: include days in current month before today
:param after_now: include days in current month after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:return DateTime
""" |
now = datetime.now(tzinfo)
this_month_start = now.replace(
day=1, hour=0, minute=0, second=0, microsecond=0)
next_month_start = this_month_start + \
relativedelta.relativedelta(months=1)
if before_now and after_now:
return self.date_time_between_dates(
this_month_start, next_month_start, tzinfo)
elif not before_now and after_now:
return self.date_time_between_dates(now, next_month_start, tzinfo)
elif not after_now and before_now:
return self.date_time_between_dates(this_month_start, now, tzinfo)
else:
return now |
<SYSTEM_TASK:>
Gets a Date object for the current century.
<END_TASK>
<USER_TASK:>
Description:
def date_this_century(self, before_today=True, after_today=False):
"""
Gets a Date object for the current century.
:param before_today: include days in current century before today
:param after_today: include days in current century after today
:example Date('2012-04-04')
:return Date
""" |
today = date.today()
this_century_start = date(today.year - (today.year % 100), 1, 1)
next_century_start = date(this_century_start.year + 100, 1, 1)
if before_today and after_today:
return self.date_between_dates(
this_century_start, next_century_start)
elif not before_today and after_today:
return self.date_between_dates(today, next_century_start)
elif not after_today and before_today:
return self.date_between_dates(this_century_start, today)
else:
return today |
<SYSTEM_TASK:>
Gets a Date object for the decade year.
<END_TASK>
<USER_TASK:>
Description:
def date_this_decade(self, before_today=True, after_today=False):
"""
Gets a Date object for the decade year.
:param before_today: include days in current decade before today
:param after_today: include days in current decade after today
:example Date('2012-04-04')
:return Date
""" |
today = date.today()
this_decade_start = date(today.year - (today.year % 10), 1, 1)
next_decade_start = date(this_decade_start.year + 10, 1, 1)
if before_today and after_today:
return self.date_between_dates(this_decade_start, next_decade_start)
elif not before_today and after_today:
return self.date_between_dates(today, next_decade_start)
elif not after_today and before_today:
return self.date_between_dates(this_decade_start, today)
else:
return today |
<SYSTEM_TASK:>
Gets a Date object for the current year.
<END_TASK>
<USER_TASK:>
Description:
def date_this_year(self, before_today=True, after_today=False):
"""
Gets a Date object for the current year.
:param before_today: include days in current year before today
:param after_today: include days in current year after today
:example Date('2012-04-04')
:return Date
""" |
today = date.today()
this_year_start = today.replace(month=1, day=1)
next_year_start = date(today.year + 1, 1, 1)
if before_today and after_today:
return self.date_between_dates(this_year_start, next_year_start)
elif not before_today and after_today:
return self.date_between_dates(today, next_year_start)
elif not after_today and before_today:
return self.date_between_dates(this_year_start, today)
else:
return today |
<SYSTEM_TASK:>
Gets a Date object for the current month.
<END_TASK>
<USER_TASK:>
Description:
def date_this_month(self, before_today=True, after_today=False):
"""
Gets a Date object for the current month.
:param before_today: include days in current month before today
:param after_today: include days in current month after today
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2012-04-04 11:02:02')
:return DateTime
""" |
today = date.today()
this_month_start = today.replace(day=1)
next_month_start = this_month_start + \
relativedelta.relativedelta(months=1)
if before_today and after_today:
return self.date_between_dates(this_month_start, next_month_start)
elif not before_today and after_today:
return self.date_between_dates(today, next_month_start)
elif not after_today and before_today:
return self.date_between_dates(this_month_start, today)
else:
return today |
<SYSTEM_TASK:>
Generate a random date of birth represented as a Date object,
<END_TASK>
<USER_TASK:>
Description:
def date_of_birth(self, tzinfo=None, minimum_age=0, maximum_age=115):
"""
Generate a random date of birth represented as a Date object,
constrained by optional miminimum_age and maximum_age
parameters.
:param tzinfo Defaults to None.
:param minimum_age Defaults to 0.
:param maximum_age Defaults to 115.
:example Date('1979-02-02')
:return Date
""" |
if not isinstance(minimum_age, int):
raise TypeError("minimum_age must be an integer.")
if not isinstance(maximum_age, int):
raise TypeError("maximum_age must be an integer.")
if (maximum_age < 0):
raise ValueError("maximum_age must be greater than or equal to zero.")
if (minimum_age < 0):
raise ValueError("minimum_age must be greater than or equal to zero.")
if (minimum_age > maximum_age):
raise ValueError("minimum_age must be less than or equal to maximum_age.")
# In order to return the full range of possible dates of birth, add one
# year to the potential age cap and subtract one day if we land on the
# boundary.
now = datetime.now(tzinfo).date()
start_date = now.replace(year=now.year - (maximum_age+1))
end_date = now.replace(year=now.year - minimum_age)
dob = self.date_time_ad(tzinfo=tzinfo, start_datetime=start_date, end_datetime=end_date).date()
return dob if dob != start_date else dob + timedelta(days=1) |
<SYSTEM_TASK:>
Adds two or more dicts together. Common keys will have their values added.
<END_TASK>
<USER_TASK:>
Description:
def add_dicts(*args):
"""
Adds two or more dicts together. Common keys will have their values added.
For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':1, 'c':3}
>>> t3 = {'d':4}
>>> add_dicts(t1, t2, t3)
{'a': 1, 'c': 3, 'b': 3, 'd': 4}
""" |
counters = [Counter(arg) for arg in args]
return dict(reduce(operator.add, counters)) |
<SYSTEM_TASK:>
Returns the provider's name of the credit card.
<END_TASK>
<USER_TASK:>
Description:
def credit_card_provider(self, card_type=None):
""" Returns the provider's name of the credit card. """ |
if card_type is None:
card_type = self.random_element(self.credit_card_types.keys())
return self._credit_card_type(card_type).name |
<SYSTEM_TASK:>
Returns a valid credit card number.
<END_TASK>
<USER_TASK:>
Description:
def credit_card_number(self, card_type=None):
""" Returns a valid credit card number. """ |
card = self._credit_card_type(card_type)
prefix = self.random_element(card.prefixes)
number = self._generate_number(self.numerify(prefix), card.length)
return number |
<SYSTEM_TASK:>
Returns a random credit card type instance.
<END_TASK>
<USER_TASK:>
Description:
def _credit_card_type(self, card_type=None):
""" Returns a random credit card type instance. """ |
if card_type is None:
card_type = self.random_element(self.credit_card_types.keys())
elif isinstance(card_type, CreditCard):
return card_type
return self.credit_card_types[card_type] |
<SYSTEM_TASK:>
Returns a 11 digits Belgian SSN called "rijksregisternummer" as a string
<END_TASK>
<USER_TASK:>
Description:
def ssn(self):
"""
Returns a 11 digits Belgian SSN called "rijksregisternummer" as a string
The first 6 digits represent the birthdate with (in order) year, month and day.
The second group of 3 digits is represents a sequence number (order of birth).
It is even for women and odd for men.
For men the range starts at 1 and ends 997, for women 2 until 998.
The third group of 2 digits is a checksum based on the previous 9 digits (modulo 97).
Divide those 9 digits by 97, subtract the remainder from 97 and that's the result.
For persons born in or after 2000, the 9 digit number needs to be proceeded by a 2
(add 2000000000) before the division by 97.
""" |
# see http://nl.wikipedia.org/wiki/Burgerservicenummer (in Dutch)
def _checksum(digits):
res = 97 - (digits % 97)
return res
# Generate a date (random)
mydate = self.generator.date()
# Convert it to an int
elms = mydate.split("-")
# Adjust for year 2000 if necessary
if elms[0][0] == '2':
above = True
else:
above = False
# Only keep the last 2 digits of the year
elms[0] = elms[0][2:4]
# Simulate the gender/sequence - should be 3 digits
seq = self.generator.random_int(1, 998)
# Right justify sequence and append to list
seq_str = "{:0>3}".format(seq)
elms.append(seq_str)
# Now convert list to an integer so the checksum can be calculated
date_as_int = int("".join(elms))
if above:
date_as_int += 2000000000
# Generate checksum
s = _checksum(date_as_int)
s_rjust = "{:0>2}".format(s)
# return result as a string
elms.append(s_rjust)
return "".join(elms) |
<SYSTEM_TASK:>
Determine validity of a Canadian Social Insurance Number.
<END_TASK>
<USER_TASK:>
Description:
def checksum(sin):
"""
Determine validity of a Canadian Social Insurance Number.
Validation is performed using a modified Luhn Algorithm. To check
the Every second digit of the SIN is doubled and the result is
summed. If the result is a multiple of ten, the Social Insurance
Number is considered valid.
https://en.wikipedia.org/wiki/Social_Insurance_Number
""" |
# Remove spaces and create a list of digits.
checksumCollection = list(sin.replace(' ', ''))
checksumCollection = [int(i) for i in checksumCollection]
# Discard the last digit, we will be calculating it later.
checksumCollection[-1] = 0
# Iterate over the provided SIN and double every second digit.
# In the case that doubling that digit results in a two-digit
# number, then add the two digits together and keep that sum.
for i in range(1, len(checksumCollection), 2):
result = checksumCollection[i] * 2
if result < 10:
checksumCollection[i] = result
else:
checksumCollection[i] = result - 10 + 1
# The appropriate checksum digit is the value that, when summed
# with the first eight values, results in a value divisible by 10
check_digit = 10 - (sum(checksumCollection) % 10)
check_digit = (0 if check_digit == 10 else check_digit)
return check_digit |
<SYSTEM_TASK:>
Produce a hostname with specified number of subdomain levels.
<END_TASK>
<USER_TASK:>
Description:
def hostname(self, levels=1):
"""
Produce a hostname with specified number of subdomain levels.
>>> hostname()
db-01.nichols-phillips.com
>>> hostname(0)
laptop-56
>>> hostname(2)
web-12.williamson-hopkins.jackson.com
""" |
if levels < 1:
return self.random_element(self.hostname_prefixes) + '-' + self.numerify('##')
return self.random_element(self.hostname_prefixes) + '-' + self.numerify('##') + '.' + self.domain_name(levels) |
<SYSTEM_TASK:>
Produce an Internet domain name with the specified number of
<END_TASK>
<USER_TASK:>
Description:
def domain_name(self, levels=1):
"""
Produce an Internet domain name with the specified number of
subdomain levels.
>>> domain_name()
nichols-phillips.com
>>> domain_name(2)
williamson-hopkins.jackson.com
""" |
if levels < 1:
raise ValueError("levels must be greater than or equal to 1")
if levels == 1:
return self.domain_word() + '.' + self.tld()
else:
return self.domain_word() + '.' + self.domain_name(levels - 1) |
<SYSTEM_TASK:>
Produces a random IPv4 address or network with a valid CIDR
<END_TASK>
<USER_TASK:>
Description:
def _random_ipv4_address_from_subnet(self, subnet, network=False):
"""
Produces a random IPv4 address or network with a valid CIDR
from within a given subnet.
:param subnet: IPv4Network to choose from within
:param network: Return a network address, and not an IP address
""" |
address = str(
subnet[self.generator.random.randint(
0, subnet.num_addresses - 1,
)],
)
if network:
address += '/' + str(self.generator.random.randint(
subnet.prefixlen,
subnet.max_prefixlen,
))
address = str(ip_network(address, strict=False))
return address |
<SYSTEM_TASK:>
Exclude the list of networks from another list of networks
<END_TASK>
<USER_TASK:>
Description:
def _exclude_ipv4_networks(self, networks, networks_to_exclude):
"""
Exclude the list of networks from another list of networks
and return a flat list of new networks.
:param networks: List of IPv4 networks to exclude from
:param networks_to_exclude: List of IPv4 networks to exclude
:returns: Flat list of IPv4 networks
""" |
for network_to_exclude in networks_to_exclude:
def _exclude_ipv4_network(network):
"""
Exclude a single network from another single network
and return a list of networks. Network to exclude
comes from the outer scope.
:param network: Network to exclude from
:returns: Flat list of IPv4 networks after exclusion.
If exclude fails because networks do not
overlap, a single element list with the
orignal network is returned. If it overlaps,
even partially, the network is excluded.
"""
try:
return list(network.address_exclude(network_to_exclude))
except ValueError:
# If networks overlap partially, `address_exclude`
# will fail, but the network still must not be used
# in generation.
if network.overlaps(network_to_exclude):
return []
else:
return [network]
networks = list(map(_exclude_ipv4_network, networks))
# flatten list of lists
networks = [
item for nested in networks for item in nested
]
return networks |
<SYSTEM_TASK:>
Produce a random IPv4 address or network with a valid CIDR.
<END_TASK>
<USER_TASK:>
Description:
def ipv4(self, network=False, address_class=None, private=None):
"""
Produce a random IPv4 address or network with a valid CIDR.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:param private: Public or private
:returns: IPv4
""" |
if private is True:
return self.ipv4_private(address_class=address_class,
network=network)
elif private is False:
return self.ipv4_public(address_class=address_class,
network=network)
# if neither private nor public is required explicitly,
# generate from whole requested address space
if address_class:
all_networks = [_IPv4Constants._network_classes[address_class]]
else:
# if no address class is choosen, use whole IPv4 pool
all_networks = [ip_network('0.0.0.0/0')]
# exclude special networks
all_networks = self._exclude_ipv4_networks(
all_networks,
_IPv4Constants._excluded_networks,
)
# choose random network from the list
random_network = self.generator.random.choice(all_networks)
return self._random_ipv4_address_from_subnet(random_network, network) |
<SYSTEM_TASK:>
Returns a private IPv4.
<END_TASK>
<USER_TASK:>
Description:
def ipv4_private(self, network=False, address_class=None):
"""
Returns a private IPv4.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:returns: Private IPv4
""" |
# compute private networks from given class
supernet = _IPv4Constants._network_classes[
address_class or self.ipv4_network_class()
]
private_networks = [
subnet for subnet in _IPv4Constants._private_networks
if subnet.overlaps(supernet)
]
# exclude special networks
private_networks = self._exclude_ipv4_networks(
private_networks,
_IPv4Constants._excluded_networks,
)
# choose random private network from the list
private_network = self.generator.random.choice(private_networks)
return self._random_ipv4_address_from_subnet(private_network, network) |
<SYSTEM_TASK:>
Returns a public IPv4 excluding private blocks.
<END_TASK>
<USER_TASK:>
Description:
def ipv4_public(self, network=False, address_class=None):
"""
Returns a public IPv4 excluding private blocks.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:returns: Public IPv4
""" |
# compute public networks
public_networks = [_IPv4Constants._network_classes[
address_class or self.ipv4_network_class()
]]
# exclude private and excluded special networks
public_networks = self._exclude_ipv4_networks(
public_networks,
_IPv4Constants._private_networks +
_IPv4Constants._excluded_networks,
)
# choose random public network from the list
public_network = self.generator.random.choice(public_networks)
return self._random_ipv4_address_from_subnet(public_network, network) |
<SYSTEM_TASK:>
Produce a random IPv6 address or network with a valid CIDR
<END_TASK>
<USER_TASK:>
Description:
def ipv6(self, network=False):
"""Produce a random IPv6 address or network with a valid CIDR""" |
address = str(ip_address(self.generator.random.randint(
2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1)))
if network:
address += '/' + str(self.generator.random.randint(0, IPV6LENGTH))
address = str(ip_network(address, strict=False))
return address |
<SYSTEM_TASK:>
This is a secure way to make a fake from another Provider.
<END_TASK>
<USER_TASK:>
Description:
def format(self, formatter, *args, **kwargs):
"""
This is a secure way to make a fake from another Provider.
""" |
# TODO: data export?
return self.get_formatter(formatter)(*args, **kwargs) |
<SYSTEM_TASK:>
Perform a forward execution and perform alias analysis. Note that this analysis is fast, light-weight, and by no
<END_TASK>
<USER_TASK:>
Description:
def _alias_analysis(self, mock_sp=True, mock_bp=True):
"""
Perform a forward execution and perform alias analysis. Note that this analysis is fast, light-weight, and by no
means complete. For instance, most arithmetic operations are not supported.
- Depending on user settings, stack pointer and stack base pointer will be mocked and propagated to individual
tmps.
:param bool mock_sp: propagate stack pointer or not
:param bool mock_bp: propagate stack base pointer or not
:return: None
""" |
state = SimLightState(
regs={
self._arch.sp_offset: self._arch.initial_sp,
self._arch.bp_offset: self._arch.initial_sp + 0x2000, # TODO: take care of the relation between sp and bp
},
temps={},
options={
'mock_sp': mock_sp,
'mock_bp': mock_bp,
}
)
for stmt_idx, stmt in list(enumerate(self._statements)):
self._forward_handler_stmt(stmt, state) |
<SYSTEM_TASK:>
Prepare the address space with the data necessary to perform relocations pointing to the given symbol.
<END_TASK>
<USER_TASK:>
Description:
def prepare_function_symbol(self, symbol_name, basic_addr=None):
"""
Prepare the address space with the data necessary to perform relocations pointing to the given symbol.
Returns a 2-tuple. The first item is the address of the function code, the second is the address of the
relocation target.
""" |
if self.project.loader.main_object.is_ppc64_abiv1:
if basic_addr is not None:
pointer = self.project.loader.memory.unpack_word(basic_addr)
return pointer, basic_addr
pseudo_hookaddr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)
pseudo_toc = self.project.loader.extern_object.allocate(size=0x18)
self.project.loader.extern_object.memory.pack_word(
AT.from_mva(pseudo_toc, self.project.loader.extern_object).to_rva(), pseudo_hookaddr)
return pseudo_hookaddr, pseudo_toc
else:
if basic_addr is None:
basic_addr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)
return basic_addr, basic_addr |
<SYSTEM_TASK:>
Set the fs register in the angr to the value of the fs register in the concrete process
<END_TASK>
<USER_TASK:>
Description:
def initialize_segment_register_x64(self, state, concrete_target):
"""
Set the fs register in the angr to the value of the fs register in the concrete process
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read the fs register
:return: None
""" |
_l.debug("Synchronizing fs segment register")
state.regs.fs = self._read_fs_register_x64(concrete_target) |
<SYSTEM_TASK:>
Create a GDT in the state memory and populate the segment registers.
<END_TASK>
<USER_TASK:>
Description:
def initialize_gdt_x86(self,state,concrete_target):
"""
Create a GDT in the state memory and populate the segment registers.
Rehook the vsyscall address using the real value in the concrete process memory
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read the fs register
:return:
""" |
_l.debug("Creating fake Global Descriptor Table and synchronizing gs segment register")
gs = self._read_gs_register_x86(concrete_target)
gdt = self.generate_gdt(0x0, gs)
self.setup_gdt(state, gdt)
# Synchronize the address of vsyscall in simprocedures dictionary with the concrete value
_vsyscall_address = concrete_target.read_memory(gs + 0x10, state.project.arch.bits / 8)
_vsyscall_address = struct.unpack(state.project.arch.struct_fmt(), _vsyscall_address)[0]
state.project.rehook_symbol(_vsyscall_address, '_vsyscall')
return gdt |
<SYSTEM_TASK:>
Merges this node with the other, returning a new node that spans the both.
<END_TASK>
<USER_TASK:>
Description:
def merge(self, other):
"""
Merges this node with the other, returning a new node that spans the both.
""" |
new_node = self.copy()
new_node.size += other.size
new_node.instruction_addrs += other.instruction_addrs
# FIXME: byte_string should never be none, but it is sometimes
# like, for example, patcherex test_cfg.py:test_fullcfg_properties
if new_node.byte_string is None or other.byte_string is None:
new_node.byte_string = None
else:
new_node.byte_string += other.byte_string
return new_node |
<SYSTEM_TASK:>
Allocates a new array in memory and returns the reference to the base.
<END_TASK>
<USER_TASK:>
Description:
def new_array(state, element_type, size):
"""
Allocates a new array in memory and returns the reference to the base.
""" |
size_bounded = SimSootExpr_NewArray._bound_array_size(state, size)
# return the reference of the array base
# => elements getting lazy initialized in the javavm memory
return SimSootValue_ArrayBaseRef(heap_alloc_id=state.javavm_memory.get_new_uuid(),
element_type=element_type,
size=size_bounded) |
<SYSTEM_TASK:>
Convert recovered reaching conditions from claripy ASTs to ailment Expressions
<END_TASK>
<USER_TASK:>
Description:
def _convert_claripy_bool_ast(self, cond):
"""
Convert recovered reaching conditions from claripy ASTs to ailment Expressions
:return: None
""" |
if isinstance(cond, ailment.Expr.Expression):
return cond
if cond.op == "BoolS" and claripy.is_true(cond):
return cond
if cond in self._condition_mapping:
return self._condition_mapping[cond]
_mapping = {
'Not': lambda cond_: ailment.Expr.UnaryOp(None, 'Not', self._convert_claripy_bool_ast(cond_.args[0])),
'And': lambda cond_: ailment.Expr.BinaryOp(None, 'LogicalAnd', (
self._convert_claripy_bool_ast(cond_.args[0]),
self._convert_claripy_bool_ast(cond_.args[1]),
)),
'Or': lambda cond_: ailment.Expr.BinaryOp(None, 'LogicalOr', (
self._convert_claripy_bool_ast(cond_.args[0]),
self._convert_claripy_bool_ast(cond_.args[1]),
)),
'ULE': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpULE',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'__le__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpLE',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'UGT': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpUGT',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'__gt__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpGT',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'__eq__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpEQ',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'__ne__': lambda cond_: ailment.Expr.BinaryOp(None, 'CmpNE',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'__xor__': lambda cond_: ailment.Expr.BinaryOp(None, 'Xor',
tuple(map(self._convert_claripy_bool_ast, cond_.args)),
),
'BVV': lambda cond_: ailment.Expr.Const(None, None, cond_.args[0], cond_.size()),
'BoolV': lambda cond_: ailment.Expr.Const(None, None, True, 1) if cond_.args[0] is True
else ailment.Expr.Const(None, None, False, 1),
}
if cond.op in _mapping:
return _mapping[cond.op](cond)
raise NotImplementedError(("Condition variable %s has an unsupported operator %s. "
"Consider implementing.") % (cond, cond.op)) |
<SYSTEM_TASK:>
Extract goto targets from a Jump or a ConditionalJump statement.
<END_TASK>
<USER_TASK:>
Description:
def _extract_jump_targets(stmt):
"""
Extract goto targets from a Jump or a ConditionalJump statement.
:param stmt: The statement to analyze.
:return: A list of known concrete jump targets.
:rtype: list
""" |
targets = [ ]
# FIXME: We are assuming all jump targets are concrete targets. They may not be.
if isinstance(stmt, ailment.Stmt.Jump):
targets.append(stmt.target.value)
elif isinstance(stmt, ailment.Stmt.ConditionalJump):
targets.append(stmt.true_target.value)
targets.append(stmt.false_target.value)
return targets |
<SYSTEM_TASK:>
A somewhat faithful implementation of libc `malloc`.
<END_TASK>
<USER_TASK:>
Description:
def malloc(self, sim_size):
"""
A somewhat faithful implementation of libc `malloc`.
:param sim_size: the amount of memory (in bytes) to be allocated
:returns: the address of the allocation, or a NULL pointer if the allocation failed
""" |
raise NotImplementedError("%s not implemented for %s" % (self.malloc.__func__.__name__,
self.__class__.__name__)) |
<SYSTEM_TASK:>
A somewhat faithful implementation of libc `free`.
<END_TASK>
<USER_TASK:>
Description:
def free(self, ptr): #pylint:disable=unused-argument
"""
A somewhat faithful implementation of libc `free`.
:param ptr: the location in memory to be freed
""" |
raise NotImplementedError("%s not implemented for %s" % (self.free.__func__.__name__,
self.__class__.__name__)) |
<SYSTEM_TASK:>
A somewhat faithful implementation of libc `calloc`.
<END_TASK>
<USER_TASK:>
Description:
def calloc(self, sim_nmemb, sim_size):
"""
A somewhat faithful implementation of libc `calloc`.
:param sim_nmemb: the number of elements to allocated
:param sim_size: the size of each element (in bytes)
:returns: the address of the allocation, or a NULL pointer if the allocation failed
""" |
raise NotImplementedError("%s not implemented for %s" % (self.calloc.__func__.__name__,
self.__class__.__name__)) |
<SYSTEM_TASK:>
A somewhat faithful implementation of libc `realloc`.
<END_TASK>
<USER_TASK:>
Description:
def realloc(self, ptr, size):
"""
A somewhat faithful implementation of libc `realloc`.
:param ptr: the location in memory to be reallocated
:param size: the new size desired for the allocation
:returns: the address of the allocation, or a NULL pointer if the allocation was freed or if no new allocation
was made
""" |
raise NotImplementedError("%s not implemented for %s" % (self.realloc.__func__.__name__,
self.__class__.__name__)) |
<SYSTEM_TASK:>
Initialize register values within the state
<END_TASK>
<USER_TASK:>
Description:
def set_regs(self, regs_dump):
"""
Initialize register values within the state
:param regs_dump: The output of ``info registers`` in gdb.
""" |
if self.real_stack_top == 0 and self.adjust_stack is True:
raise SimStateError("You need to set the stack first, or set"
"adjust_stack to False. Beware that in this case, sp and bp won't be updated")
data = self._read_data(regs_dump)
rdata = re.split(b"\n", data)
for r in rdata:
if r == b"":
continue
reg = re.split(b" +", r)[0].decode()
val = int(re.split(b" +", r)[1],16)
try:
self.state.registers.store(reg, claripy.BVV(val, self.state.arch.bits))
# Some registers such as cs, ds, eflags etc. aren't supported in angr
except KeyError as e:
l.warning("Reg %s was not set", e)
self._adjust_regs() |
<SYSTEM_TASK:>
Adjust bp and sp w.r.t. stack difference between GDB session and angr.
<END_TASK>
<USER_TASK:>
Description:
def _adjust_regs(self):
"""
Adjust bp and sp w.r.t. stack difference between GDB session and angr.
This matches sp and bp registers, but there is a high risk of pointers inconsistencies.
""" |
if not self.adjust_stack:
return
bp = self.state.arch.register_names[self.state.arch.bp_offset]
sp = self.state.arch.register_names[self.state.arch.sp_offset]
stack_shift = self.state.arch.initial_sp - self.real_stack_top
self.state.registers.store(sp, self.state.regs.sp + stack_shift)
if not self.omit_fp:
self.state.registers.store(bp, self.state.regs.bp + stack_shift) |
<SYSTEM_TASK:>
Create a Loop object for a strongly connected graph, and any strongly
<END_TASK>
<USER_TASK:>
Description:
def _parse_loop_graph(self, subg, bigg):
"""
Create a Loop object for a strongly connected graph, and any strongly
connected subgraphs, if possible.
:param subg: A strongly connected subgraph.
:param bigg: The graph which subg is a subgraph of.
:return: A list of Loop objects, some of which may be inside others,
but all need to be documented.
""" |
loop_body_nodes = list(subg.nodes())[:]
entry_edges = []
break_edges = []
continue_edges = []
entry_node = None
for node in loop_body_nodes:
for pred_node in bigg.predecessors(node):
if pred_node not in loop_body_nodes:
if entry_node is not None and entry_node != node:
l.warning("Bad loop: more than one entry point (%s, %s)", entry_node, node)
return None, []
entry_node = node
entry_edges.append((pred_node, node))
subg.add_edge(pred_node, node)
for succ_node in bigg.successors(node):
if succ_node not in loop_body_nodes:
break_edges.append((node, succ_node))
subg.add_edge(node, succ_node)
if entry_node is None:
entry_node = min(loop_body_nodes, key=lambda n: n.addr)
l.info("Couldn't find entry point, assuming it's the first by address (%s)", entry_node)
acyclic_subg = subg.copy()
for pred_node in subg.predecessors(entry_node):
if pred_node in loop_body_nodes:
continue_edge = (pred_node, entry_node)
acyclic_subg.remove_edge(*continue_edge)
continue_edges.append(continue_edge)
removed_exits = {}
removed_entries = {}
tops, alls = self._parse_loops_from_graph(acyclic_subg)
for subloop in tops:
if subloop.entry in loop_body_nodes:
# break existing entry edges, exit edges
# re-link in loop object
# the exception logic is to handle when you have two loops adjacent to each other
# you gotta link the two loops together and remove the dangling edge
for entry_edge in subloop.entry_edges:
try:
subg.remove_edge(*entry_edge)
except networkx.NetworkXError:
if entry_edge in removed_entries:
subg.add_edge(removed_entries[entry_edge], subloop)
try:
subg.remove_edge(removed_entries[entry_edge], entry_edge[1])
except networkx.NetworkXError:
pass
else:
raise
else:
subg.add_edge(entry_edge[0], subloop)
removed_entries[entry_edge] = subloop
for exit_edge in subloop.break_edges:
try:
subg.remove_edge(*exit_edge)
except networkx.NetworkXError:
if exit_edge in removed_entries:
subg.add_edge(subloop, removed_entries[exit_edge])
try:
subg.remove_edge(exit_edge[0], removed_entries[exit_edge])
except networkx.NetworkXError:
pass
else:
raise
else:
subg.add_edge(subloop, exit_edge[1])
removed_exits[exit_edge] = subloop
subg = next(filter(lambda g: entry_node in g.nodes(),
networkx.weakly_connected_component_subgraphs(subg)))
me = Loop(entry_node,
entry_edges,
break_edges,
continue_edges,
loop_body_nodes,
subg,
tops[:])
return me, [me] + alls |
<SYSTEM_TASK:>
Return all Loop instances that can be extracted from a graph.
<END_TASK>
<USER_TASK:>
Description:
def _parse_loops_from_graph(self, graph):
"""
Return all Loop instances that can be extracted from a graph.
:param graph: The graph to analyze.
:return: A list of all the Loop instances that were found in the graph.
""" |
outtop = []
outall = []
for subg in networkx.strongly_connected_component_subgraphs(graph):
if len(subg.nodes()) == 1:
if len(list(subg.successors(list(subg.nodes())[0]))) == 0:
continue
thisloop, allloops = self._parse_loop_graph(subg, graph)
if thisloop is not None:
outall += allloops
outtop.append(thisloop)
return outtop, outall |
<SYSTEM_TASK:>
Resolve the field within the given state.
<END_TASK>
<USER_TASK:>
Description:
def get_ref(cls, state, obj_alloc_id, field_class_name, field_name, field_type):
"""
Resolve the field within the given state.
""" |
# resolve field
field_class = state.javavm_classloader.get_class(field_class_name)
field_id = resolve_field(state, field_class, field_name, field_type)
# return field ref
return cls.from_field_id(obj_alloc_id, field_id) |
<SYSTEM_TASK:>
This function calculates the levenshtein distance but allows for elements in the lists to be different by any number
<END_TASK>
<USER_TASK:>
Description:
def _normalized_levenshtein_distance(s1, s2, acceptable_differences):
"""
This function calculates the levenshtein distance but allows for elements in the lists to be different by any number
in the set acceptable_differences.
:param s1: A list.
:param s2: Another list.
:param acceptable_differences: A set of numbers. If (s2[i]-s1[i]) is in the set then they are considered equal.
:returns:
""" |
if len(s1) > len(s2):
s1, s2 = s2, s1
acceptable_differences = set(-i for i in acceptable_differences)
distances = range(len(s1) + 1)
for index2, num2 in enumerate(s2):
new_distances = [index2 + 1]
for index1, num1 in enumerate(s1):
if num2 - num1 in acceptable_differences:
new_distances.append(distances[index1])
else:
new_distances.append(1 + min((distances[index1],
distances[index1+1],
new_distances[-1])))
distances = new_distances
return distances[-1] |
<SYSTEM_TASK:>
Compares two basic blocks and finds all the constants that differ from the first block to the second.
<END_TASK>
<USER_TASK:>
Description:
def differing_constants(block_a, block_b):
"""
Compares two basic blocks and finds all the constants that differ from the first block to the second.
:param block_a: The first block to compare.
:param block_b: The second block to compare.
:returns: Returns a list of differing constants in the form of ConstantChange, which has the offset in the
block and the respective constants.
""" |
statements_a = [s for s in block_a.vex.statements if s.tag != "Ist_IMark"] + [block_a.vex.next]
statements_b = [s for s in block_b.vex.statements if s.tag != "Ist_IMark"] + [block_b.vex.next]
if len(statements_a) != len(statements_b):
raise UnmatchedStatementsException("Blocks have different numbers of statements")
start_1 = min(block_a.instruction_addrs)
start_2 = min(block_b.instruction_addrs)
changes = []
# check statements
current_offset = None
for statement, statement_2 in zip(statements_a, statements_b):
# sanity check
if statement.tag != statement_2.tag:
raise UnmatchedStatementsException("Statement tag has changed")
if statement.tag == "Ist_IMark":
if statement.addr - start_1 != statement_2.addr - start_2:
raise UnmatchedStatementsException("Instruction length has changed")
current_offset = statement.addr - start_1
continue
differences = compare_statement_dict(statement, statement_2)
for d in differences:
if d.type != DIFF_VALUE:
raise UnmatchedStatementsException("Instruction has changed")
else:
changes.append(ConstantChange(current_offset, d.value_a, d.value_b))
return changes |
<SYSTEM_TASK:>
Compare two functions and return True if they appear identical.
<END_TASK>
<USER_TASK:>
Description:
def functions_probably_identical(self, func_a_addr, func_b_addr, check_consts=False):
"""
Compare two functions and return True if they appear identical.
:param func_a_addr: The address of the first function (in the first binary).
:param func_b_addr: The address of the second function (in the second binary).
:returns: Whether or not the functions appear to be identical.
""" |
if self.cfg_a.project.is_hooked(func_a_addr) and self.cfg_b.project.is_hooked(func_b_addr):
return self.cfg_a.project._sim_procedures[func_a_addr] == self.cfg_b.project._sim_procedures[func_b_addr]
func_diff = self.get_function_diff(func_a_addr, func_b_addr)
if check_consts:
return func_diff.probably_identical_with_consts
return func_diff.probably_identical |
<SYSTEM_TASK:>
Load a new project based on a string of raw bytecode.
<END_TASK>
<USER_TASK:>
Description:
def load_shellcode(shellcode, arch, start_offset=0, load_address=0):
"""
Load a new project based on a string of raw bytecode.
:param shellcode: The data to load
:param arch: The name of the arch to use, or an archinfo class
:param start_offset: The offset into the data to start analysis (default 0)
:param load_address: The address to place the data in memory (default 0)
""" |
return Project(
BytesIO(shellcode),
main_opts={
'backend': 'blob',
'arch': arch,
'entry_point': start_offset,
'base_addr': load_address,
}
) |
<SYSTEM_TASK:>
Has symbol name `f` been marked for exclusion by any of the user
<END_TASK>
<USER_TASK:>
Description:
def _check_user_blacklists(self, f):
"""
Has symbol name `f` been marked for exclusion by any of the user
parameters?
""" |
return not self._should_use_sim_procedures or \
f in self._exclude_sim_procedures_list or \
f in self._ignore_functions or \
(self._exclude_sim_procedures_func is not None and self._exclude_sim_procedures_func(f)) |
<SYSTEM_TASK:>
Hook a section of code with a custom function. This is used internally to provide symbolic
<END_TASK>
<USER_TASK:>
Description:
def hook(self, addr, hook=None, length=0, kwargs=None, replace=False):
"""
Hook a section of code with a custom function. This is used internally to provide symbolic
summaries of library functions, and can be used to instrument execution or to modify
control flow.
When hook is not specified, it returns a function decorator that allows easy hooking.
Usage::
# Assuming proj is an instance of angr.Project, we will add a custom hook at the entry
# point of the project.
@proj.hook(proj.entry)
def my_hook(state):
print("Welcome to execution!")
:param addr: The address to hook.
:param hook: A :class:`angr.project.Hook` describing a procedure to run at the
given address. You may also pass in a SimProcedure class or a function
directly and it will be wrapped in a Hook object for you.
:param length: If you provide a function for the hook, this is the number of bytes
that will be skipped by executing the hook by default.
:param kwargs: If you provide a SimProcedure for the hook, these are the keyword
arguments that will be passed to the procedure's `run` method
eventually.
:param replace: Control the behavior on finding that the address is already hooked. If
true, silently replace the hook. If false (default), warn and do not
replace the hook. If none, warn and replace the hook.
""" |
if hook is None:
# if we haven't been passed a thing to hook with, assume we're being used as a decorator
return self._hook_decorator(addr, length=length, kwargs=kwargs)
if kwargs is None: kwargs = {}
l.debug('hooking %s with %s', self._addr_to_str(addr), str(hook))
if self.is_hooked(addr):
if replace is True:
pass
elif replace is False:
l.warning("Address is already hooked, during hook(%s, %s). Not re-hooking.", self._addr_to_str(addr), hook)
return
else:
l.warning("Address is already hooked, during hook(%s, %s). Re-hooking.", self._addr_to_str(addr), hook)
if isinstance(hook, type):
raise TypeError("Please instanciate your SimProcedure before hooking with it")
if callable(hook):
hook = SIM_PROCEDURES['stubs']['UserHook'](user_func=hook, length=length, **kwargs)
self._sim_procedures[addr] = hook |
<SYSTEM_TASK:>
Returns the current hook for `addr`.
<END_TASK>
<USER_TASK:>
Description:
def hooked_by(self, addr):
"""
Returns the current hook for `addr`.
:param addr: An address.
:returns: None if the address is not hooked.
""" |
if not self.is_hooked(addr):
l.warning("Address %s is not hooked", self._addr_to_str(addr))
return None
return self._sim_procedures[addr] |
<SYSTEM_TASK:>
Remove a hook.
<END_TASK>
<USER_TASK:>
Description:
def unhook(self, addr):
"""
Remove a hook.
:param addr: The address of the hook.
""" |
if not self.is_hooked(addr):
l.warning("Address %s not hooked", self._addr_to_str(addr))
return
del self._sim_procedures[addr] |
<SYSTEM_TASK:>
Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that
<END_TASK>
<USER_TASK:>
Description:
def hook_symbol(self, symbol_name, simproc, kwargs=None, replace=None):
"""
Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that
address. If the symbol was not available in the loaded libraries, this address may be provided
by the CLE externs object.
Additionally, if instead of a symbol name you provide an address, some secret functionality will
kick in and you will probably just hook that address, UNLESS you're on powerpc64 ABIv1 or some
yet-unknown scary ABI that has its function pointers point to something other than the actual
functions, in which case it'll do the right thing.
:param symbol_name: The name of the dependency to resolve.
:param simproc: The SimProcedure instance (or function) with which to hook the symbol
:param kwargs: If you provide a SimProcedure for the hook, these are the keyword
arguments that will be passed to the procedure's `run` method
eventually.
:param replace: Control the behavior on finding that the address is already hooked. If
true, silently replace the hook. If false, warn and do not replace the
hook. If none (default), warn and replace the hook.
:returns: The address of the new symbol.
:rtype: int
""" |
if type(symbol_name) is not int:
sym = self.loader.find_symbol(symbol_name)
if sym is None:
# it could be a previously unresolved weak symbol..?
new_sym = None
for reloc in self.loader.find_relevant_relocations(symbol_name):
if not reloc.symbol.is_weak:
raise Exception("Symbol is strong but we couldn't find its resolution? Report to @rhelmot.")
if new_sym is None:
new_sym = self.loader.extern_object.make_extern(symbol_name)
reloc.resolve(new_sym)
reloc.relocate([])
if new_sym is None:
l.error("Could not find symbol %s", symbol_name)
return None
sym = new_sym
basic_addr = sym.rebased_addr
else:
basic_addr = symbol_name
symbol_name = None
hook_addr, _ = self.simos.prepare_function_symbol(symbol_name, basic_addr=basic_addr)
self.hook(hook_addr, simproc, kwargs=kwargs, replace=replace)
return hook_addr |
<SYSTEM_TASK:>
Check if a symbol is already hooked.
<END_TASK>
<USER_TASK:>
Description:
def is_symbol_hooked(self, symbol_name):
"""
Check if a symbol is already hooked.
:param str symbol_name: Name of the symbol.
:return: True if the symbol can be resolved and is hooked, False otherwise.
:rtype: bool
""" |
sym = self.loader.find_symbol(symbol_name)
if sym is None:
l.warning("Could not find symbol %s", symbol_name)
return False
hook_addr, _ = self.simos.prepare_function_symbol(symbol_name, basic_addr=sym.rebased_addr)
return self.is_hooked(hook_addr) |
<SYSTEM_TASK:>
Remove the hook on a symbol.
<END_TASK>
<USER_TASK:>
Description:
def unhook_symbol(self, symbol_name):
"""
Remove the hook on a symbol.
This function will fail if the symbol is provided by the extern object, as that would result in a state where
analysis would be unable to cope with a call to this symbol.
""" |
sym = self.loader.find_symbol(symbol_name)
if sym is None:
l.warning("Could not find symbol %s", symbol_name)
return False
if sym.owner is self.loader._extern_object:
l.warning("Refusing to unhook external symbol %s, replace it with another hook if you want to change it",
symbol_name)
return False
hook_addr, _ = self.simos.prepare_function_symbol(symbol_name, basic_addr=sym.rebased_addr)
self.unhook(hook_addr)
return True |
<SYSTEM_TASK:>
Indicates if the project's main binary is a Java Archive.
<END_TASK>
<USER_TASK:>
Description:
def is_java_project(self):
"""
Indicates if the project's main binary is a Java Archive.
""" |
if self._is_java_project is None:
self._is_java_project = isinstance(self.arch, ArchSoot)
return self._is_java_project |
<SYSTEM_TASK:>
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to
<END_TASK>
<USER_TASK:>
Description:
def register_preset(cls, name, preset):
"""
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to
automatically register themselves with a preset by using a classmethod of their own with only the name of the
preset to register with.
""" |
if cls._presets is None:
cls._presets = {}
cls._presets[name] = preset |
<SYSTEM_TASK:>
Apply a preset to the hub. If there was a previously active preset, discard it.
<END_TASK>
<USER_TASK:>
Description:
def use_plugin_preset(self, preset):
"""
Apply a preset to the hub. If there was a previously active preset, discard it.
Preset can be either the string name of a preset or a PluginPreset instance.
""" |
if isinstance(preset, str):
try:
preset = self._presets[preset]
except (AttributeError, KeyError):
raise AngrNoPluginError("There is no preset named %s" % preset)
elif not isinstance(preset, PluginPreset):
raise ValueError("Argument must be an instance of PluginPreset: %s" % preset)
if self._active_preset:
l.warning("Overriding active preset %s with %s", self._active_preset, preset)
self.discard_plugin_preset()
preset.activate(self)
self._active_preset = preset |
<SYSTEM_TASK:>
Discard the current active preset. Will release any active plugins that could have come from the old preset.
<END_TASK>
<USER_TASK:>
Description:
def discard_plugin_preset(self):
"""
Discard the current active preset. Will release any active plugins that could have come from the old preset.
""" |
if self.has_plugin_preset:
for name, plugin in list(self._active_plugins.items()):
if id(plugin) in self._provided_by_preset:
self.release_plugin(name)
self._active_preset.deactivate(self)
self._active_preset = None |
<SYSTEM_TASK:>
Get the plugin named ``name``. If no such plugin is currently active, try to activate a new
<END_TASK>
<USER_TASK:>
Description:
def get_plugin(self, name):
"""
Get the plugin named ``name``. If no such plugin is currently active, try to activate a new
one using the current preset.
""" |
if name in self._active_plugins:
return self._active_plugins[name]
elif self.has_plugin_preset:
plugin_cls = self._active_preset.request_plugin(name)
plugin = self._init_plugin(plugin_cls)
# Remember that this plugin was provided by preset.
self._provided_by_preset.append(id(plugin))
self.register_plugin(name, plugin)
return plugin
else:
raise AngrNoPluginError("No such plugin: %s" % name) |
<SYSTEM_TASK:>
Add a new plugin ``plugin`` with name ``name`` to the active plugins.
<END_TASK>
<USER_TASK:>
Description:
def register_plugin(self, name, plugin):
"""
Add a new plugin ``plugin`` with name ``name`` to the active plugins.
""" |
if self.has_plugin(name):
self.release_plugin(name)
self._active_plugins[name] = plugin
setattr(self, name, plugin)
return plugin |
<SYSTEM_TASK:>
Deactivate and remove the plugin with name ``name``.
<END_TASK>
<USER_TASK:>
Description:
def release_plugin(self, name):
"""
Deactivate and remove the plugin with name ``name``.
""" |
plugin = self._active_plugins[name]
if id(plugin) in self._provided_by_preset:
self._provided_by_preset.remove(id(plugin))
del self._active_plugins[name]
delattr(self, name) |
<SYSTEM_TASK:>
Grabs the concretized result so we can add the constraint ourselves.
<END_TASK>
<USER_TASK:>
Description:
def _grab_concretization_results(cls, state):
"""
Grabs the concretized result so we can add the constraint ourselves.
""" |
# only grab ones that match the constrained addrs
if cls._should_add_constraints(state):
addr = state.inspect.address_concretization_expr
result = state.inspect.address_concretization_result
if result is None:
l.warning("addr concretization result is None")
return
state.preconstrainer.address_concretization.append((addr, result)) |
<SYSTEM_TASK:>
Check to see if the current address concretization variable is any of the registered
<END_TASK>
<USER_TASK:>
Description:
def _should_add_constraints(cls, state):
"""
Check to see if the current address concretization variable is any of the registered
constrained_addrs we want to allow concretization for
""" |
expr = state.inspect.address_concretization_expr
hit_indices = cls._to_indices(state, expr)
for action in state.preconstrainer._constrained_addrs:
var_indices = cls._to_indices(state, action.addr)
if var_indices == hit_indices:
return True
return False |
<SYSTEM_TASK:>
The actual allocation primitive for this heap implementation. Increases the position of the break to allocate
<END_TASK>
<USER_TASK:>
Description:
def allocate(self, sim_size):
"""
The actual allocation primitive for this heap implementation. Increases the position of the break to allocate
space. Has no guards against the heap growing too large.
:param sim_size: a size specifying how much to increase the break pointer by
:returns: a pointer to the previous break position, above which there is now allocated space
""" |
size = self._conc_alloc_size(sim_size)
addr = self.state.heap.heap_location
self.state.heap.heap_location += size
l.debug("Allocating %d bytes at address %#08x", size, addr)
return addr |
<SYSTEM_TASK:>
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate
<END_TASK>
<USER_TASK:>
Description:
def release(self, sim_size):
"""
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate
space. Guards against releasing beyond the initial heap base.
:param sim_size: a size specifying how much to decrease the break pointer by (may be symbolic or not)
""" |
requested = self._conc_alloc_size(sim_size)
used = self.heap_location - self.heap_base
released = requested if requested <= used else used
self.heap_location -= released
l.debug("Releasing %d bytes from the heap (%d bytes were requested to be released)", released, requested) |
<SYSTEM_TASK:>
Get the function name from a C-style function declaration string.
<END_TASK>
<USER_TASK:>
Description:
def get_function_name(s):
"""
Get the function name from a C-style function declaration string.
:param str s: A C-style function declaration string.
:return: The function name.
:rtype: str
""" |
s = s.strip()
if s.startswith("__attribute__"):
# Remove "__attribute__ ((foobar))"
if "))" not in s:
raise ValueError("__attribute__ is present, but I cannot find double-right parenthesis in the function "
"declaration string.")
s = s[s.index("))") + 2 : ].strip()
if '(' not in s:
raise ValueError("Cannot find any left parenthesis in the function declaration string.")
func_name = s[:s.index('(')].strip()
for i, ch in enumerate(reversed(func_name)):
if ch == ' ':
pos = len(func_name) - 1 - i
break
else:
raise ValueError('Cannot find any space in the function declaration string.')
func_name = func_name[pos + 1 : ]
return func_name |
<SYSTEM_TASK:>
Convert a C-style function declaration string to its corresponding SimTypes-based Python representation.
<END_TASK>
<USER_TASK:>
Description:
def convert_cproto_to_py(c_decl):
"""
Convert a C-style function declaration string to its corresponding SimTypes-based Python representation.
:param str c_decl: The C-style function declaration string.
:return: A tuple of the function name, the prototype, and a string representing the
SimType-based Python representation.
:rtype: tuple
""" |
s = [ ]
try:
s.append('# %s' % c_decl) # comment string
parsed = parse_file(c_decl)
parsed_decl = parsed[0]
if not parsed_decl:
raise ValueError('Cannot parse the function prototype.')
func_name, func_proto = next(iter(parsed_decl.items()))
s.append('"%s": %s,' % (func_name, func_proto._init_str())) # The real Python string
except Exception: # pylint:disable=broad-except
# Silently catch all parsing errors... supporting all function declarations is impossible
try:
func_name = get_function_name(c_decl)
func_proto = None
s.append('"%s": None,' % func_name)
except ValueError:
# Failed to extract the function name. Is it a function declaration?
func_name, func_proto = None, None
return func_name, func_proto, "\n".join(s) |
<SYSTEM_TASK:>
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if
<END_TASK>
<USER_TASK:>
Description:
def is_prev_free(self):
"""
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if
that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free.
:returns: True if the previous chunk is free; False otherwise
""" |
flag = self.state.memory.load(self.base + self._chunk_size_t_size, self._chunk_size_t_size) & CHUNK_P_MASK
def sym_flag_handler(flag):
l.warning("A chunk's P flag is symbolic; assuming it is not set")
return self.state.solver.min_int(flag)
flag = concretize(flag, self.state.solver, sym_flag_handler)
return False if flag else True |
<SYSTEM_TASK:>
Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in
<END_TASK>
<USER_TASK:>
Description:
def fwd_chunk(self):
"""
Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in
no such list and this method raises an error.
:returns: If possible, the forward chunk; otherwise, raises an error
""" |
if self.is_free():
base = self.state.memory.load(self.base + 2 * self._chunk_size_t_size, self._chunk_size_t_size)
return PTChunk(base, self.state)
else:
raise SimHeapError("Attempted to access the forward chunk of an allocated chunk") |
<SYSTEM_TASK:>
Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head
<END_TASK>
<USER_TASK:>
Description:
def _find_bck(self, chunk):
"""
Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head
and all other metadata are unaltered by this function.
""" |
cur = self.free_head_chunk
if cur is None:
return None
fwd = cur.fwd_chunk()
if cur == fwd:
return cur
# At this point there should be at least two free chunks in the heap
if cur < chunk:
while cur < fwd < chunk:
cur = fwd
fwd = cur.fwd_chunk()
return cur
else:
while fwd != self.free_head_chunk:
cur = fwd
fwd = cur.fwd_chunk()
return cur |
<SYSTEM_TASK:>
Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages
<END_TASK>
<USER_TASK:>
Description:
def _set_final_freeness(self, flag):
"""
Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages
this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk.
""" |
if flag:
self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, ~CHUNK_P_MASK)
else:
self.state.memory.store(self.heap_base + self.heap_size - self._chunk_size_t_size, CHUNK_P_MASK) |
<SYSTEM_TASK:>
Takes an allocation size as requested by the user and modifies it to be a suitable chunk size.
<END_TASK>
<USER_TASK:>
Description:
def _make_chunk_size(self, req_size):
"""
Takes an allocation size as requested by the user and modifies it to be a suitable chunk size.
""" |
size = req_size
size += 2 * self._chunk_size_t_size # Two size fields
size = self._chunk_min_size if size < self._chunk_min_size else size
if size & self._chunk_align_mask: # If the chunk would not be aligned
size = (size & ~self._chunk_align_mask) + self._chunk_align_mask + 1 # Fix it
return size |
<SYSTEM_TASK:>
Allocate and initialize a new string in the context of the state passed.
<END_TASK>
<USER_TASK:>
Description:
def new_string(state, value):
"""
Allocate and initialize a new string in the context of the state passed.
The method returns the reference to the newly allocated string
:param state: angr state where we want to allocate the string
:type SimState
:param value: value of the string to initialize
:type claripy.String
:return SimSootValue_StringRef
""" |
str_ref = SimSootValue_StringRef(state.memory.get_new_uuid())
state.memory.store(str_ref, value)
return str_ref |
<SYSTEM_TASK:>
loads a number from addr, and returns a condition that addr must start with the prefix
<END_TASK>
<USER_TASK:>
Description:
def _load_num_with_prefix(prefix, addr, region, state, base, signed, read_length=None):
"""
loads a number from addr, and returns a condition that addr must start with the prefix
""" |
length = len(prefix)
read_length = (read_length-length) if read_length else None
condition, value, num_bytes = strtol._string_to_int(addr+length, state, region, base, signed, read_length)
# the prefix must match
if len(prefix) > 0:
loaded_prefix = region.load(addr, length)
condition = state.solver.And(loaded_prefix == state.solver.BVV(prefix), condition)
total_num_bytes = num_bytes + length
# negatives
if prefix.startswith(b"-"):
value = state.solver.BVV(0, state.arch.bits) - value
return condition, value, total_num_bytes |
<SYSTEM_TASK:>
reads values from s and generates the symbolic number that it would equal
<END_TASK>
<USER_TASK:>
Description:
def _string_to_int(s, state, region, base, signed, read_length=None):
"""
reads values from s and generates the symbolic number that it would equal
the first char is either a number in the given base, or the result is 0
expression indicates whether or not it was successful
""" |
# if length wasn't provided, read the maximum bytes
length = state.libc.max_strtol_len if read_length is None else read_length
# expression whether or not it was valid at all
expression, _ = strtol._char_to_val(region.load(s, 1), base)
cases = []
# to detect overflows we keep it in a larger bv and extract it at the end
num_bits = min(state.arch.bits*2, 128)
current_val = state.solver.BVV(0, num_bits)
num_bytes = state.solver.BVS("num_bytes", state.arch.bits)
constraints_num_bytes = []
conditions = []
cutoff = False
# we need all the conditions to hold except the last one to have found a value
for i in range(length):
char = region.load(s + i, 1)
condition, value = strtol._char_to_val(char, base)
# if it was the end we'll get the current val
cases.append((num_bytes == i, current_val))
# identify the constraints necessary to set num_bytes to the current value
# the current char (i.e. the terminator if this is satisfied) should not be a char,
# so `condition` should be false, plus all the previous conditions should be satisfied
case_constraints = conditions + [state.solver.Not(condition)] + [num_bytes == i]
constraints_num_bytes.append(state.solver.And(*case_constraints))
# break the loop early if no value past this is viable
if condition.is_false():
cutoff = True # ???
break
# add the value and the condition
current_val = current_val*base + value.zero_extend(num_bits-8)
conditions.append(condition)
# the last one is unterminated, let's ignore it
if not cutoff:
cases.append((num_bytes == length, current_val))
case_constraints = conditions + [num_bytes == length]
constraints_num_bytes.append(state.solver.And(*case_constraints))
# only one of the constraints need to hold
# since the constraints look like (num_bytes == 2 and the first 2 chars are valid, and the 3rd isn't)
final_constraint = state.solver.Or(*constraints_num_bytes)
if final_constraint.op == '__eq__' and final_constraint.args[0] is num_bytes and not final_constraint.args[1].symbolic:
# CONCRETE CASE
result = cases[state.solver.eval(final_constraint.args[1])][1]
num_bytes = final_constraint.args[1]
else:
# symbolic case
state.add_constraints(final_constraint)
result = state.solver.ite_cases(cases, 0)
# overflow check
max_bits = state.arch.bits-1 if signed else state.arch.bits
max_val = 2**max_bits - 1
result = state.solver.If(result < max_val, state.solver.Extract(state.arch.bits-1, 0, result),
state.solver.BVV(max_val, state.arch.bits))
return expression, result, num_bytes |
<SYSTEM_TASK:>
converts a symbolic char to a number in the given base
<END_TASK>
<USER_TASK:>
Description:
def _char_to_val(char, base):
"""
converts a symbolic char to a number in the given base
returns expression, result
expression is a symbolic boolean indicating whether or not it was a valid number
result is the value
""" |
cases = []
# 0-9
max_digit = claripy.BVV(b"9")
min_digit = claripy.BVV(b"0")
if base < 10:
max_digit = claripy.BVV(ord("0") + base, 8)
is_digit = claripy.And(char >= min_digit, char <= max_digit)
# return early here so we don't add unnecessary statements
if base <= 10:
return is_digit, char - min_digit
# handle alphabetic chars
max_char_lower = claripy.BVV(ord("a") + base-10 - 1, 8)
max_char_upper = claripy.BVV(ord("A") + base-10 - 1, 8)
min_char_lower = claripy.BVV(ord("a"), 8)
min_char_upper = claripy.BVV(ord("A"), 8)
cases.append((is_digit, char - min_digit))
is_alpha_lower = claripy.And(char >= min_char_lower, char <= max_char_lower)
cases.append((is_alpha_lower, char - min_char_lower + 10))
is_alpha_upper = claripy.And(char >= min_char_upper, char <= max_char_upper)
cases.append((is_alpha_upper, char - min_char_upper + 10))
expression = claripy.Or(is_digit, is_alpha_lower, is_alpha_upper)
# use the last case as the default, the expression will encode whether or not it's satisfiable
result = claripy.ite_cases(cases[:-1], cases[-1][1])
return expression, result |
<SYSTEM_TASK:>
Implement printf - based on the stored format specifier information, format the values from the arg getter function `args` into a string.
<END_TASK>
<USER_TASK:>
Description:
def replace(self, startpos, args):
"""
Implement printf - based on the stored format specifier information, format the values from the arg getter function `args` into a string.
:param startpos: The index of the first argument to be used by the first element of the format string
:param args: A function which, given an argument index, returns the integer argument to the current function at that index
:return: The result formatted string
""" |
argpos = startpos
string = None
for component in self.components:
# if this is just concrete data
if isinstance(component, bytes):
string = self._add_to_string(string, self.parser.state.solver.BVV(component))
elif isinstance(component, str):
raise Exception("this branch should be impossible?")
elif isinstance(component, claripy.ast.BV):
string = self._add_to_string(string, component)
else:
# okay now for the interesting stuff
# what type of format specifier is it?
fmt_spec = component
if fmt_spec.spec_type == b's':
if fmt_spec.length_spec == b".*":
str_length = args(argpos)
argpos += 1
else:
str_length = None
str_ptr = args(argpos)
string = self._add_to_string(string, self._get_str_at(str_ptr, max_length=str_length))
# integers, for most of these we'll end up concretizing values..
else:
i_val = args(argpos)
c_val = int(self.parser.state.solver.eval(i_val))
c_val &= (1 << (fmt_spec.size * 8)) - 1
if fmt_spec.signed and (c_val & (1 << ((fmt_spec.size * 8) - 1))):
c_val -= (1 << fmt_spec.size * 8)
if fmt_spec.spec_type in (b'd', b'i'):
s_val = str(c_val)
elif fmt_spec.spec_type == b'u':
s_val = str(c_val)
elif fmt_spec.spec_type == b'c':
s_val = chr(c_val & 0xff)
elif fmt_spec.spec_type == b'x':
s_val = hex(c_val)[2:]
elif fmt_spec.spec_type == b'o':
s_val = oct(c_val)[2:]
elif fmt_spec.spec_type == b'p':
s_val = hex(c_val)
else:
raise SimProcedureError("Unimplemented format specifier '%s'" % fmt_spec.spec_type)
string = self._add_to_string(string, self.parser.state.solver.BVV(s_val.encode()))
argpos += 1
return string |
<SYSTEM_TASK:>
All specifiers and their lengths.
<END_TASK>
<USER_TASK:>
Description:
def _all_spec(self):
"""
All specifiers and their lengths.
""" |
base = self._mod_spec
for spec in self.basic_spec:
base[spec] = self.basic_spec[spec]
return base |
<SYSTEM_TASK:>
match the string `nugget` to a format specifier.
<END_TASK>
<USER_TASK:>
Description:
def _match_spec(self, nugget):
"""
match the string `nugget` to a format specifier.
""" |
# TODO: handle positional modifiers and other similar format string tricks.
all_spec = self._all_spec
# iterate through nugget throwing away anything which is an int
# TODO store this in a size variable
original_nugget = nugget
length_str = [ ]
length_spec = None
length_spec_str_len = 0
if nugget.startswith(b".*"):
# ".*": precision is specified as an argument
nugget = nugget[2:]
length_spec = b".*"
length_spec_str_len = 2
for j, c in enumerate(nugget):
if c in ascii_digits:
length_str.append(c)
else:
nugget = nugget[j:]
if length_spec is None:
length_spec = None if len(length_str) == 0 else int(bytes(length_str))
break
# we need the length of the format's length specifier to extract the format and nothing else
if length_spec_str_len == 0 and length_str:
length_spec_str_len = len(length_str)
# is it an actual format?
for spec in all_spec:
if nugget.startswith(spec):
# this is gross coz sim_type is gross..
nugget = nugget[:len(spec)]
original_nugget = original_nugget[:(length_spec_str_len + len(spec))]
nugtype = all_spec[nugget]
try:
typeobj = sim_type.parse_type(nugtype).with_arch(self.state.arch)
except:
raise SimProcedureError("format specifier uses unknown type '%s'" % repr(nugtype))
return FormatSpecifier(original_nugget, length_spec, typeobj.size // 8, typeobj.signed)
return None |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.