repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
python-xlib/python-xlib | Xlib/display.py | Display.set_access_control | def set_access_control(self, mode, onerror = None):
"""Enable use of access control lists at connection setup if mode
is X.EnableAccess, disable if it is X.DisableAccess."""
request.SetAccessControl(display = self.display,
onerror = onerror,
mode = mode) | python | def set_access_control(self, mode, onerror = None):
"""Enable use of access control lists at connection setup if mode
is X.EnableAccess, disable if it is X.DisableAccess."""
request.SetAccessControl(display = self.display,
onerror = onerror,
mode = mode) | [
"def",
"set_access_control",
"(",
"self",
",",
"mode",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"SetAccessControl",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"mode",
"=",
"mode",
")"
] | Enable use of access control lists at connection setup if mode
is X.EnableAccess, disable if it is X.DisableAccess. | [
"Enable",
"use",
"of",
"access",
"control",
"lists",
"at",
"connection",
"setup",
"if",
"mode",
"is",
"X",
".",
"EnableAccess",
"disable",
"if",
"it",
"is",
"X",
".",
"DisableAccess",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L878-L883 | train | 198,400 |
python-xlib/python-xlib | Xlib/display.py | Display.set_close_down_mode | def set_close_down_mode(self, mode, onerror = None):
"""Control what will happen with the client's resources at
connection close. The default is X.DestroyAll, the other values
are X.RetainPermanent and X.RetainTemporary."""
request.SetCloseDownMode(display = self.display,
onerror = onerror,
mode = mode) | python | def set_close_down_mode(self, mode, onerror = None):
"""Control what will happen with the client's resources at
connection close. The default is X.DestroyAll, the other values
are X.RetainPermanent and X.RetainTemporary."""
request.SetCloseDownMode(display = self.display,
onerror = onerror,
mode = mode) | [
"def",
"set_close_down_mode",
"(",
"self",
",",
"mode",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"SetCloseDownMode",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"mode",
"=",
"mode",
")"
] | Control what will happen with the client's resources at
connection close. The default is X.DestroyAll, the other values
are X.RetainPermanent and X.RetainTemporary. | [
"Control",
"what",
"will",
"happen",
"with",
"the",
"client",
"s",
"resources",
"at",
"connection",
"close",
".",
"The",
"default",
"is",
"X",
".",
"DestroyAll",
"the",
"other",
"values",
"are",
"X",
".",
"RetainPermanent",
"and",
"X",
".",
"RetainTemporary"... | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L885-L891 | train | 198,401 |
python-xlib/python-xlib | Xlib/display.py | Display.force_screen_saver | def force_screen_saver(self, mode, onerror = None):
"""If mode is X.ScreenSaverActive the screen saver is activated.
If it is X.ScreenSaverReset, the screen saver is deactivated as
if device input had been received."""
request.ForceScreenSaver(display = self.display,
onerror = onerror,
mode = mode) | python | def force_screen_saver(self, mode, onerror = None):
"""If mode is X.ScreenSaverActive the screen saver is activated.
If it is X.ScreenSaverReset, the screen saver is deactivated as
if device input had been received."""
request.ForceScreenSaver(display = self.display,
onerror = onerror,
mode = mode) | [
"def",
"force_screen_saver",
"(",
"self",
",",
"mode",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"ForceScreenSaver",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"mode",
"=",
"mode",
")"
] | If mode is X.ScreenSaverActive the screen saver is activated.
If it is X.ScreenSaverReset, the screen saver is deactivated as
if device input had been received. | [
"If",
"mode",
"is",
"X",
".",
"ScreenSaverActive",
"the",
"screen",
"saver",
"is",
"activated",
".",
"If",
"it",
"is",
"X",
".",
"ScreenSaverReset",
"the",
"screen",
"saver",
"is",
"deactivated",
"as",
"if",
"device",
"input",
"had",
"been",
"received",
".... | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L893-L899 | train | 198,402 |
python-xlib/python-xlib | Xlib/display.py | Display.get_pointer_mapping | def get_pointer_mapping(self):
"""Return a list of the pointer button mappings. Entry N in the
list sets the logical button number for the physical button N+1."""
r = request.GetPointerMapping(display = self.display)
return r.map | python | def get_pointer_mapping(self):
"""Return a list of the pointer button mappings. Entry N in the
list sets the logical button number for the physical button N+1."""
r = request.GetPointerMapping(display = self.display)
return r.map | [
"def",
"get_pointer_mapping",
"(",
"self",
")",
":",
"r",
"=",
"request",
".",
"GetPointerMapping",
"(",
"display",
"=",
"self",
".",
"display",
")",
"return",
"r",
".",
"map"
] | Return a list of the pointer button mappings. Entry N in the
list sets the logical button number for the physical button N+1. | [
"Return",
"a",
"list",
"of",
"the",
"pointer",
"button",
"mappings",
".",
"Entry",
"N",
"in",
"the",
"list",
"sets",
"the",
"logical",
"button",
"number",
"for",
"the",
"physical",
"button",
"N",
"+",
"1",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L919-L923 | train | 198,403 |
python-xlib/python-xlib | Xlib/display.py | Display.set_modifier_mapping | def set_modifier_mapping(self, keycodes):
"""Set the keycodes for the eight modifiers X.Shift, X.Lock,
X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes
should be a eight-element list where each entry is a list of the
keycodes that should be bound to that modifier.
If any changed
key is logically in the down state, X.MappingBusy is returned and
the mapping is not changed. If the mapping violates some server
restriction, X.MappingFailed is returned. Otherwise the mapping
is changed and X.MappingSuccess is returned."""
r = request.SetModifierMapping(display = self.display,
keycodes = keycodes)
return r.status | python | def set_modifier_mapping(self, keycodes):
"""Set the keycodes for the eight modifiers X.Shift, X.Lock,
X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes
should be a eight-element list where each entry is a list of the
keycodes that should be bound to that modifier.
If any changed
key is logically in the down state, X.MappingBusy is returned and
the mapping is not changed. If the mapping violates some server
restriction, X.MappingFailed is returned. Otherwise the mapping
is changed and X.MappingSuccess is returned."""
r = request.SetModifierMapping(display = self.display,
keycodes = keycodes)
return r.status | [
"def",
"set_modifier_mapping",
"(",
"self",
",",
"keycodes",
")",
":",
"r",
"=",
"request",
".",
"SetModifierMapping",
"(",
"display",
"=",
"self",
".",
"display",
",",
"keycodes",
"=",
"keycodes",
")",
"return",
"r",
".",
"status"
] | Set the keycodes for the eight modifiers X.Shift, X.Lock,
X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes
should be a eight-element list where each entry is a list of the
keycodes that should be bound to that modifier.
If any changed
key is logically in the down state, X.MappingBusy is returned and
the mapping is not changed. If the mapping violates some server
restriction, X.MappingFailed is returned. Otherwise the mapping
is changed and X.MappingSuccess is returned. | [
"Set",
"the",
"keycodes",
"for",
"the",
"eight",
"modifiers",
"X",
".",
"Shift",
"X",
".",
"Lock",
"X",
".",
"Control",
"X",
".",
"Mod1",
"X",
".",
"Mod2",
"X",
".",
"Mod3",
"X",
".",
"Mod4",
"and",
"X",
".",
"Mod5",
".",
"keycodes",
"should",
"b... | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L925-L938 | train | 198,404 |
python-xlib/python-xlib | Xlib/display.py | Display.get_modifier_mapping | def get_modifier_mapping(self):
"""Return a list of eight lists, one for each modifier. The list
can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on.
The sublists list the keycodes bound to that modifier."""
r = request.GetModifierMapping(display = self.display)
return r.keycodes | python | def get_modifier_mapping(self):
"""Return a list of eight lists, one for each modifier. The list
can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on.
The sublists list the keycodes bound to that modifier."""
r = request.GetModifierMapping(display = self.display)
return r.keycodes | [
"def",
"get_modifier_mapping",
"(",
"self",
")",
":",
"r",
"=",
"request",
".",
"GetModifierMapping",
"(",
"display",
"=",
"self",
".",
"display",
")",
"return",
"r",
".",
"keycodes"
] | Return a list of eight lists, one for each modifier. The list
can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on.
The sublists list the keycodes bound to that modifier. | [
"Return",
"a",
"list",
"of",
"eight",
"lists",
"one",
"for",
"each",
"modifier",
".",
"The",
"list",
"can",
"be",
"indexed",
"using",
"X",
".",
"ShiftMapIndex",
"X",
".",
"Mod1MapIndex",
"and",
"so",
"on",
".",
"The",
"sublists",
"list",
"the",
"keycodes... | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L940-L945 | train | 198,405 |
python-xlib/python-xlib | Xlib/display.py | Display.no_operation | def no_operation(self, onerror = None):
"""Do nothing but send a request to the server."""
request.NoOperation(display = self.display,
onerror = onerror) | python | def no_operation(self, onerror = None):
"""Do nothing but send a request to the server."""
request.NoOperation(display = self.display,
onerror = onerror) | [
"def",
"no_operation",
"(",
"self",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"NoOperation",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
")"
] | Do nothing but send a request to the server. | [
"Do",
"nothing",
"but",
"send",
"a",
"request",
"to",
"the",
"server",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L947-L950 | train | 198,406 |
python-xlib/python-xlib | Xlib/protocol/display.py | Display.parse_connection_setup | def parse_connection_setup(self):
"""Internal function used to parse connection setup response.
"""
# Only the ConnectionSetupRequest has been sent so far
r = self.sent_requests[0]
while 1:
# print 'data_send:', repr(self.data_send)
# print 'data_recv:', repr(self.data_recv)
if r._data:
alen = r._data['additional_length'] * 4
# The full response haven't arrived yet
if len(self.data_recv) < alen:
return 0
# Connection failed or further authentication is needed.
# Set reason to the reason string
if r._data['status'] != 1:
r._data['reason'] = self.data_recv[:r._data['reason_length']]
# Else connection succeeded, parse the reply
else:
x, d = r._success_reply.parse_binary(self.data_recv[:alen],
self, rawdict = 1)
r._data.update(x)
del self.sent_requests[0]
self.data_recv = self.data_recv[alen:]
return 1
else:
# The base reply is 8 bytes long
if len(self.data_recv) < 8:
return 0
r._data, d = r._reply.parse_binary(self.data_recv[:8],
self, rawdict = 1)
self.data_recv = self.data_recv[8:] | python | def parse_connection_setup(self):
"""Internal function used to parse connection setup response.
"""
# Only the ConnectionSetupRequest has been sent so far
r = self.sent_requests[0]
while 1:
# print 'data_send:', repr(self.data_send)
# print 'data_recv:', repr(self.data_recv)
if r._data:
alen = r._data['additional_length'] * 4
# The full response haven't arrived yet
if len(self.data_recv) < alen:
return 0
# Connection failed or further authentication is needed.
# Set reason to the reason string
if r._data['status'] != 1:
r._data['reason'] = self.data_recv[:r._data['reason_length']]
# Else connection succeeded, parse the reply
else:
x, d = r._success_reply.parse_binary(self.data_recv[:alen],
self, rawdict = 1)
r._data.update(x)
del self.sent_requests[0]
self.data_recv = self.data_recv[alen:]
return 1
else:
# The base reply is 8 bytes long
if len(self.data_recv) < 8:
return 0
r._data, d = r._reply.parse_binary(self.data_recv[:8],
self, rawdict = 1)
self.data_recv = self.data_recv[8:] | [
"def",
"parse_connection_setup",
"(",
"self",
")",
":",
"# Only the ConnectionSetupRequest has been sent so far",
"r",
"=",
"self",
".",
"sent_requests",
"[",
"0",
"]",
"while",
"1",
":",
"# print 'data_send:', repr(self.data_send)",
"# print 'data_recv:', repr(self.data_recv)"... | Internal function used to parse connection setup response. | [
"Internal",
"function",
"used",
"to",
"parse",
"connection",
"setup",
"response",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/protocol/display.py#L933-L975 | train | 198,407 |
python-xlib/python-xlib | Xlib/ext/composite.py | redirect_subwindows | def redirect_subwindows(self, update, onerror = None):
"""Redirect the hierarchies starting at all current and future
children to this window to off-screen storage.
"""
RedirectSubwindows(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | python | def redirect_subwindows(self, update, onerror = None):
"""Redirect the hierarchies starting at all current and future
children to this window to off-screen storage.
"""
RedirectSubwindows(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | [
"def",
"redirect_subwindows",
"(",
"self",
",",
"update",
",",
"onerror",
"=",
"None",
")",
":",
"RedirectSubwindows",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extens... | Redirect the hierarchies starting at all current and future
children to this window to off-screen storage. | [
"Redirect",
"the",
"hierarchies",
"starting",
"at",
"all",
"current",
"and",
"future",
"children",
"to",
"this",
"window",
"to",
"off",
"-",
"screen",
"storage",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L105-L114 | train | 198,408 |
python-xlib/python-xlib | Xlib/ext/composite.py | unredirect_window | def unredirect_window(self, update, onerror = None):
"""Stop redirecting this window hierarchy.
"""
UnredirectWindow(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | python | def unredirect_window(self, update, onerror = None):
"""Stop redirecting this window hierarchy.
"""
UnredirectWindow(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | [
"def",
"unredirect_window",
"(",
"self",
",",
"update",
",",
"onerror",
"=",
"None",
")",
":",
"UnredirectWindow",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_... | Stop redirecting this window hierarchy. | [
"Stop",
"redirecting",
"this",
"window",
"hierarchy",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L127-L135 | train | 198,409 |
python-xlib/python-xlib | Xlib/ext/composite.py | unredirect_subwindows | def unredirect_subwindows(self, update, onerror = None):
"""Stop redirecting the hierarchies of children to this window.
"""
RedirectWindow(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | python | def unredirect_subwindows(self, update, onerror = None):
"""Stop redirecting the hierarchies of children to this window.
"""
RedirectWindow(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
update = update,
) | [
"def",
"unredirect_subwindows",
"(",
"self",
",",
"update",
",",
"onerror",
"=",
"None",
")",
":",
"RedirectWindow",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extensio... | Stop redirecting the hierarchies of children to this window. | [
"Stop",
"redirecting",
"the",
"hierarchies",
"of",
"children",
"to",
"this",
"window",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L148-L156 | train | 198,410 |
python-xlib/python-xlib | Xlib/ext/composite.py | create_region_from_border_clip | def create_region_from_border_clip(self, onerror = None):
"""Create a region of the border clip of the window, i.e. the area
that is not clipped by the parent and any sibling windows.
"""
rid = self.display.allocate_resource_id()
CreateRegionFromBorderClip(
display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
region = rid,
window = self,
)
# FIXME: create Region object and return it
return rid | python | def create_region_from_border_clip(self, onerror = None):
"""Create a region of the border clip of the window, i.e. the area
that is not clipped by the parent and any sibling windows.
"""
rid = self.display.allocate_resource_id()
CreateRegionFromBorderClip(
display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
region = rid,
window = self,
)
# FIXME: create Region object and return it
return rid | [
"def",
"create_region_from_border_clip",
"(",
"self",
",",
"onerror",
"=",
"None",
")",
":",
"rid",
"=",
"self",
".",
"display",
".",
"allocate_resource_id",
"(",
")",
"CreateRegionFromBorderClip",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"... | Create a region of the border clip of the window, i.e. the area
that is not clipped by the parent and any sibling windows. | [
"Create",
"a",
"region",
"of",
"the",
"border",
"clip",
"of",
"the",
"window",
"i",
".",
"e",
".",
"the",
"area",
"that",
"is",
"not",
"clipped",
"by",
"the",
"parent",
"and",
"any",
"sibling",
"windows",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L168-L183 | train | 198,411 |
python-xlib/python-xlib | Xlib/ext/composite.py | name_window_pixmap | def name_window_pixmap(self, onerror = None):
"""Create a new pixmap that refers to the off-screen storage of
the window, including its border.
This pixmap will remain allocated until freed whatever happens
with the window. However, the window will get a new off-screen
pixmap every time it is mapped or resized, so to keep track of the
contents you must listen for these events and get a new pixmap
after them.
"""
pid = self.display.allocate_resource_id()
NameWindowPixmap(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
pixmap = pid,
)
cls = self.display.get_resource_class('pixmap', drawable.Pixmap)
return cls(self.display, pid, owner = 1) | python | def name_window_pixmap(self, onerror = None):
"""Create a new pixmap that refers to the off-screen storage of
the window, including its border.
This pixmap will remain allocated until freed whatever happens
with the window. However, the window will get a new off-screen
pixmap every time it is mapped or resized, so to keep track of the
contents you must listen for these events and get a new pixmap
after them.
"""
pid = self.display.allocate_resource_id()
NameWindowPixmap(display = self.display,
onerror = onerror,
opcode = self.display.get_extension_major(extname),
window = self,
pixmap = pid,
)
cls = self.display.get_resource_class('pixmap', drawable.Pixmap)
return cls(self.display, pid, owner = 1) | [
"def",
"name_window_pixmap",
"(",
"self",
",",
"onerror",
"=",
"None",
")",
":",
"pid",
"=",
"self",
".",
"display",
".",
"allocate_resource_id",
"(",
")",
"NameWindowPixmap",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
","... | Create a new pixmap that refers to the off-screen storage of
the window, including its border.
This pixmap will remain allocated until freed whatever happens
with the window. However, the window will get a new off-screen
pixmap every time it is mapped or resized, so to keep track of the
contents you must listen for these events and get a new pixmap
after them. | [
"Create",
"a",
"new",
"pixmap",
"that",
"refers",
"to",
"the",
"off",
"-",
"screen",
"storage",
"of",
"the",
"window",
"including",
"its",
"border",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L195-L215 | train | 198,412 |
python-xlib/python-xlib | Xlib/ext/composite.py | get_overlay_window | def get_overlay_window(self):
"""Return the overlay window of the root window.
"""
return GetOverlayWindow(display = self.display,
opcode = self.display.get_extension_major(extname),
window = self) | python | def get_overlay_window(self):
"""Return the overlay window of the root window.
"""
return GetOverlayWindow(display = self.display,
opcode = self.display.get_extension_major(extname),
window = self) | [
"def",
"get_overlay_window",
"(",
"self",
")",
":",
"return",
"GetOverlayWindow",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_major",
"(",
"extname",
")",
",",
"window",
"=",
"self",
")"
] | Return the overlay window of the root window. | [
"Return",
"the",
"overlay",
"window",
"of",
"the",
"root",
"window",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/composite.py#L233-L239 | train | 198,413 |
python-xlib/python-xlib | Xlib/protocol/rq.py | String16.pack_value | def pack_value(self, val):
"""Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self.pad:
pad = b'\0\0' * (slen % 2)
else:
pad = b''
return struct.pack('>' + 'H' * slen, *val) + pad, slen, None | python | def pack_value(self, val):
"""Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self.pad:
pad = b'\0\0' * (slen % 2)
else:
pad = b''
return struct.pack('>' + 'H' * slen, *val) + pad, slen, None | [
"def",
"pack_value",
"(",
"self",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"val",
"=",
"list",
"(",
"iterbytes",
"(",
"val",
")",
")",
"slen",
"=",
"len",
"(",
"val",
")",
"if",
"self",
".",
"pad",
":",
"pad... | Convert 8-byte string into 16-byte list | [
"Convert",
"8",
"-",
"byte",
"string",
"into",
"16",
"-",
"byte",
"list"
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/protocol/rq.py#L457-L469 | train | 198,414 |
python-xlib/python-xlib | Xlib/protocol/rq.py | Struct.pack_value | def pack_value(self, value):
""" This function allows Struct objects to be used in List and
Object fields. Each item represents the arguments to pass to
to_binary, either a tuple, a dictionary or a DictWrapper.
"""
if type(value) is tuple:
return self.to_binary(*value)
elif isinstance(value, dict):
return self.to_binary(**value)
elif isinstance(value, DictWrapper):
return self.to_binary(**value._data)
else:
raise BadDataError('%s is not a tuple or a list' % (value)) | python | def pack_value(self, value):
""" This function allows Struct objects to be used in List and
Object fields. Each item represents the arguments to pass to
to_binary, either a tuple, a dictionary or a DictWrapper.
"""
if type(value) is tuple:
return self.to_binary(*value)
elif isinstance(value, dict):
return self.to_binary(**value)
elif isinstance(value, DictWrapper):
return self.to_binary(**value._data)
else:
raise BadDataError('%s is not a tuple or a list' % (value)) | [
"def",
"pack_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"tuple",
":",
"return",
"self",
".",
"to_binary",
"(",
"*",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"self",
... | This function allows Struct objects to be used in List and
Object fields. Each item represents the arguments to pass to
to_binary, either a tuple, a dictionary or a DictWrapper. | [
"This",
"function",
"allows",
"Struct",
"objects",
"to",
"be",
"used",
"in",
"List",
"and",
"Object",
"fields",
".",
"Each",
"item",
"represents",
"the",
"arguments",
"to",
"pass",
"to",
"to_binary",
"either",
"a",
"tuple",
"a",
"dictionary",
"or",
"a",
"D... | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/protocol/rq.py#L1074-L1089 | train | 198,415 |
python-xlib/python-xlib | Xlib/protocol/rq.py | Struct.parse_value | def parse_value(self, val, display, rawdict = 0):
"""This function is used by List and Object fields to convert
Struct objects with no var_fields into Python values.
"""
ret = {}
vno = 0
for f in self.static_fields:
# Fields without names should be ignored, and there should
# not be any length or format fields if this function
# ever gets called. (If there were such fields, there should
# be a matching field in var_fields and then parse_binary
# would have been called instead.
if not f.name:
pass
elif isinstance(f, LengthField):
pass
elif isinstance(f, FormatField):
pass
# Value fields
else:
# If this field has a parse_value method, call it, otherwise
# use the unpacked value as is.
if f.structvalues == 1:
field_val = val[vno]
else:
field_val = val[vno:vno+f.structvalues]
if f.parse_value is not None:
field_val = f.parse_value(field_val, display, rawdict=rawdict)
ret[f.name] = field_val
vno = vno + f.structvalues
if not rawdict:
return DictWrapper(ret)
return ret | python | def parse_value(self, val, display, rawdict = 0):
"""This function is used by List and Object fields to convert
Struct objects with no var_fields into Python values.
"""
ret = {}
vno = 0
for f in self.static_fields:
# Fields without names should be ignored, and there should
# not be any length or format fields if this function
# ever gets called. (If there were such fields, there should
# be a matching field in var_fields and then parse_binary
# would have been called instead.
if not f.name:
pass
elif isinstance(f, LengthField):
pass
elif isinstance(f, FormatField):
pass
# Value fields
else:
# If this field has a parse_value method, call it, otherwise
# use the unpacked value as is.
if f.structvalues == 1:
field_val = val[vno]
else:
field_val = val[vno:vno+f.structvalues]
if f.parse_value is not None:
field_val = f.parse_value(field_val, display, rawdict=rawdict)
ret[f.name] = field_val
vno = vno + f.structvalues
if not rawdict:
return DictWrapper(ret)
return ret | [
"def",
"parse_value",
"(",
"self",
",",
"val",
",",
"display",
",",
"rawdict",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"}",
"vno",
"=",
"0",
"for",
"f",
"in",
"self",
".",
"static_fields",
":",
"# Fields without names should be ignored, and there should",
"# no... | This function is used by List and Object fields to convert
Struct objects with no var_fields into Python values. | [
"This",
"function",
"is",
"used",
"by",
"List",
"and",
"Object",
"fields",
"to",
"convert",
"Struct",
"objects",
"with",
"no",
"var_fields",
"into",
"Python",
"values",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/protocol/rq.py#L1092-L1133 | train | 198,416 |
python-xlib/python-xlib | Xlib/xauth.py | Xauthority.get_best_auth | def get_best_auth(self, family, address, dispno,
types = ( b"MIT-MAGIC-COOKIE-1", )):
"""Find an authentication entry matching FAMILY, ADDRESS and
DISPNO.
The name of the auth scheme must match one of the names in
TYPES. If several entries match, the first scheme in TYPES
will be choosen.
If an entry is found, the tuple (name, data) is returned,
otherwise XNoAuthError is raised.
"""
num = str(dispno).encode()
matches = {}
for efam, eaddr, enum, ename, edata in self.entries:
if efam == family and eaddr == address and num == enum:
matches[ename] = edata
for t in types:
try:
return (t, matches[t])
except KeyError:
pass
raise error.XNoAuthError((family, address, dispno)) | python | def get_best_auth(self, family, address, dispno,
types = ( b"MIT-MAGIC-COOKIE-1", )):
"""Find an authentication entry matching FAMILY, ADDRESS and
DISPNO.
The name of the auth scheme must match one of the names in
TYPES. If several entries match, the first scheme in TYPES
will be choosen.
If an entry is found, the tuple (name, data) is returned,
otherwise XNoAuthError is raised.
"""
num = str(dispno).encode()
matches = {}
for efam, eaddr, enum, ename, edata in self.entries:
if efam == family and eaddr == address and num == enum:
matches[ename] = edata
for t in types:
try:
return (t, matches[t])
except KeyError:
pass
raise error.XNoAuthError((family, address, dispno)) | [
"def",
"get_best_auth",
"(",
"self",
",",
"family",
",",
"address",
",",
"dispno",
",",
"types",
"=",
"(",
"b\"MIT-MAGIC-COOKIE-1\"",
",",
")",
")",
":",
"num",
"=",
"str",
"(",
"dispno",
")",
".",
"encode",
"(",
")",
"matches",
"=",
"{",
"}",
"for",... | Find an authentication entry matching FAMILY, ADDRESS and
DISPNO.
The name of the auth scheme must match one of the names in
TYPES. If several entries match, the first scheme in TYPES
will be choosen.
If an entry is found, the tuple (name, data) is returned,
otherwise XNoAuthError is raised. | [
"Find",
"an",
"authentication",
"entry",
"matching",
"FAMILY",
"ADDRESS",
"and",
"DISPNO",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/xauth.py#L102-L130 | train | 198,417 |
python-xlib/python-xlib | examples/run_examples.py | run_example | def run_example(path):
""" Returns returncode of example """
cmd = "{0} {1}".format(sys.executable, path)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
res = proc.communicate()
if proc.returncode:
print(res[1].decode())
return proc.returncode | python | def run_example(path):
""" Returns returncode of example """
cmd = "{0} {1}".format(sys.executable, path)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
res = proc.communicate()
if proc.returncode:
print(res[1].decode())
return proc.returncode | [
"def",
"run_example",
"(",
"path",
")",
":",
"cmd",
"=",
"\"{0} {1}\"",
".",
"format",
"(",
"sys",
".",
"executable",
",",
"path",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
... | Returns returncode of example | [
"Returns",
"returncode",
"of",
"example"
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/examples/run_examples.py#L34-L41 | train | 198,418 |
python-xlib/python-xlib | Xlib/XK.py | load_keysym_group | def load_keysym_group(group):
'''Load all the keysyms in group.
Given a group name such as 'latin1' or 'katakana' load the keysyms
defined in module 'Xlib.keysymdef.group-name' into this XK module.'''
if '.' in group:
raise ValueError('invalid keysym group name: %s' % group)
G = globals() #Get a reference to XK.__dict__ a.k.a. globals
#Import just the keysyms module.
mod = __import__('Xlib.keysymdef.%s' % group, G, locals(), [group])
#Extract names of just the keysyms.
keysyms = [n for n in dir(mod) if n.startswith('XK_')]
#Copy the named keysyms into XK.__dict__
for keysym in keysyms:
## k = mod.__dict__[keysym]; assert k == int(k) #probably too much.
G[keysym] = mod.__dict__[keysym]
#And get rid of the keysym module.
del mod | python | def load_keysym_group(group):
'''Load all the keysyms in group.
Given a group name such as 'latin1' or 'katakana' load the keysyms
defined in module 'Xlib.keysymdef.group-name' into this XK module.'''
if '.' in group:
raise ValueError('invalid keysym group name: %s' % group)
G = globals() #Get a reference to XK.__dict__ a.k.a. globals
#Import just the keysyms module.
mod = __import__('Xlib.keysymdef.%s' % group, G, locals(), [group])
#Extract names of just the keysyms.
keysyms = [n for n in dir(mod) if n.startswith('XK_')]
#Copy the named keysyms into XK.__dict__
for keysym in keysyms:
## k = mod.__dict__[keysym]; assert k == int(k) #probably too much.
G[keysym] = mod.__dict__[keysym]
#And get rid of the keysym module.
del mod | [
"def",
"load_keysym_group",
"(",
"group",
")",
":",
"if",
"'.'",
"in",
"group",
":",
"raise",
"ValueError",
"(",
"'invalid keysym group name: %s'",
"%",
"group",
")",
"G",
"=",
"globals",
"(",
")",
"#Get a reference to XK.__dict__ a.k.a. globals",
"#Import just the ke... | Load all the keysyms in group.
Given a group name such as 'latin1' or 'katakana' load the keysyms
defined in module 'Xlib.keysymdef.group-name' into this XK module. | [
"Load",
"all",
"the",
"keysyms",
"in",
"group",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/XK.py#L36-L58 | train | 198,419 |
python-xlib/python-xlib | Xlib/ext/randr.py | _1_0set_screen_config | def _1_0set_screen_config(self, size_id, rotation, config_timestamp, timestamp=X.CurrentTime):
"""Sets the screen to the specified size and rotation.
"""
return _1_0SetScreenConfig(
display=self.display,
opcode=self.display.get_extension_major(extname),
drawable=self,
timestamp=timestamp,
config_timestamp=config_timestamp,
size_id=size_id,
rotation=rotation,
) | python | def _1_0set_screen_config(self, size_id, rotation, config_timestamp, timestamp=X.CurrentTime):
"""Sets the screen to the specified size and rotation.
"""
return _1_0SetScreenConfig(
display=self.display,
opcode=self.display.get_extension_major(extname),
drawable=self,
timestamp=timestamp,
config_timestamp=config_timestamp,
size_id=size_id,
rotation=rotation,
) | [
"def",
"_1_0set_screen_config",
"(",
"self",
",",
"size_id",
",",
"rotation",
",",
"config_timestamp",
",",
"timestamp",
"=",
"X",
".",
"CurrentTime",
")",
":",
"return",
"_1_0SetScreenConfig",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
... | Sets the screen to the specified size and rotation. | [
"Sets",
"the",
"screen",
"to",
"the",
"specified",
"size",
"and",
"rotation",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/randr.py#L227-L239 | train | 198,420 |
python-xlib/python-xlib | Xlib/ext/randr.py | set_screen_config | def set_screen_config(self, size_id, rotation, config_timestamp, rate=0, timestamp=X.CurrentTime):
"""Sets the screen to the specified size, rate, rotation and reflection.
rate can be 0 to have the server select an appropriate rate.
"""
return SetScreenConfig(
display=self.display,
opcode=self.display.get_extension_major(extname),
drawable=self,
timestamp=timestamp,
config_timestamp=config_timestamp,
size_id=size_id,
rotation=rotation,
rate=rate,
) | python | def set_screen_config(self, size_id, rotation, config_timestamp, rate=0, timestamp=X.CurrentTime):
"""Sets the screen to the specified size, rate, rotation and reflection.
rate can be 0 to have the server select an appropriate rate.
"""
return SetScreenConfig(
display=self.display,
opcode=self.display.get_extension_major(extname),
drawable=self,
timestamp=timestamp,
config_timestamp=config_timestamp,
size_id=size_id,
rotation=rotation,
rate=rate,
) | [
"def",
"set_screen_config",
"(",
"self",
",",
"size_id",
",",
"rotation",
",",
"config_timestamp",
",",
"rate",
"=",
"0",
",",
"timestamp",
"=",
"X",
".",
"CurrentTime",
")",
":",
"return",
"SetScreenConfig",
"(",
"display",
"=",
"self",
".",
"display",
",... | Sets the screen to the specified size, rate, rotation and reflection.
rate can be 0 to have the server select an appropriate rate. | [
"Sets",
"the",
"screen",
"to",
"the",
"specified",
"size",
"rate",
"rotation",
"and",
"reflection",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/randr.py#L267-L282 | train | 198,421 |
python-xlib/python-xlib | Xlib/ext/randr.py | get_screen_info | def get_screen_info(self):
"""Retrieve information about the current and available configurations for
the screen associated with this window.
"""
return GetScreenInfo(
display=self.display,
opcode=self.display.get_extension_major(extname),
window=self,
) | python | def get_screen_info(self):
"""Retrieve information about the current and available configurations for
the screen associated with this window.
"""
return GetScreenInfo(
display=self.display,
opcode=self.display.get_extension_major(extname),
window=self,
) | [
"def",
"get_screen_info",
"(",
"self",
")",
":",
"return",
"GetScreenInfo",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_major",
"(",
"extname",
")",
",",
"window",
"=",
"self",
",",
")"
] | Retrieve information about the current and available configurations for
the screen associated with this window. | [
"Retrieve",
"information",
"about",
"the",
"current",
"and",
"available",
"configurations",
"for",
"the",
"screen",
"associated",
"with",
"this",
"window",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/randr.py#L329-L338 | train | 198,422 |
python-xlib/python-xlib | Xlib/ext/randr.py | get_screen_size_range | def get_screen_size_range(self):
"""Retrieve the range of possible screen sizes. The screen may be set to
any size within this range.
"""
return GetScreenSizeRange(
display=self.display,
opcode=self.display.get_extension_major(extname),
window=self,
) | python | def get_screen_size_range(self):
"""Retrieve the range of possible screen sizes. The screen may be set to
any size within this range.
"""
return GetScreenSizeRange(
display=self.display,
opcode=self.display.get_extension_major(extname),
window=self,
) | [
"def",
"get_screen_size_range",
"(",
"self",
")",
":",
"return",
"GetScreenSizeRange",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_major",
"(",
"extname",
")",
",",
"window",
"=",
"self",
",",
... | Retrieve the range of possible screen sizes. The screen may be set to
any size within this range. | [
"Retrieve",
"the",
"range",
"of",
"possible",
"screen",
"sizes",
".",
"The",
"screen",
"may",
"be",
"set",
"to",
"any",
"size",
"within",
"this",
"range",
"."
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/randr.py#L362-L371 | train | 198,423 |
python-xlib/python-xlib | Xlib/ext/xinerama.py | get_screen_size | def get_screen_size(self, screen_no):
"""Returns the size of the given screen number"""
return GetScreenSize(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self.id,
screen=screen_no,
) | python | def get_screen_size(self, screen_no):
"""Returns the size of the given screen number"""
return GetScreenSize(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self.id,
screen=screen_no,
) | [
"def",
"get_screen_size",
"(",
"self",
",",
"screen_no",
")",
":",
"return",
"GetScreenSize",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_major",
"(",
"extname",
")",
",",
"window",
"=",
"sel... | Returns the size of the given screen number | [
"Returns",
"the",
"size",
"of",
"the",
"given",
"screen",
"number"
] | 8901e831737e79fe5645f48089d70e1d1046d2f2 | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/xinerama.py#L137-L143 | train | 198,424 |
noripyt/django-cachalot | cachalot/utils.py | get_query_cache_key | def get_query_cache_key(compiler):
"""
Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg compiler: A SQLCompiler that will generate the SQL query
:type compiler: django.db.models.sql.compiler.SQLCompiler
:return: A cache key
:rtype: int
"""
sql, params = compiler.as_sql()
check_parameter_types(params)
cache_key = '%s:%s:%s' % (compiler.using, sql,
[text_type(p) for p in params])
return sha1(cache_key.encode('utf-8')).hexdigest() | python | def get_query_cache_key(compiler):
"""
Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg compiler: A SQLCompiler that will generate the SQL query
:type compiler: django.db.models.sql.compiler.SQLCompiler
:return: A cache key
:rtype: int
"""
sql, params = compiler.as_sql()
check_parameter_types(params)
cache_key = '%s:%s:%s' % (compiler.using, sql,
[text_type(p) for p in params])
return sha1(cache_key.encode('utf-8')).hexdigest() | [
"def",
"get_query_cache_key",
"(",
"compiler",
")",
":",
"sql",
",",
"params",
"=",
"compiler",
".",
"as_sql",
"(",
")",
"check_parameter_types",
"(",
"params",
")",
"cache_key",
"=",
"'%s:%s:%s'",
"%",
"(",
"compiler",
".",
"using",
",",
"sql",
",",
"[",
... | Generates a cache key from a SQLCompiler.
This cache key is specific to the SQL query and its context
(which database is used). The same query in the same context
(= the same database) must generate the same cache key.
:arg compiler: A SQLCompiler that will generate the SQL query
:type compiler: django.db.models.sql.compiler.SQLCompiler
:return: A cache key
:rtype: int | [
"Generates",
"a",
"cache",
"key",
"from",
"a",
"SQLCompiler",
"."
] | f3f8773f853d4814ec801b8b7f8a6470781857c8 | https://github.com/noripyt/django-cachalot/blob/f3f8773f853d4814ec801b8b7f8a6470781857c8/cachalot/utils.py#L63-L80 | train | 198,425 |
noripyt/django-cachalot | cachalot/utils.py | get_table_cache_key | def get_table_cache_key(db_alias, table):
"""
Generates a cache key from a SQL table.
:arg db_alias: Alias of the used database
:type db_alias: str or unicode
:arg table: Name of the SQL table
:type table: str or unicode
:return: A cache key
:rtype: int
"""
cache_key = '%s:%s' % (db_alias, table)
return sha1(cache_key.encode('utf-8')).hexdigest() | python | def get_table_cache_key(db_alias, table):
"""
Generates a cache key from a SQL table.
:arg db_alias: Alias of the used database
:type db_alias: str or unicode
:arg table: Name of the SQL table
:type table: str or unicode
:return: A cache key
:rtype: int
"""
cache_key = '%s:%s' % (db_alias, table)
return sha1(cache_key.encode('utf-8')).hexdigest() | [
"def",
"get_table_cache_key",
"(",
"db_alias",
",",
"table",
")",
":",
"cache_key",
"=",
"'%s:%s'",
"%",
"(",
"db_alias",
",",
"table",
")",
"return",
"sha1",
"(",
"cache_key",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")"
] | Generates a cache key from a SQL table.
:arg db_alias: Alias of the used database
:type db_alias: str or unicode
:arg table: Name of the SQL table
:type table: str or unicode
:return: A cache key
:rtype: int | [
"Generates",
"a",
"cache",
"key",
"from",
"a",
"SQL",
"table",
"."
] | f3f8773f853d4814ec801b8b7f8a6470781857c8 | https://github.com/noripyt/django-cachalot/blob/f3f8773f853d4814ec801b8b7f8a6470781857c8/cachalot/utils.py#L83-L95 | train | 198,426 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator.translate | def translate(self, instr):
"""Return the SMT representation of a REIL instruction.
"""
try:
translator = self._instr_translators[instr.mnemonic]
return translator(*instr.operands)
except Exception:
logger.error("Failed to translate instruction: %s", instr, exc_info=True)
raise | python | def translate(self, instr):
"""Return the SMT representation of a REIL instruction.
"""
try:
translator = self._instr_translators[instr.mnemonic]
return translator(*instr.operands)
except Exception:
logger.error("Failed to translate instruction: %s", instr, exc_info=True)
raise | [
"def",
"translate",
"(",
"self",
",",
"instr",
")",
":",
"try",
":",
"translator",
"=",
"self",
".",
"_instr_translators",
"[",
"instr",
".",
"mnemonic",
"]",
"return",
"translator",
"(",
"*",
"instr",
".",
"operands",
")",
"except",
"Exception",
":",
"l... | Return the SMT representation of a REIL instruction. | [
"Return",
"the",
"SMT",
"representation",
"of",
"a",
"REIL",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L126-L136 | train | 198,427 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator.get_name_init | def get_name_init(self, name):
"""Get initial name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_init() | python | def get_name_init(self, name):
"""Get initial name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_init() | [
"def",
"get_name_init",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_register_name",
"(",
"name",
")",
"return",
"self",
".",
"_var_name_mappers",
"[",
"name",
"]",
".",
"get_init",
"(",
")"
] | Get initial name of symbol. | [
"Get",
"initial",
"name",
"of",
"symbol",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L138-L143 | train | 198,428 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator.get_name_curr | def get_name_curr(self, name):
"""Get current name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_current() | python | def get_name_curr(self, name):
"""Get current name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_current() | [
"def",
"get_name_curr",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_register_name",
"(",
"name",
")",
"return",
"self",
".",
"_var_name_mappers",
"[",
"name",
"]",
".",
"get_current",
"(",
")"
] | Get current name of symbol. | [
"Get",
"current",
"name",
"of",
"symbol",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L145-L150 | train | 198,429 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator.reset | def reset(self):
"""Reset internal state.
"""
self._solver.reset()
# Memory versioning.
self._mem_instance = 0
self._mem_init = smtsymbol.BitVecArray(self._address_size, 8, "MEM_{}".format(self._mem_instance))
self._mem_curr = self.make_array(self._address_size, "MEM_{}".format(self._mem_instance))
self._var_name_mappers = {} | python | def reset(self):
"""Reset internal state.
"""
self._solver.reset()
# Memory versioning.
self._mem_instance = 0
self._mem_init = smtsymbol.BitVecArray(self._address_size, 8, "MEM_{}".format(self._mem_instance))
self._mem_curr = self.make_array(self._address_size, "MEM_{}".format(self._mem_instance))
self._var_name_mappers = {} | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_solver",
".",
"reset",
"(",
")",
"# Memory versioning.",
"self",
".",
"_mem_instance",
"=",
"0",
"self",
".",
"_mem_init",
"=",
"smtsymbol",
".",
"BitVecArray",
"(",
"self",
".",
"_address_size",
",",
... | Reset internal state. | [
"Reset",
"internal",
"state",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L162-L173 | train | 198,430 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._register_name | def _register_name(self, name):
"""Get register name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name) | python | def _register_name(self, name):
"""Get register name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name) | [
"def",
"_register_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_var_name_mappers",
":",
"self",
".",
"_var_name_mappers",
"[",
"name",
"]",
"=",
"VariableNamer",
"(",
"name",
")"
] | Get register name. | [
"Get",
"register",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L222-L226 | train | 198,431 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._get_var_name | def _get_var_name(self, name, fresh=False):
"""Get variable name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name)
if fresh:
var_name = self._var_name_mappers[name].get_next()
else:
var_name = self._var_name_mappers[name].get_current()
return var_name | python | def _get_var_name(self, name, fresh=False):
"""Get variable name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name)
if fresh:
var_name = self._var_name_mappers[name].get_next()
else:
var_name = self._var_name_mappers[name].get_current()
return var_name | [
"def",
"_get_var_name",
"(",
"self",
",",
"name",
",",
"fresh",
"=",
"False",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_var_name_mappers",
":",
"self",
".",
"_var_name_mappers",
"[",
"name",
"]",
"=",
"VariableNamer",
"(",
"name",
")",
"if",
... | Get variable name. | [
"Get",
"variable",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L228-L239 | train | 198,432 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_src_oprnd | def _translate_src_oprnd(self, operand):
"""Translate source operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(operand.size, operand.immediate)
else:
raise Exception("Invalid operand type") | python | def _translate_src_oprnd(self, operand):
"""Translate source operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(operand.size, operand.immediate)
else:
raise Exception("Invalid operand type") | [
"def",
"_translate_src_oprnd",
"(",
"self",
",",
"operand",
")",
":",
"if",
"isinstance",
"(",
"operand",
",",
"ReilRegisterOperand",
")",
":",
"return",
"self",
".",
"_translate_src_register_oprnd",
"(",
"operand",
")",
"elif",
"isinstance",
"(",
"operand",
","... | Translate source operand to a SMT expression. | [
"Translate",
"source",
"operand",
"to",
"a",
"SMT",
"expression",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L241-L249 | train | 198,433 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_dst_oprnd | def _translate_dst_oprnd(self, operand):
"""Translate destination operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_dst_register_oprnd(operand)
else:
raise Exception("Invalid operand type") | python | def _translate_dst_oprnd(self, operand):
"""Translate destination operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_dst_register_oprnd(operand)
else:
raise Exception("Invalid operand type") | [
"def",
"_translate_dst_oprnd",
"(",
"self",
",",
"operand",
")",
":",
"if",
"isinstance",
"(",
"operand",
",",
"ReilRegisterOperand",
")",
":",
"return",
"self",
".",
"_translate_dst_register_oprnd",
"(",
"operand",
")",
"else",
":",
"raise",
"Exception",
"(",
... | Translate destination operand to a SMT expression. | [
"Translate",
"destination",
"operand",
"to",
"a",
"SMT",
"expression",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L251-L257 | train | 198,434 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_src_register_oprnd | def _translate_src_register_oprnd(self, operand):
"""Translate source register operand to SMT expr.
"""
reg_info = self._arch_alias_mapper.get(operand.name, None)
if reg_info:
var_base_name, offset = reg_info
var_size = self._arch_regs_size[var_base_name]
else:
var_base_name = operand.name
var_size = operand.size
var_name = self._get_var_name(var_base_name)
ret_val = self.make_bitvec(var_size, var_name)
if reg_info:
ret_val = smtfunction.extract(ret_val, offset, operand.size)
return ret_val | python | def _translate_src_register_oprnd(self, operand):
"""Translate source register operand to SMT expr.
"""
reg_info = self._arch_alias_mapper.get(operand.name, None)
if reg_info:
var_base_name, offset = reg_info
var_size = self._arch_regs_size[var_base_name]
else:
var_base_name = operand.name
var_size = operand.size
var_name = self._get_var_name(var_base_name)
ret_val = self.make_bitvec(var_size, var_name)
if reg_info:
ret_val = smtfunction.extract(ret_val, offset, operand.size)
return ret_val | [
"def",
"_translate_src_register_oprnd",
"(",
"self",
",",
"operand",
")",
":",
"reg_info",
"=",
"self",
".",
"_arch_alias_mapper",
".",
"get",
"(",
"operand",
".",
"name",
",",
"None",
")",
"if",
"reg_info",
":",
"var_base_name",
",",
"offset",
"=",
"reg_inf... | Translate source register operand to SMT expr. | [
"Translate",
"source",
"register",
"operand",
"to",
"SMT",
"expr",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L259-L278 | train | 198,435 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_dst_register_oprnd | def _translate_dst_register_oprnd(self, operand):
"""Translate destination register operand to SMT expr.
"""
reg_info = self._arch_alias_mapper.get(operand.name, None)
parent_reg_constrs = []
if reg_info:
var_base_name, offset = reg_info
var_name_old = self._get_var_name(var_base_name, fresh=False)
var_name_new = self._get_var_name(var_base_name, fresh=True)
var_size = self._arch_regs_size[var_base_name]
ret_val_old = self.make_bitvec(var_size, var_name_old)
ret_val_new = self.make_bitvec(var_size, var_name_new)
ret_val = smtfunction.extract(ret_val_new, offset, operand.size)
if 0 < offset < var_size - 1:
lower_expr_1 = smtfunction.extract(ret_val_new, 0, offset)
lower_expr_2 = smtfunction.extract(ret_val_old, 0, offset)
parent_reg_constrs += [lower_expr_1 == lower_expr_2]
upper_expr_1 = smtfunction.extract(ret_val_new, offset + operand.size, var_size - offset - operand.size)
upper_expr_2 = smtfunction.extract(ret_val_old, offset + operand.size, var_size - offset - operand.size)
parent_reg_constrs += [upper_expr_1 == upper_expr_2]
elif offset == 0:
upper_expr_1 = smtfunction.extract(ret_val_new, offset + operand.size, var_size - offset - operand.size)
upper_expr_2 = smtfunction.extract(ret_val_old, offset + operand.size, var_size - offset - operand.size)
parent_reg_constrs += [upper_expr_1 == upper_expr_2]
elif offset == var_size-1:
lower_expr_1 = smtfunction.extract(ret_val_new, 0, offset)
lower_expr_2 = smtfunction.extract(ret_val_old, 0, offset)
parent_reg_constrs += [lower_expr_1 == lower_expr_2]
else:
var_name_new = self._get_var_name(operand.name, fresh=True)
ret_val = self.make_bitvec(operand.size, var_name_new)
return ret_val, parent_reg_constrs | python | def _translate_dst_register_oprnd(self, operand):
"""Translate destination register operand to SMT expr.
"""
reg_info = self._arch_alias_mapper.get(operand.name, None)
parent_reg_constrs = []
if reg_info:
var_base_name, offset = reg_info
var_name_old = self._get_var_name(var_base_name, fresh=False)
var_name_new = self._get_var_name(var_base_name, fresh=True)
var_size = self._arch_regs_size[var_base_name]
ret_val_old = self.make_bitvec(var_size, var_name_old)
ret_val_new = self.make_bitvec(var_size, var_name_new)
ret_val = smtfunction.extract(ret_val_new, offset, operand.size)
if 0 < offset < var_size - 1:
lower_expr_1 = smtfunction.extract(ret_val_new, 0, offset)
lower_expr_2 = smtfunction.extract(ret_val_old, 0, offset)
parent_reg_constrs += [lower_expr_1 == lower_expr_2]
upper_expr_1 = smtfunction.extract(ret_val_new, offset + operand.size, var_size - offset - operand.size)
upper_expr_2 = smtfunction.extract(ret_val_old, offset + operand.size, var_size - offset - operand.size)
parent_reg_constrs += [upper_expr_1 == upper_expr_2]
elif offset == 0:
upper_expr_1 = smtfunction.extract(ret_val_new, offset + operand.size, var_size - offset - operand.size)
upper_expr_2 = smtfunction.extract(ret_val_old, offset + operand.size, var_size - offset - operand.size)
parent_reg_constrs += [upper_expr_1 == upper_expr_2]
elif offset == var_size-1:
lower_expr_1 = smtfunction.extract(ret_val_new, 0, offset)
lower_expr_2 = smtfunction.extract(ret_val_old, 0, offset)
parent_reg_constrs += [lower_expr_1 == lower_expr_2]
else:
var_name_new = self._get_var_name(operand.name, fresh=True)
ret_val = self.make_bitvec(operand.size, var_name_new)
return ret_val, parent_reg_constrs | [
"def",
"_translate_dst_register_oprnd",
"(",
"self",
",",
"operand",
")",
":",
"reg_info",
"=",
"self",
".",
"_arch_alias_mapper",
".",
"get",
"(",
"operand",
".",
"name",
",",
"None",
")",
"parent_reg_constrs",
"=",
"[",
"]",
"if",
"reg_info",
":",
"var_bas... | Translate destination register operand to SMT expr. | [
"Translate",
"destination",
"register",
"operand",
"to",
"SMT",
"expr",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L280-L324 | train | 198,436 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_add | def _translate_add(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of an ADD instruction.
"""
assert oprnd1.size and oprnd2.size and oprnd3.size
assert oprnd1.size == oprnd2.size
op1_var = self._translate_src_oprnd(oprnd1)
op2_var = self._translate_src_oprnd(oprnd2)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.zero_extend(op1_var, oprnd3.size) + smtfunction.zero_extend(op2_var, oprnd3.size)
elif oprnd3.size < oprnd1.size:
result = smtfunction.extract(op1_var + op2_var, 0, oprnd3.size)
else:
result = op1_var + op2_var
return [op3_var == result] + op3_var_constrs | python | def _translate_add(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of an ADD instruction.
"""
assert oprnd1.size and oprnd2.size and oprnd3.size
assert oprnd1.size == oprnd2.size
op1_var = self._translate_src_oprnd(oprnd1)
op2_var = self._translate_src_oprnd(oprnd2)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.zero_extend(op1_var, oprnd3.size) + smtfunction.zero_extend(op2_var, oprnd3.size)
elif oprnd3.size < oprnd1.size:
result = smtfunction.extract(op1_var + op2_var, 0, oprnd3.size)
else:
result = op1_var + op2_var
return [op3_var == result] + op3_var_constrs | [
"def",
"_translate_add",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd2",
".",
"size",
"and",
"oprnd3",
".",
"size",
"assert",
"oprnd1",
".",
"size",
"==",
"oprnd2",
".",
"size",
"op1... | Return a formula representation of an ADD instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"an",
"ADD",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L328-L345 | train | 198,437 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_bsh | def _translate_bsh(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a BSH instruction.
"""
assert oprnd1.size and oprnd2.size and oprnd3.size
assert oprnd1.size == oprnd2.size
op1_var = self._translate_src_oprnd(oprnd1)
op2_var = self._translate_src_oprnd(oprnd2)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
op1_var_zx = smtfunction.zero_extend(op1_var, oprnd3.size)
op2_var_zx = smtfunction.zero_extend(op2_var, oprnd3.size)
op2_var_neg_sx = smtfunction.sign_extend(-op2_var, oprnd3.size)
shr = smtfunction.extract(op1_var_zx >> op2_var_neg_sx, 0, op3_var.size)
shl = smtfunction.extract(op1_var_zx << op2_var_zx, 0, op3_var.size)
elif oprnd3.size < oprnd1.size:
shr = smtfunction.extract(op1_var >> -op2_var, 0, op3_var.size)
shl = smtfunction.extract(op1_var << op2_var, 0, op3_var.size)
else:
shr = op1_var >> -op2_var
shl = op1_var << op2_var
result = smtfunction.ite(oprnd3.size, op2_var >= 0, shl, shr)
return [op3_var == result] + op3_var_constrs | python | def _translate_bsh(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a BSH instruction.
"""
assert oprnd1.size and oprnd2.size and oprnd3.size
assert oprnd1.size == oprnd2.size
op1_var = self._translate_src_oprnd(oprnd1)
op2_var = self._translate_src_oprnd(oprnd2)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
op1_var_zx = smtfunction.zero_extend(op1_var, oprnd3.size)
op2_var_zx = smtfunction.zero_extend(op2_var, oprnd3.size)
op2_var_neg_sx = smtfunction.sign_extend(-op2_var, oprnd3.size)
shr = smtfunction.extract(op1_var_zx >> op2_var_neg_sx, 0, op3_var.size)
shl = smtfunction.extract(op1_var_zx << op2_var_zx, 0, op3_var.size)
elif oprnd3.size < oprnd1.size:
shr = smtfunction.extract(op1_var >> -op2_var, 0, op3_var.size)
shl = smtfunction.extract(op1_var << op2_var, 0, op3_var.size)
else:
shr = op1_var >> -op2_var
shl = op1_var << op2_var
result = smtfunction.ite(oprnd3.size, op2_var >= 0, shl, shr)
return [op3_var == result] + op3_var_constrs | [
"def",
"_translate_bsh",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd2",
".",
"size",
"and",
"oprnd3",
".",
"size",
"assert",
"oprnd1",
".",
"size",
"==",
"oprnd2",
".",
"size",
"op1... | Return a formula representation of a BSH instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"BSH",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L429-L455 | train | 198,438 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_ldm | def _translate_ldm(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a LDM instruction.
"""
assert oprnd1.size and oprnd3.size
assert oprnd1.size == self._address_size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
exprs = []
for i in reversed(range(0, oprnd3.size, 8)):
exprs += [self._mem_curr[op1_var + i // 8] == smtfunction.extract(op3_var, i, 8)]
return exprs + op3_var_constrs | python | def _translate_ldm(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a LDM instruction.
"""
assert oprnd1.size and oprnd3.size
assert oprnd1.size == self._address_size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
exprs = []
for i in reversed(range(0, oprnd3.size, 8)):
exprs += [self._mem_curr[op1_var + i // 8] == smtfunction.extract(op3_var, i, 8)]
return exprs + op3_var_constrs | [
"def",
"_translate_ldm",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"assert",
"oprnd1",
".",
"size",
"==",
"self",
".",
"_address_size",
"op1_var",
"=",
"self",
".",
... | Return a formula representation of a LDM instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"LDM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L518-L532 | train | 198,439 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_stm | def _translate_stm(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a STM instruction.
"""
assert oprnd1.size and oprnd3.size
assert oprnd3.size == self._address_size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var = self._translate_src_oprnd(oprnd3)
for i in range(0, oprnd1.size, 8):
self._mem_curr[op3_var + i//8] = smtfunction.extract(op1_var, i, 8)
# Memory versioning.
self._mem_instance += 1
mem_old = self._mem_curr
mem_new = self.make_array(self._address_size, "MEM_{}".format(self._mem_instance))
self._mem_curr = mem_new
return [mem_new == mem_old] | python | def _translate_stm(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a STM instruction.
"""
assert oprnd1.size and oprnd3.size
assert oprnd3.size == self._address_size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var = self._translate_src_oprnd(oprnd3)
for i in range(0, oprnd1.size, 8):
self._mem_curr[op3_var + i//8] = smtfunction.extract(op1_var, i, 8)
# Memory versioning.
self._mem_instance += 1
mem_old = self._mem_curr
mem_new = self.make_array(self._address_size, "MEM_{}".format(self._mem_instance))
self._mem_curr = mem_new
return [mem_new == mem_old] | [
"def",
"_translate_stm",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"assert",
"oprnd3",
".",
"size",
"==",
"self",
".",
"_address_size",
"op1_var",
"=",
"self",
".",
... | Return a formula representation of a STM instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"STM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L534-L554 | train | 198,440 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_str | def _translate_str(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a STR instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.zero_extend(op1_var, op3_var.size)
elif oprnd3.size < oprnd1.size:
result = smtfunction.extract(op1_var, 0, op3_var.size)
else:
result = op1_var
return [op3_var == result] + op3_var_constrs | python | def _translate_str(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a STR instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.zero_extend(op1_var, op3_var.size)
elif oprnd3.size < oprnd1.size:
result = smtfunction.extract(op1_var, 0, op3_var.size)
else:
result = op1_var
return [op3_var == result] + op3_var_constrs | [
"def",
"_translate_str",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"op3_var",
",",
"op3_var_co... | Return a formula representation of a STR instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"STR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L556-L571 | train | 198,441 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_bisz | def _translate_bisz(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a BISZ instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
result = smtfunction.ite(oprnd3.size, op1_var == 0x0, smtsymbol.Constant(oprnd3.size, 0x1),
smtsymbol.Constant(oprnd3.size, 0x0))
return [op3_var == result] + op3_var_constrs | python | def _translate_bisz(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a BISZ instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
result = smtfunction.ite(oprnd3.size, op1_var == 0x0, smtsymbol.Constant(oprnd3.size, 0x1),
smtsymbol.Constant(oprnd3.size, 0x0))
return [op3_var == result] + op3_var_constrs | [
"def",
"_translate_bisz",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"op3_var",
",",
"op3_var_c... | Return a formula representation of a BISZ instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"BISZ",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L575-L586 | train | 198,442 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_jcc | def _translate_jcc(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a JCC instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
return [op1_var != 0x0] | python | def _translate_jcc(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a JCC instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
return [op1_var != 0x0] | [
"def",
"_translate_jcc",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"return",
"[",
"op1_var",
... | Return a formula representation of a JCC instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"JCC",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L588-L595 | train | 198,443 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | SmtTranslator._translate_sext | def _translate_sext(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a SEXT instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.sign_extend(op1_var, op3_var.size)
elif oprnd3.size < oprnd1.size:
raise Exception("Operands size mismatch.")
else:
result = op1_var
return [op3_var == result] + op3_var_constrs | python | def _translate_sext(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of a SEXT instruction.
"""
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.sign_extend(op1_var, op3_var.size)
elif oprnd3.size < oprnd1.size:
raise Exception("Operands size mismatch.")
else:
result = op1_var
return [op3_var == result] + op3_var_constrs | [
"def",
"_translate_sext",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd3",
".",
"size",
"op1_var",
"=",
"self",
".",
"_translate_src_oprnd",
"(",
"oprnd1",
")",
"op3_var",
",",
"op3_var_c... | Return a formula representation of a SEXT instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"a",
"SEXT",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L616-L631 | train | 198,444 |
programa-stic/barf-project | barf/analysis/gadgets/verifier.py | GadgetVerifier.verify | def verify(self, gadget):
"""Verify gadgets.
"""
# Add instructions to the analyzer
self.analyzer.reset()
for reil_instr in gadget.ir_instrs:
self.analyzer.add_instruction(reil_instr)
# Generate constraints for the gadgets type.
constrs = self._constraints_generators[gadget.type](gadget)
# Check constraints.
if not constrs:
return False
for constr in constrs:
self.analyzer.add_constraint(constr)
return self.analyzer.check() == 'unsat' | python | def verify(self, gadget):
"""Verify gadgets.
"""
# Add instructions to the analyzer
self.analyzer.reset()
for reil_instr in gadget.ir_instrs:
self.analyzer.add_instruction(reil_instr)
# Generate constraints for the gadgets type.
constrs = self._constraints_generators[gadget.type](gadget)
# Check constraints.
if not constrs:
return False
for constr in constrs:
self.analyzer.add_constraint(constr)
return self.analyzer.check() == 'unsat' | [
"def",
"verify",
"(",
"self",
",",
"gadget",
")",
":",
"# Add instructions to the analyzer",
"self",
".",
"analyzer",
".",
"reset",
"(",
")",
"for",
"reil_instr",
"in",
"gadget",
".",
"ir_instrs",
":",
"self",
".",
"analyzer",
".",
"add_instruction",
"(",
"r... | Verify gadgets. | [
"Verify",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/verifier.py#L97-L116 | train | 198,445 |
programa-stic/barf-project | barf/analysis/gadgets/verifier.py | GadgetVerifier._get_constrs_no_operation | def _get_constrs_no_operation(self, gadget):
"""Verify NoOperation gadgets.
"""
# Constraints on memory locations.
# mem_constrs = [self.analyzer.get_memory("pre") != self.analyzer.get_memory("post")]
mem_constrs = [self.analyzer.get_memory_curr("pre").__neq__(self.analyzer.get_memory_curr("post"))]
# Constraints on flags.
flags_constrs = []
for name in self._arch_info.registers_flags:
var_initial = self.analyzer.get_register_expr(name, mode="pre")
var_final = self.analyzer.get_register_expr(name, mode="post")
flags_constrs += [var_initial != var_final]
# Constraints on registers.
reg_constrs = []
for name in self._arch_info.registers_gp_base:
var_initial = self.analyzer.get_register_expr(name, mode="pre")
var_final = self.analyzer.get_register_expr(name, mode="post")
reg_constrs += [var_initial != var_final]
# Make a big OR expression.
constrs = mem_constrs + flags_constrs + reg_constrs
constrs = [reduce(lambda c, acc: acc | c, constrs[1:], constrs[0])]
return constrs | python | def _get_constrs_no_operation(self, gadget):
"""Verify NoOperation gadgets.
"""
# Constraints on memory locations.
# mem_constrs = [self.analyzer.get_memory("pre") != self.analyzer.get_memory("post")]
mem_constrs = [self.analyzer.get_memory_curr("pre").__neq__(self.analyzer.get_memory_curr("post"))]
# Constraints on flags.
flags_constrs = []
for name in self._arch_info.registers_flags:
var_initial = self.analyzer.get_register_expr(name, mode="pre")
var_final = self.analyzer.get_register_expr(name, mode="post")
flags_constrs += [var_initial != var_final]
# Constraints on registers.
reg_constrs = []
for name in self._arch_info.registers_gp_base:
var_initial = self.analyzer.get_register_expr(name, mode="pre")
var_final = self.analyzer.get_register_expr(name, mode="post")
reg_constrs += [var_initial != var_final]
# Make a big OR expression.
constrs = mem_constrs + flags_constrs + reg_constrs
constrs = [reduce(lambda c, acc: acc | c, constrs[1:], constrs[0])]
return constrs | [
"def",
"_get_constrs_no_operation",
"(",
"self",
",",
"gadget",
")",
":",
"# Constraints on memory locations.",
"# mem_constrs = [self.analyzer.get_memory(\"pre\") != self.analyzer.get_memory(\"post\")]",
"mem_constrs",
"=",
"[",
"self",
".",
"analyzer",
".",
"get_memory_curr",
"... | Verify NoOperation gadgets. | [
"Verify",
"NoOperation",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/verifier.py#L120-L149 | train | 198,446 |
programa-stic/barf-project | barf/arch/x86/parser.py | infer_operands_size | def infer_operands_size(operands):
"""Infer x86 instruction operand size based on other operands.
"""
size = None
for oprnd in operands:
if oprnd.size:
size = oprnd.size
break
if size:
for oprnd in operands:
if not oprnd.size:
oprnd.size = size
else:
for oprnd in operands:
if isinstance(oprnd, X86ImmediateOperand) and not oprnd.size:
oprnd.size = arch_info.architecture_size | python | def infer_operands_size(operands):
"""Infer x86 instruction operand size based on other operands.
"""
size = None
for oprnd in operands:
if oprnd.size:
size = oprnd.size
break
if size:
for oprnd in operands:
if not oprnd.size:
oprnd.size = size
else:
for oprnd in operands:
if isinstance(oprnd, X86ImmediateOperand) and not oprnd.size:
oprnd.size = arch_info.architecture_size | [
"def",
"infer_operands_size",
"(",
"operands",
")",
":",
"size",
"=",
"None",
"for",
"oprnd",
"in",
"operands",
":",
"if",
"oprnd",
".",
"size",
":",
"size",
"=",
"oprnd",
".",
"size",
"break",
"if",
"size",
":",
"for",
"oprnd",
"in",
"operands",
":",
... | Infer x86 instruction operand size based on other operands. | [
"Infer",
"x86",
"instruction",
"operand",
"size",
"based",
"on",
"other",
"operands",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/x86/parser.py#L71-L88 | train | 198,447 |
programa-stic/barf-project | barf/arch/x86/parser.py | parse_operand | def parse_operand(string, location, tokens):
"""Parse an x86 instruction operand.
"""
mod = " ".join(tokens.get("modifier", ""))
if "immediate" in tokens:
imm = parse_immediate("".join(tokens["immediate"]))
size = modifier_size.get(mod, None)
oprnd = X86ImmediateOperand(imm, size)
if "register" in tokens:
name = tokens["register"]
size = arch_info.registers_size[tokens["register"]]
oprnd = X86RegisterOperand(name, size)
if "memory" in tokens:
seg_reg = tokens.get("segment", None)
base_reg = tokens.get("base", None)
index_reg = tokens.get("index", None)
scale_imm = int(tokens.get("scale", "0x1"), 16)
displ_imm = int("".join(tokens.get("displacement", "0x0")), 16)
oprnd = X86MemoryOperand(seg_reg, base_reg, index_reg, scale_imm, displ_imm)
oprnd.modifier = mod
if not oprnd.size and oprnd.modifier:
oprnd.size = modifier_size[oprnd.modifier]
return oprnd | python | def parse_operand(string, location, tokens):
"""Parse an x86 instruction operand.
"""
mod = " ".join(tokens.get("modifier", ""))
if "immediate" in tokens:
imm = parse_immediate("".join(tokens["immediate"]))
size = modifier_size.get(mod, None)
oprnd = X86ImmediateOperand(imm, size)
if "register" in tokens:
name = tokens["register"]
size = arch_info.registers_size[tokens["register"]]
oprnd = X86RegisterOperand(name, size)
if "memory" in tokens:
seg_reg = tokens.get("segment", None)
base_reg = tokens.get("base", None)
index_reg = tokens.get("index", None)
scale_imm = int(tokens.get("scale", "0x1"), 16)
displ_imm = int("".join(tokens.get("displacement", "0x0")), 16)
oprnd = X86MemoryOperand(seg_reg, base_reg, index_reg, scale_imm, displ_imm)
oprnd.modifier = mod
if not oprnd.size and oprnd.modifier:
oprnd.size = modifier_size[oprnd.modifier]
return oprnd | [
"def",
"parse_operand",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"mod",
"=",
"\" \"",
".",
"join",
"(",
"tokens",
".",
"get",
"(",
"\"modifier\"",
",",
"\"\"",
")",
")",
"if",
"\"immediate\"",
"in",
"tokens",
":",
"imm",
"=",
"parse_imm... | Parse an x86 instruction operand. | [
"Parse",
"an",
"x86",
"instruction",
"operand",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/x86/parser.py#L100-L131 | train | 198,448 |
programa-stic/barf-project | barf/core/reil/emulator/emulator.py | ReilEmulator.execute_lite | def execute_lite(self, instructions, context=None):
"""Execute a list of instructions. It does not support loops.
"""
if context:
self.__cpu.registers = dict(context)
for instr in instructions:
self.__execute_one(instr)
return dict(self.__cpu.registers), self.__mem | python | def execute_lite(self, instructions, context=None):
"""Execute a list of instructions. It does not support loops.
"""
if context:
self.__cpu.registers = dict(context)
for instr in instructions:
self.__execute_one(instr)
return dict(self.__cpu.registers), self.__mem | [
"def",
"execute_lite",
"(",
"self",
",",
"instructions",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
":",
"self",
".",
"__cpu",
".",
"registers",
"=",
"dict",
"(",
"context",
")",
"for",
"instr",
"in",
"instructions",
":",
"self",
".",
"__e... | Execute a list of instructions. It does not support loops. | [
"Execute",
"a",
"list",
"of",
"instructions",
".",
"It",
"does",
"not",
"support",
"loops",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/emulator.py#L108-L117 | train | 198,449 |
programa-stic/barf-project | barf/core/reil/emulator/emulator.py | ReilEmulator.reset | def reset(self):
"""Reset emulator. All registers and memory are reset.
"""
self.__mem.reset()
self.__cpu.reset()
self.__tainter.reset()
# Instructions pre and post handlers.
self.__instr_handler_pre = None, None
self.__instr_handler_post = None, None
self.__set_default_handlers() | python | def reset(self):
"""Reset emulator. All registers and memory are reset.
"""
self.__mem.reset()
self.__cpu.reset()
self.__tainter.reset()
# Instructions pre and post handlers.
self.__instr_handler_pre = None, None
self.__instr_handler_post = None, None
self.__set_default_handlers() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"__mem",
".",
"reset",
"(",
")",
"self",
".",
"__cpu",
".",
"reset",
"(",
")",
"self",
".",
"__tainter",
".",
"reset",
"(",
")",
"# Instructions pre and post handlers.",
"self",
".",
"__instr_handler_pre"... | Reset emulator. All registers and memory are reset. | [
"Reset",
"emulator",
".",
"All",
"registers",
"and",
"memory",
"are",
"reset",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/emulator.py#L141-L152 | train | 198,450 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_bsh | def __execute_bsh(self, instr):
"""Execute BSH instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op1_val = self.read_operand(instr.operands[1])
op1_size = instr.operands[1].size
# Check sign bit.
if extract_sign_bit(op1_val, op1_size) == 0:
op2_val = op0_val << op1_val
else:
op2_val = op0_val >> twos_complement(op1_val, op1_size)
self.write_operand(instr.operands[2], op2_val)
return None | python | def __execute_bsh(self, instr):
"""Execute BSH instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op1_val = self.read_operand(instr.operands[1])
op1_size = instr.operands[1].size
# Check sign bit.
if extract_sign_bit(op1_val, op1_size) == 0:
op2_val = op0_val << op1_val
else:
op2_val = op0_val >> twos_complement(op1_val, op1_size)
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_bsh",
"(",
"self",
",",
"instr",
")",
":",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"op1_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"1",
"]",
")... | Execute BSH instruction. | [
"Execute",
"BSH",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L301-L317 | train | 198,451 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_ldm | def __execute_ldm(self, instr):
"""Execute LDM instruction.
"""
assert instr.operands[0].size == self.__mem.address_size
assert instr.operands[2].size in [8, 16, 32, 64, 128, 256]
# Memory address.
op0_val = self.read_operand(instr.operands[0])
# Data.
op2_val = self.read_memory(op0_val, instr.operands[2].size // 8)
self.write_operand(instr.operands[2], op2_val)
return None | python | def __execute_ldm(self, instr):
"""Execute LDM instruction.
"""
assert instr.operands[0].size == self.__mem.address_size
assert instr.operands[2].size in [8, 16, 32, 64, 128, 256]
# Memory address.
op0_val = self.read_operand(instr.operands[0])
# Data.
op2_val = self.read_memory(op0_val, instr.operands[2].size // 8)
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_ldm",
"(",
"self",
",",
"instr",
")",
":",
"assert",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"==",
"self",
".",
"__mem",
".",
"address_size",
"assert",
"instr",
".",
"operands",
"[",
"2",
"]",
".",
"size",
"in",
"[",
... | Execute LDM instruction. | [
"Execute",
"LDM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L418-L431 | train | 198,452 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_stm | def __execute_stm(self, instr):
"""Execute STM instruction.
"""
assert instr.operands[0].size in [8, 16, 32, 64, 128, 256]
assert instr.operands[2].size == self.__mem.address_size
op0_val = self.read_operand(instr.operands[0]) # Data.
op2_val = self.read_operand(instr.operands[2]) # Memory address.
op0_size = instr.operands[0].size
self.write_memory(op2_val, op0_size // 8, op0_val)
return None | python | def __execute_stm(self, instr):
"""Execute STM instruction.
"""
assert instr.operands[0].size in [8, 16, 32, 64, 128, 256]
assert instr.operands[2].size == self.__mem.address_size
op0_val = self.read_operand(instr.operands[0]) # Data.
op2_val = self.read_operand(instr.operands[2]) # Memory address.
op0_size = instr.operands[0].size
self.write_memory(op2_val, op0_size // 8, op0_val)
return None | [
"def",
"__execute_stm",
"(",
"self",
",",
"instr",
")",
":",
"assert",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"in",
"[",
"8",
",",
"16",
",",
"32",
",",
"64",
",",
"128",
",",
"256",
"]",
"assert",
"instr",
".",
"operands",
"[",
... | Execute STM instruction. | [
"Execute",
"STM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L433-L446 | train | 198,453 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_str | def __execute_str(self, instr):
"""Execute STR instruction.
"""
op0_val = self.read_operand(instr.operands[0])
self.write_operand(instr.operands[2], op0_val)
return None | python | def __execute_str(self, instr):
"""Execute STR instruction.
"""
op0_val = self.read_operand(instr.operands[0])
self.write_operand(instr.operands[2], op0_val)
return None | [
"def",
"__execute_str",
"(",
"self",
",",
"instr",
")",
":",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"self",
".",
"write_operand",
"(",
"instr",
".",
"operands",
"[",
"2",
"]",
",",
"op0_val",
"... | Execute STR instruction. | [
"Execute",
"STR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L448-L455 | train | 198,454 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_bisz | def __execute_bisz(self, instr):
"""Execute BISZ instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op2_val = 1 if op0_val == 0 else 0
self.write_operand(instr.operands[2], op2_val)
return None | python | def __execute_bisz(self, instr):
"""Execute BISZ instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op2_val = 1 if op0_val == 0 else 0
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_bisz",
"(",
"self",
",",
"instr",
")",
":",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"op2_val",
"=",
"1",
"if",
"op0_val",
"==",
"0",
"else",
"0",
"self",
".",
"write_operand",
... | Execute BISZ instruction. | [
"Execute",
"BISZ",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L459-L468 | train | 198,455 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_jcc | def __execute_jcc(self, instr):
"""Execute JCC instruction.
"""
op0_val = self.read_operand(instr.operands[0]) # Branch condition.
op2_val = self.read_operand(instr.operands[2]) # Target address.
return op2_val if op0_val != 0 else None | python | def __execute_jcc(self, instr):
"""Execute JCC instruction.
"""
op0_val = self.read_operand(instr.operands[0]) # Branch condition.
op2_val = self.read_operand(instr.operands[2]) # Target address.
return op2_val if op0_val != 0 else None | [
"def",
"__execute_jcc",
"(",
"self",
",",
"instr",
")",
":",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"# Branch condition.",
"op2_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
... | Execute JCC instruction. | [
"Execute",
"JCC",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L470-L476 | train | 198,456 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_undef | def __execute_undef(self, instr):
"""Execute UNDEF instruction.
"""
op2_val = random.randint(0, instr.operands[2].size)
self.write_operand(instr.operands[2], op2_val)
return None | python | def __execute_undef(self, instr):
"""Execute UNDEF instruction.
"""
op2_val = random.randint(0, instr.operands[2].size)
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_undef",
"(",
"self",
",",
"instr",
")",
":",
"op2_val",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"instr",
".",
"operands",
"[",
"2",
"]",
".",
"size",
")",
"self",
".",
"write_operand",
"(",
"instr",
".",
"operands",
"[",
"2",
... | Execute UNDEF instruction. | [
"Execute",
"UNDEF",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L480-L487 | train | 198,457 |
programa-stic/barf-project | barf/core/reil/emulator/cpu.py | ReilCpu.__execute_sext | def __execute_sext(self, instr):
"""Execute SEXT instruction.
"""
op0_size = instr.operands[0].size
op2_size = instr.operands[2].size
op0_val = self.read_operand(instr.operands[0])
op0_msb = extract_sign_bit(op0_val, op0_size)
op2_mask = (2**op2_size-1) & ~(2**op0_size-1) if op0_msb == 1 else 0x0
op2_val = op0_val | op2_mask
self.write_operand(instr.operands[2], op2_val)
return None | python | def __execute_sext(self, instr):
"""Execute SEXT instruction.
"""
op0_size = instr.operands[0].size
op2_size = instr.operands[2].size
op0_val = self.read_operand(instr.operands[0])
op0_msb = extract_sign_bit(op0_val, op0_size)
op2_mask = (2**op2_size-1) & ~(2**op0_size-1) if op0_msb == 1 else 0x0
op2_val = op0_val | op2_mask
self.write_operand(instr.operands[2], op2_val)
return None | [
"def",
"__execute_sext",
"(",
"self",
",",
"instr",
")",
":",
"op0_size",
"=",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"op2_size",
"=",
"instr",
".",
"operands",
"[",
"2",
"]",
".",
"size",
"op0_val",
"=",
"self",
".",
"read_operand",
"... | Execute SEXT instruction. | [
"Execute",
"SEXT",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/cpu.py#L501-L516 | train | 198,458 |
programa-stic/barf-project | barf/utils/utils.py | VariableNamer.get_init | def get_init(self):
"""Return initial name.
"""
suffix = self._separator + "%s" % str(self._counter_init)
return self._base_name + suffix | python | def get_init(self):
"""Return initial name.
"""
suffix = self._separator + "%s" % str(self._counter_init)
return self._base_name + suffix | [
"def",
"get_init",
"(",
"self",
")",
":",
"suffix",
"=",
"self",
".",
"_separator",
"+",
"\"%s\"",
"%",
"str",
"(",
"self",
".",
"_counter_init",
")",
"return",
"self",
".",
"_base_name",
"+",
"suffix"
] | Return initial name. | [
"Return",
"initial",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/utils/utils.py#L71-L76 | train | 198,459 |
programa-stic/barf-project | barf/utils/utils.py | VariableNamer.get_current | def get_current(self):
"""Return current name.
"""
suffix = self._separator + "%s" % str(self._counter_curr)
return self._base_name + suffix | python | def get_current(self):
"""Return current name.
"""
suffix = self._separator + "%s" % str(self._counter_curr)
return self._base_name + suffix | [
"def",
"get_current",
"(",
"self",
")",
":",
"suffix",
"=",
"self",
".",
"_separator",
"+",
"\"%s\"",
"%",
"str",
"(",
"self",
".",
"_counter_curr",
")",
"return",
"self",
".",
"_base_name",
"+",
"suffix"
] | Return current name. | [
"Return",
"current",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/utils/utils.py#L78-L83 | train | 198,460 |
programa-stic/barf-project | barf/utils/utils.py | VariableNamer.get_next | def get_next(self):
"""Return next name.
"""
self._counter_curr += 1
suffix = self._separator + "%s" % str(self._counter_curr)
return self._base_name + suffix | python | def get_next(self):
"""Return next name.
"""
self._counter_curr += 1
suffix = self._separator + "%s" % str(self._counter_curr)
return self._base_name + suffix | [
"def",
"get_next",
"(",
"self",
")",
":",
"self",
".",
"_counter_curr",
"+=",
"1",
"suffix",
"=",
"self",
".",
"_separator",
"+",
"\"%s\"",
"%",
"str",
"(",
"self",
".",
"_counter_curr",
")",
"return",
"self",
".",
"_base_name",
"+",
"suffix"
] | Return next name. | [
"Return",
"next",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/utils/utils.py#L85-L92 | train | 198,461 |
programa-stic/barf-project | examples/misc/check_paths.x86.py | check_path_satisfiability | def check_path_satisfiability(code_analyzer, path, start_address):
"""Check satisfiability of a basic block path.
"""
start_instr_found = False
sat = False
# Traverse basic blocks, translate its instructions to SMT
# expressions and add them as assertions.
for bb_curr, bb_next in zip(path[:-1], path[1:]):
logger.info("BB @ {:#x}".format(bb_curr.address))
# For each instruction...
for instr in bb_curr:
# If the start instruction have not been found, keep
# looking...
if not start_instr_found:
if instr.address == start_address:
start_instr_found = True
else:
continue
logger.info("{:#x} {}".format(instr.address, instr))
# For each REIL instruction...
for reil_instr in instr.ir_instrs:
logger.info("{:#x} {:02d} {}".format(reil_instr.address >> 0x8, reil_instr.address & 0xff,
reil_instr))
if reil_instr.mnemonic == ReilMnemonic.JCC:
# Check that the JCC is the last instruction of
# the basic block (skip CALL instructions.)
if instr.address + instr.size - 1 != bb_curr.end_address:
logger.error("Unexpected JCC instruction: {:#x} {} ({})".format(instr.address,
instr,
reil_instr))
# raise Exception()
continue
# Make sure branch target address from current
# basic block is the start address of the next.
assert(bb_curr.taken_branch == bb_next.address or
bb_curr.not_taken_branch == bb_next.address or
bb_curr.direct_branch == bb_next.address)
# Set branch condition accordingly.
if bb_curr.taken_branch == bb_next.address:
branch_var_goal = 0x1
elif bb_curr.not_taken_branch == bb_next.address:
branch_var_goal = 0x0
else:
continue
# Add branch condition goal constraint.
code_analyzer.add_constraint(code_analyzer.get_operand_expr(reil_instr.operands[0]) == branch_var_goal)
# The JCC instruction was the last within the
# current basic block. End this iteration and
# start next one.
break
# Translate and add SMT expressions to the solver.
code_analyzer.add_instruction(reil_instr)
sat = code_analyzer.check() == 'sat'
logger.info("BB @ {:#x} sat? {}".format(bb_curr.address, sat))
if not sat:
break
# Return satisfiability.
return sat | python | def check_path_satisfiability(code_analyzer, path, start_address):
"""Check satisfiability of a basic block path.
"""
start_instr_found = False
sat = False
# Traverse basic blocks, translate its instructions to SMT
# expressions and add them as assertions.
for bb_curr, bb_next in zip(path[:-1], path[1:]):
logger.info("BB @ {:#x}".format(bb_curr.address))
# For each instruction...
for instr in bb_curr:
# If the start instruction have not been found, keep
# looking...
if not start_instr_found:
if instr.address == start_address:
start_instr_found = True
else:
continue
logger.info("{:#x} {}".format(instr.address, instr))
# For each REIL instruction...
for reil_instr in instr.ir_instrs:
logger.info("{:#x} {:02d} {}".format(reil_instr.address >> 0x8, reil_instr.address & 0xff,
reil_instr))
if reil_instr.mnemonic == ReilMnemonic.JCC:
# Check that the JCC is the last instruction of
# the basic block (skip CALL instructions.)
if instr.address + instr.size - 1 != bb_curr.end_address:
logger.error("Unexpected JCC instruction: {:#x} {} ({})".format(instr.address,
instr,
reil_instr))
# raise Exception()
continue
# Make sure branch target address from current
# basic block is the start address of the next.
assert(bb_curr.taken_branch == bb_next.address or
bb_curr.not_taken_branch == bb_next.address or
bb_curr.direct_branch == bb_next.address)
# Set branch condition accordingly.
if bb_curr.taken_branch == bb_next.address:
branch_var_goal = 0x1
elif bb_curr.not_taken_branch == bb_next.address:
branch_var_goal = 0x0
else:
continue
# Add branch condition goal constraint.
code_analyzer.add_constraint(code_analyzer.get_operand_expr(reil_instr.operands[0]) == branch_var_goal)
# The JCC instruction was the last within the
# current basic block. End this iteration and
# start next one.
break
# Translate and add SMT expressions to the solver.
code_analyzer.add_instruction(reil_instr)
sat = code_analyzer.check() == 'sat'
logger.info("BB @ {:#x} sat? {}".format(bb_curr.address, sat))
if not sat:
break
# Return satisfiability.
return sat | [
"def",
"check_path_satisfiability",
"(",
"code_analyzer",
",",
"path",
",",
"start_address",
")",
":",
"start_instr_found",
"=",
"False",
"sat",
"=",
"False",
"# Traverse basic blocks, translate its instructions to SMT",
"# expressions and add them as assertions.",
"for",
"bb_c... | Check satisfiability of a basic block path. | [
"Check",
"satisfiability",
"of",
"a",
"basic",
"block",
"path",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/examples/misc/check_paths.x86.py#L15-L88 | train | 198,462 |
programa-stic/barf-project | barf/core/reil/reil.py | ReilMnemonic.to_string | def to_string(mnemonic):
"""Return the string representation of the given mnemonic.
"""
strings = {
# Arithmetic Instructions
ReilMnemonic.ADD: "add",
ReilMnemonic.SUB: "sub",
ReilMnemonic.MUL: "mul",
ReilMnemonic.DIV: "div",
ReilMnemonic.MOD: "mod",
ReilMnemonic.BSH: "bsh",
# Bitwise Instructions
ReilMnemonic.AND: "and",
ReilMnemonic.OR: "or",
ReilMnemonic.XOR: "xor",
# Data Transfer Instructions
ReilMnemonic.LDM: "ldm",
ReilMnemonic.STM: "stm",
ReilMnemonic.STR: "str",
# Conditional Instructions
ReilMnemonic.BISZ: "bisz",
ReilMnemonic.JCC: "jcc",
# Other Instructions
ReilMnemonic.UNKN: "unkn",
ReilMnemonic.UNDEF: "undef",
ReilMnemonic.NOP: "nop",
# Extensions
ReilMnemonic.SEXT: "sext",
ReilMnemonic.SDIV: "sdiv",
ReilMnemonic.SMOD: "smod",
ReilMnemonic.SMUL: "smul",
}
return strings[mnemonic] | python | def to_string(mnemonic):
"""Return the string representation of the given mnemonic.
"""
strings = {
# Arithmetic Instructions
ReilMnemonic.ADD: "add",
ReilMnemonic.SUB: "sub",
ReilMnemonic.MUL: "mul",
ReilMnemonic.DIV: "div",
ReilMnemonic.MOD: "mod",
ReilMnemonic.BSH: "bsh",
# Bitwise Instructions
ReilMnemonic.AND: "and",
ReilMnemonic.OR: "or",
ReilMnemonic.XOR: "xor",
# Data Transfer Instructions
ReilMnemonic.LDM: "ldm",
ReilMnemonic.STM: "stm",
ReilMnemonic.STR: "str",
# Conditional Instructions
ReilMnemonic.BISZ: "bisz",
ReilMnemonic.JCC: "jcc",
# Other Instructions
ReilMnemonic.UNKN: "unkn",
ReilMnemonic.UNDEF: "undef",
ReilMnemonic.NOP: "nop",
# Extensions
ReilMnemonic.SEXT: "sext",
ReilMnemonic.SDIV: "sdiv",
ReilMnemonic.SMOD: "smod",
ReilMnemonic.SMUL: "smul",
}
return strings[mnemonic] | [
"def",
"to_string",
"(",
"mnemonic",
")",
":",
"strings",
"=",
"{",
"# Arithmetic Instructions",
"ReilMnemonic",
".",
"ADD",
":",
"\"add\"",
",",
"ReilMnemonic",
".",
"SUB",
":",
"\"sub\"",
",",
"ReilMnemonic",
".",
"MUL",
":",
"\"mul\"",
",",
"ReilMnemonic",
... | Return the string representation of the given mnemonic. | [
"Return",
"the",
"string",
"representation",
"of",
"the",
"given",
"mnemonic",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/reil.py#L100-L138 | train | 198,463 |
programa-stic/barf-project | barf/core/reil/reil.py | ReilMnemonic.from_string | def from_string(string):
"""Return the mnemonic represented by the given string.
"""
mnemonics = {
# Arithmetic Instructions
"add": ReilMnemonic.ADD,
"sub": ReilMnemonic.SUB,
"mul": ReilMnemonic.MUL,
"div": ReilMnemonic.DIV,
"mod": ReilMnemonic.MOD,
"bsh": ReilMnemonic.BSH,
# Bitwise Instructions
"and": ReilMnemonic.AND,
"or": ReilMnemonic.OR,
"xor": ReilMnemonic.XOR,
# Data Transfer Instructions
"ldm": ReilMnemonic.LDM,
"stm": ReilMnemonic.STM,
"str": ReilMnemonic.STR,
# Conditional Instructions
"bisz": ReilMnemonic.BISZ,
"jcc": ReilMnemonic.JCC,
# Other Instructions
"unkn": ReilMnemonic.UNKN,
"undef": ReilMnemonic.UNDEF,
"nop": ReilMnemonic.NOP,
# Added Instructions
"sext": ReilMnemonic.SEXT,
"sdiv": ReilMnemonic.SDIV,
"smod": ReilMnemonic.SMOD,
"smul": ReilMnemonic.SMUL,
}
return mnemonics[string] | python | def from_string(string):
"""Return the mnemonic represented by the given string.
"""
mnemonics = {
# Arithmetic Instructions
"add": ReilMnemonic.ADD,
"sub": ReilMnemonic.SUB,
"mul": ReilMnemonic.MUL,
"div": ReilMnemonic.DIV,
"mod": ReilMnemonic.MOD,
"bsh": ReilMnemonic.BSH,
# Bitwise Instructions
"and": ReilMnemonic.AND,
"or": ReilMnemonic.OR,
"xor": ReilMnemonic.XOR,
# Data Transfer Instructions
"ldm": ReilMnemonic.LDM,
"stm": ReilMnemonic.STM,
"str": ReilMnemonic.STR,
# Conditional Instructions
"bisz": ReilMnemonic.BISZ,
"jcc": ReilMnemonic.JCC,
# Other Instructions
"unkn": ReilMnemonic.UNKN,
"undef": ReilMnemonic.UNDEF,
"nop": ReilMnemonic.NOP,
# Added Instructions
"sext": ReilMnemonic.SEXT,
"sdiv": ReilMnemonic.SDIV,
"smod": ReilMnemonic.SMOD,
"smul": ReilMnemonic.SMUL,
}
return mnemonics[string] | [
"def",
"from_string",
"(",
"string",
")",
":",
"mnemonics",
"=",
"{",
"# Arithmetic Instructions",
"\"add\"",
":",
"ReilMnemonic",
".",
"ADD",
",",
"\"sub\"",
":",
"ReilMnemonic",
".",
"SUB",
",",
"\"mul\"",
":",
"ReilMnemonic",
".",
"MUL",
",",
"\"div\"",
"... | Return the mnemonic represented by the given string. | [
"Return",
"the",
"mnemonic",
"represented",
"by",
"the",
"given",
"string",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/reil.py#L141-L179 | train | 198,464 |
programa-stic/barf-project | barf/core/reil/reil.py | ReilInstruction.mnemonic | def mnemonic(self, value):
"""Set instruction mnemonic.
"""
if value not in REIL_MNEMONICS:
raise Exception("Invalid instruction mnemonic : %s" % str(value))
self._mnemonic = value | python | def mnemonic(self, value):
"""Set instruction mnemonic.
"""
if value not in REIL_MNEMONICS:
raise Exception("Invalid instruction mnemonic : %s" % str(value))
self._mnemonic = value | [
"def",
"mnemonic",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"REIL_MNEMONICS",
":",
"raise",
"Exception",
"(",
"\"Invalid instruction mnemonic : %s\"",
"%",
"str",
"(",
"value",
")",
")",
"self",
".",
"_mnemonic",
"=",
"value"
] | Set instruction mnemonic. | [
"Set",
"instruction",
"mnemonic",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/reil.py#L257-L263 | train | 198,465 |
programa-stic/barf-project | barf/core/reil/reil.py | ReilInstruction.operands | def operands(self, value):
"""Set instruction operands.
"""
if len(value) != 3:
raise Exception("Invalid instruction operands : %s" % str(value))
self._operands = value | python | def operands(self, value):
"""Set instruction operands.
"""
if len(value) != 3:
raise Exception("Invalid instruction operands : %s" % str(value))
self._operands = value | [
"def",
"operands",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"3",
":",
"raise",
"Exception",
"(",
"\"Invalid instruction operands : %s\"",
"%",
"str",
"(",
"value",
")",
")",
"self",
".",
"_operands",
"=",
"value"
] | Set instruction operands. | [
"Set",
"instruction",
"operands",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/reil.py#L272-L278 | train | 198,466 |
programa-stic/barf-project | barf/core/reil/emulator/tainter.py | ReilEmulatorTainter.__taint_load | def __taint_load(self, instr):
"""Taint LDM instruction.
"""
# Get memory address.
op0_val = self.__emu.read_operand(instr.operands[0])
# Get taint information.
op0_taint = self.get_memory_taint(op0_val, instr.operands[2].size // 8)
# Propagate taint.
self.set_operand_taint(instr.operands[2], op0_taint) | python | def __taint_load(self, instr):
"""Taint LDM instruction.
"""
# Get memory address.
op0_val = self.__emu.read_operand(instr.operands[0])
# Get taint information.
op0_taint = self.get_memory_taint(op0_val, instr.operands[2].size // 8)
# Propagate taint.
self.set_operand_taint(instr.operands[2], op0_taint) | [
"def",
"__taint_load",
"(",
"self",
",",
"instr",
")",
":",
"# Get memory address.",
"op0_val",
"=",
"self",
".",
"__emu",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"# Get taint information.",
"op0_taint",
"=",
"self",
".",
"get... | Taint LDM instruction. | [
"Taint",
"LDM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/tainter.py#L170-L180 | train | 198,467 |
programa-stic/barf-project | barf/core/reil/emulator/tainter.py | ReilEmulatorTainter.__taint_store | def __taint_store(self, instr):
"""Taint STM instruction.
"""
# Get memory address.
op2_val = self.__emu.read_operand(instr.operands[2])
# Get taint information.
op0_size = instr.operands[0].size
op0_taint = self.get_operand_taint(instr.operands[0])
# Propagate taint.
self.set_memory_taint(op2_val, op0_size // 8, op0_taint) | python | def __taint_store(self, instr):
"""Taint STM instruction.
"""
# Get memory address.
op2_val = self.__emu.read_operand(instr.operands[2])
# Get taint information.
op0_size = instr.operands[0].size
op0_taint = self.get_operand_taint(instr.operands[0])
# Propagate taint.
self.set_memory_taint(op2_val, op0_size // 8, op0_taint) | [
"def",
"__taint_store",
"(",
"self",
",",
"instr",
")",
":",
"# Get memory address.",
"op2_val",
"=",
"self",
".",
"__emu",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"2",
"]",
")",
"# Get taint information.",
"op0_size",
"=",
"instr",
".",
"op... | Taint STM instruction. | [
"Taint",
"STM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/tainter.py#L182-L193 | train | 198,468 |
programa-stic/barf-project | barf/core/reil/emulator/tainter.py | ReilEmulatorTainter.__taint_move | def __taint_move(self, instr):
"""Taint registers move instruction.
"""
# Get taint information.
op0_taint = self.get_operand_taint(instr.operands[0])
# Propagate taint.
self.set_operand_taint(instr.operands[2], op0_taint) | python | def __taint_move(self, instr):
"""Taint registers move instruction.
"""
# Get taint information.
op0_taint = self.get_operand_taint(instr.operands[0])
# Propagate taint.
self.set_operand_taint(instr.operands[2], op0_taint) | [
"def",
"__taint_move",
"(",
"self",
",",
"instr",
")",
":",
"# Get taint information.",
"op0_taint",
"=",
"self",
".",
"get_operand_taint",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"# Propagate taint.",
"self",
".",
"set_operand_taint",
"(",
"instr",
... | Taint registers move instruction. | [
"Taint",
"registers",
"move",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/tainter.py#L195-L202 | train | 198,469 |
programa-stic/barf-project | barf/arch/emulator.py | Emulator.execute | def execute(self, asm_instr):
"""Execute an assembler instruction.
Args:
asm_instr (X86Instruction): A instruction to execute.
Returns:
A int. The address of the next instruction to execute.
"""
# Update the instruction pointer.
self.ir_emulator.registers[self.ip] = asm_instr.address + asm_instr.size
# Process syscall.
if self.arch_info.instr_is_syscall(asm_instr):
raise Syscall()
# Process instruction and return next address instruction to execute.
return self.__execute(asm_instr) | python | def execute(self, asm_instr):
"""Execute an assembler instruction.
Args:
asm_instr (X86Instruction): A instruction to execute.
Returns:
A int. The address of the next instruction to execute.
"""
# Update the instruction pointer.
self.ir_emulator.registers[self.ip] = asm_instr.address + asm_instr.size
# Process syscall.
if self.arch_info.instr_is_syscall(asm_instr):
raise Syscall()
# Process instruction and return next address instruction to execute.
return self.__execute(asm_instr) | [
"def",
"execute",
"(",
"self",
",",
"asm_instr",
")",
":",
"# Update the instruction pointer.",
"self",
".",
"ir_emulator",
".",
"registers",
"[",
"self",
".",
"ip",
"]",
"=",
"asm_instr",
".",
"address",
"+",
"asm_instr",
".",
"size",
"# Process syscall.",
"i... | Execute an assembler instruction.
Args:
asm_instr (X86Instruction): A instruction to execute.
Returns:
A int. The address of the next instruction to execute. | [
"Execute",
"an",
"assembler",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/emulator.py#L131-L148 | train | 198,470 |
programa-stic/barf-project | barf/analysis/gadgets/gadget.py | RawGadget.ir_instrs | def ir_instrs(self):
"""Get gadgets IR instructions.
"""
ir_instrs = []
for asm_instr in self._instrs:
ir_instrs += asm_instr.ir_instrs
return ir_instrs | python | def ir_instrs(self):
"""Get gadgets IR instructions.
"""
ir_instrs = []
for asm_instr in self._instrs:
ir_instrs += asm_instr.ir_instrs
return ir_instrs | [
"def",
"ir_instrs",
"(",
"self",
")",
":",
"ir_instrs",
"=",
"[",
"]",
"for",
"asm_instr",
"in",
"self",
".",
"_instrs",
":",
"ir_instrs",
"+=",
"asm_instr",
".",
"ir_instrs",
"return",
"ir_instrs"
] | Get gadgets IR instructions. | [
"Get",
"gadgets",
"IR",
"instructions",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/gadget.py#L72-L80 | train | 198,471 |
programa-stic/barf-project | barf/core/symbols.py | load_symbols_elf | def load_symbols_elf(filename):
""" Load the symbol tables contained in the file
"""
f = open(filename, 'rb')
elffile = ELFFile(f)
symbols = []
for section in elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
logger.warn("Symbol table {} has a sh_entsize of zero.".format(section.name))
continue
logger.info("Symbol table {} contains {} entries.".format(section.name, section.num_symbols()))
for _, symbol in enumerate(section.iter_symbols()):
if describe_symbol_shndx(symbol['st_shndx']) != "UND" and \
describe_symbol_type(symbol['st_info']['type']) == "FUNC":
symbols.append((symbol['st_value'], symbol['st_size'], symbol.name))
f.close()
symbols_by_addr = {
addr: (name, size, True) for addr, size, name in symbols
}
return symbols_by_addr | python | def load_symbols_elf(filename):
""" Load the symbol tables contained in the file
"""
f = open(filename, 'rb')
elffile = ELFFile(f)
symbols = []
for section in elffile.iter_sections():
if not isinstance(section, SymbolTableSection):
continue
if section['sh_entsize'] == 0:
logger.warn("Symbol table {} has a sh_entsize of zero.".format(section.name))
continue
logger.info("Symbol table {} contains {} entries.".format(section.name, section.num_symbols()))
for _, symbol in enumerate(section.iter_symbols()):
if describe_symbol_shndx(symbol['st_shndx']) != "UND" and \
describe_symbol_type(symbol['st_info']['type']) == "FUNC":
symbols.append((symbol['st_value'], symbol['st_size'], symbol.name))
f.close()
symbols_by_addr = {
addr: (name, size, True) for addr, size, name in symbols
}
return symbols_by_addr | [
"def",
"load_symbols_elf",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"elffile",
"=",
"ELFFile",
"(",
"f",
")",
"symbols",
"=",
"[",
"]",
"for",
"section",
"in",
"elffile",
".",
"iter_sections",
"(",
")",
":",
"if... | Load the symbol tables contained in the file | [
"Load",
"the",
"symbol",
"tables",
"contained",
"in",
"the",
"file"
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/symbols.py#L52-L83 | train | 198,472 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_no_operation | def _classify_no_operation(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify no-operation gadgets.
"""
# TODO: Flags should be taken into account
matches = []
# Check that registers didn't change their value.
regs_changed = any(regs_init[r] != regs_fini[r] for r in regs_init)
# Check that flags didn't change their value.
flags_changed = False
# Check that memory didn't change.
mem_changed = mem_fini.get_write_count() != 0
if not regs_changed and not flags_changed and not mem_changed:
matches.append({
"op": "nop",
})
return matches | python | def _classify_no_operation(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify no-operation gadgets.
"""
# TODO: Flags should be taken into account
matches = []
# Check that registers didn't change their value.
regs_changed = any(regs_init[r] != regs_fini[r] for r in regs_init)
# Check that flags didn't change their value.
flags_changed = False
# Check that memory didn't change.
mem_changed = mem_fini.get_write_count() != 0
if not regs_changed and not flags_changed and not mem_changed:
matches.append({
"op": "nop",
})
return matches | [
"def",
"_classify_no_operation",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"# TODO: Flags should be taken into account",
"matches",
"=",
"[",
"]",
"# Check that registers didn't change their value.",
... | Classify no-operation gadgets. | [
"Classify",
"no",
"-",
"operation",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L125-L146 | train | 198,473 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_move_register | def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify move-register gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- src_reg" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
for src_reg in regs_init_inv.get(dst_val, []):
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions...
if self._arch_regs_size[src_reg] != self._arch_regs_size[dst_reg]:
continue
if src_reg == dst_reg:
continue
if regs_init[dst_reg] == regs_init[src_reg]:
continue
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir]
})
return matches | python | def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify move-register gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- src_reg" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
for src_reg in regs_init_inv.get(dst_val, []):
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions...
if self._arch_regs_size[src_reg] != self._arch_regs_size[dst_reg]:
continue
if src_reg == dst_reg:
continue
if regs_init[dst_reg] == regs_init[src_reg]:
continue
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir]
})
return matches | [
"def",
"_classify_move_register",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"regs_init_inv",
"=",
"self",
".",
"_invert_dictionary",
"(",
"regs_init",
")",
"# Ch... | Classify move-register gadgets. | [
"Classify",
"move",
"-",
"register",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L157-L193 | train | 198,474 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_load_constant | def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-constant gadgets.
"""
matches = []
# Check for "dst_reg <- constant" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
# Check restrictions...
if dst_val == regs_init[dst_reg]:
continue
dst_val_ir = ReilImmediateOperand(dst_val, self._arch_regs_size[dst_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_val_ir],
"dst": [dst_reg_ir]
})
return matches | python | def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-constant gadgets.
"""
matches = []
# Check for "dst_reg <- constant" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
# Check restrictions...
if dst_val == regs_init[dst_reg]:
continue
dst_val_ir = ReilImmediateOperand(dst_val, self._arch_regs_size[dst_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_val_ir],
"dst": [dst_reg_ir]
})
return matches | [
"def",
"_classify_load_constant",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"# Check for \"dst_reg <- constant\" pattern.",
"for",
"dst_reg",
",",
"dst_val",
"in",
"... | Classify load-constant gadgets. | [
"Classify",
"load",
"-",
"constant",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L195-L218 | train | 198,475 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_arithmetic | def _classify_arithmetic(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify binary-operation gadgets.
"""
matches = []
# TODO: Review these restrictions.
op_restrictions = {
"+": lambda x, y: False,
"-": lambda x, y: x == y,
"|": lambda x, y: x == y,
"&": lambda x, y: x == y,
"^": lambda x, y: x == y,
}
# Check for "dst_reg <- src1_reg OP src2_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for src_1_reg, src_1_val in regs_init.items():
# Make sure the *src* register was read.
if src_1_reg not in read_regs:
continue
for src_2_reg, src_2_val in regs_init.items():
# Make sure the *src* register was read.
if src_2_reg not in read_regs:
continue
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_1_reg] != self._arch_regs_size[src_2_reg] or \
self._arch_regs_size[src_1_reg] != self._arch_regs_size[dst_reg]:
continue
# Avoid trivial operations.
if op_restrictions[op_name](src_1_reg, src_2_reg):
continue
size = self._arch_regs_size[src_1_reg]
if dst_val == op_fn(src_1_val, src_2_val) & (2**size - 1):
src = sorted([src_1_reg, src_2_reg])
src_ir = [
ReilRegisterOperand(src[0], self._arch_regs_size[src[0]]),
ReilRegisterOperand(src[1], self._arch_regs_size[src[1]])
]
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": src_ir,
"dst": [dst_reg_ir],
"op": op_name
})
return matches | python | def _classify_arithmetic(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify binary-operation gadgets.
"""
matches = []
# TODO: Review these restrictions.
op_restrictions = {
"+": lambda x, y: False,
"-": lambda x, y: x == y,
"|": lambda x, y: x == y,
"&": lambda x, y: x == y,
"^": lambda x, y: x == y,
}
# Check for "dst_reg <- src1_reg OP src2_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for src_1_reg, src_1_val in regs_init.items():
# Make sure the *src* register was read.
if src_1_reg not in read_regs:
continue
for src_2_reg, src_2_val in regs_init.items():
# Make sure the *src* register was read.
if src_2_reg not in read_regs:
continue
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_1_reg] != self._arch_regs_size[src_2_reg] or \
self._arch_regs_size[src_1_reg] != self._arch_regs_size[dst_reg]:
continue
# Avoid trivial operations.
if op_restrictions[op_name](src_1_reg, src_2_reg):
continue
size = self._arch_regs_size[src_1_reg]
if dst_val == op_fn(src_1_val, src_2_val) & (2**size - 1):
src = sorted([src_1_reg, src_2_reg])
src_ir = [
ReilRegisterOperand(src[0], self._arch_regs_size[src[0]]),
ReilRegisterOperand(src[1], self._arch_regs_size[src[1]])
]
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": src_ir,
"dst": [dst_reg_ir],
"op": op_name
})
return matches | [
"def",
"_classify_arithmetic",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"# TODO: Review these restrictions.",
"op_restrictions",
"=",
"{",
"\"+\"",
":",
"lambda",
... | Classify binary-operation gadgets. | [
"Classify",
"binary",
"-",
"operation",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L220-L278 | train | 198,476 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_load_memory | def _classify_load_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- mem[src_reg + offset]" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
# Look for memory addresses that contain *dst_val*.
for src_addr in mem_fini.read_inverse(dst_val, dst_size // 8):
# Look for registers whose values are used as memory
# addresses.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != self._address_size:
continue
offset = (src_addr - src_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
src_off_ir = ReilImmediateOperand(offset, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir, src_off_ir],
"dst": [dst_reg_ir]
})
# Check for "dst_reg <- mem[offset]" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for src_addr in mem_fini.read_inverse(dst_val, dst_size // 8):
src_reg_ir = ReilEmptyOperand()
src_off_ir = ReilImmediateOperand(src_addr, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir, src_off_ir],
"dst": [dst_reg_ir]
})
return matches | python | def _classify_load_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- mem[src_reg + offset]" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
# Look for memory addresses that contain *dst_val*.
for src_addr in mem_fini.read_inverse(dst_val, dst_size // 8):
# Look for registers whose values are used as memory
# addresses.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != self._address_size:
continue
offset = (src_addr - src_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
src_off_ir = ReilImmediateOperand(offset, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir, src_off_ir],
"dst": [dst_reg_ir]
})
# Check for "dst_reg <- mem[offset]" pattern.
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was written.
if dst_reg not in written_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for src_addr in mem_fini.read_inverse(dst_val, dst_size // 8):
src_reg_ir = ReilEmptyOperand()
src_off_ir = ReilImmediateOperand(src_addr, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir, src_off_ir],
"dst": [dst_reg_ir]
})
return matches | [
"def",
"_classify_load_memory",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"regs_init_inv",
"=",
"self",
".",
"_invert_dictionary",
"(",
"regs_init",
")",
"# Chec... | Classify load-memory gadgets. | [
"Classify",
"load",
"-",
"memory",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L280-L338 | train | 198,477 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_store_memory | def _classify_store_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify store-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "mem[dst_reg + offset] <- src_reg" pattern.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
src_size = self._arch_regs_size[src_reg]
for addr in mem_fini.read_inverse(src_val, src_size // 8):
for dst_reg, dst_val in regs_init.items():
# Make sure the *dst* register was written.
if dst_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[dst_reg] != self._address_size:
continue
offset = (addr - dst_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
dst_off_ir = ReilImmediateOperand(offset, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir]
})
# Check for "mem[offset] <- src_reg" pattern.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
src_size = self._arch_regs_size[src_reg]
for addr in mem_fini.read_inverse(src_val, src_size // 8):
offset = addr & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilEmptyOperand()
dst_off_ir = ReilImmediateOperand(offset, self._address_size)
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir]
})
return matches | python | def _classify_store_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify store-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "mem[dst_reg + offset] <- src_reg" pattern.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
src_size = self._arch_regs_size[src_reg]
for addr in mem_fini.read_inverse(src_val, src_size // 8):
for dst_reg, dst_val in regs_init.items():
# Make sure the *dst* register was written.
if dst_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[dst_reg] != self._address_size:
continue
offset = (addr - dst_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
dst_off_ir = ReilImmediateOperand(offset, self._arch_regs_size[dst_reg])
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir]
})
# Check for "mem[offset] <- src_reg" pattern.
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
src_size = self._arch_regs_size[src_reg]
for addr in mem_fini.read_inverse(src_val, src_size // 8):
offset = addr & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilEmptyOperand()
dst_off_ir = ReilImmediateOperand(offset, self._address_size)
matches.append({
"src": [src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir]
})
return matches | [
"def",
"_classify_store_memory",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"regs_init_inv",
"=",
"self",
".",
"_invert_dictionary",
"(",
"regs_init",
")",
"# Che... | Classify store-memory gadgets. | [
"Classify",
"store",
"-",
"memory",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L340-L396 | train | 198,478 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_arithmetic_load | def _classify_arithmetic_load(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify arithmetic-load gadgets.
"""
matches = []
# Check for "dst_reg <- dst_reg OP mem[src_reg + offset]" pattern.
for op_name, op_fn in self._binary_ops.items():
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was read and written.
if dst_reg not in written_regs or dst_reg not in read_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for addr in mem_fini.get_addresses():
success, val = mem_fini.try_read(addr, dst_size // 8)
if success and dst_val == op_fn(regs_init[dst_reg], val) & (2**dst_size - 1):
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != self._address_size:
continue
offset = (addr - src_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
src_off_ir = ReilImmediateOperand(offset, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_reg_ir, src_reg_ir, src_off_ir],
"dst": [dst_reg_ir],
"op": op_name
})
# Check for "dst_reg <- dst_reg OP mem[offset]" pattern.
for op_name, op_fn in self._binary_ops.items():
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was read and written.
if dst_reg not in written_regs or dst_reg not in read_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for addr in mem_fini.get_addresses():
success, val = mem_fini.try_read(addr, dst_size // 8)
if success and dst_val == op_fn(regs_init[dst_reg], val) & (2**dst_size - 1):
src_reg_ir = ReilEmptyOperand()
src_off_ir = ReilImmediateOperand(addr, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_reg_ir, src_reg_ir, src_off_ir],
"dst": [dst_reg_ir],
"op": op_name
})
return matches | python | def _classify_arithmetic_load(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify arithmetic-load gadgets.
"""
matches = []
# Check for "dst_reg <- dst_reg OP mem[src_reg + offset]" pattern.
for op_name, op_fn in self._binary_ops.items():
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was read and written.
if dst_reg not in written_regs or dst_reg not in read_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for addr in mem_fini.get_addresses():
success, val = mem_fini.try_read(addr, dst_size // 8)
if success and dst_val == op_fn(regs_init[dst_reg], val) & (2**dst_size - 1):
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != self._address_size:
continue
offset = (addr - src_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
src_off_ir = ReilImmediateOperand(offset, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_reg_ir, src_reg_ir, src_off_ir],
"dst": [dst_reg_ir],
"op": op_name
})
# Check for "dst_reg <- dst_reg OP mem[offset]" pattern.
for op_name, op_fn in self._binary_ops.items():
for dst_reg, dst_val in regs_fini.items():
# Make sure the *dst* register was read and written.
if dst_reg not in written_regs or dst_reg not in read_regs:
continue
dst_size = self._arch_regs_size[dst_reg]
for addr in mem_fini.get_addresses():
success, val = mem_fini.try_read(addr, dst_size // 8)
if success and dst_val == op_fn(regs_init[dst_reg], val) & (2**dst_size - 1):
src_reg_ir = ReilEmptyOperand()
src_off_ir = ReilImmediateOperand(addr, self._address_size)
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
matches.append({
"src": [dst_reg_ir, src_reg_ir, src_off_ir],
"dst": [dst_reg_ir],
"op": op_name
})
return matches | [
"def",
"_classify_arithmetic_load",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"# Check for \"dst_reg <- dst_reg OP mem[src_reg + offset]\" pattern.",
"for",
"op_name",
","... | Classify arithmetic-load gadgets. | [
"Classify",
"arithmetic",
"-",
"load",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L398-L461 | train | 198,479 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._classify_arithmetic_store | def _classify_arithmetic_store(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify arithmetic-store gadgets.
"""
matches = []
# Check for "m[dst_reg + offset] <- m[dst_reg + offset] OP src_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for size in [8, 16, 32, 64]:
for addr in mem_fini.get_addresses():
success_read_curr, val_curr = mem_fini.try_read(addr, size // 8)
success_read_prev, val_prev = mem_fini.try_read_prev(addr, size // 8)
if success_read_curr and success_read_prev:
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != size:
continue
if val_curr == op_fn(src_val, val_prev) & (2**size - 1):
# find dst + offset
for dst_reg, dst_val in regs_init.items():
# Make sure the *dst* register was written.
if dst_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[dst_reg] != self._address_size:
continue
offset = (addr - dst_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
dst_off_ir = ReilImmediateOperand(offset, self._address_size)
matches.append({
"src": [dst_reg_ir, dst_off_ir, src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir],
"op": op_name
})
# Check for "m[offset] <- m[offset] OP src_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for size in [8, 16, 32, 64]:
for addr in mem_fini.get_addresses():
success_read_curr, val_curr = mem_fini.try_read(addr, size // 8)
success_read_prev, val_prev = mem_fini.try_read_prev(addr, size // 8)
if success_read_curr and success_read_prev:
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != size:
continue
if val_curr == op_fn(src_val, val_prev) & (2**size - 1):
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilEmptyOperand()
dst_off_ir = ReilImmediateOperand(addr, self._address_size)
matches.append({
"src": [dst_reg_ir, dst_off_ir, src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir],
"op": op_name
})
return matches | python | def _classify_arithmetic_store(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify arithmetic-store gadgets.
"""
matches = []
# Check for "m[dst_reg + offset] <- m[dst_reg + offset] OP src_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for size in [8, 16, 32, 64]:
for addr in mem_fini.get_addresses():
success_read_curr, val_curr = mem_fini.try_read(addr, size // 8)
success_read_prev, val_prev = mem_fini.try_read_prev(addr, size // 8)
if success_read_curr and success_read_prev:
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != size:
continue
if val_curr == op_fn(src_val, val_prev) & (2**size - 1):
# find dst + offset
for dst_reg, dst_val in regs_init.items():
# Make sure the *dst* register was written.
if dst_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[dst_reg] != self._address_size:
continue
offset = (addr - dst_val) & (2**self._address_size - 1)
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilRegisterOperand(dst_reg, self._arch_regs_size[dst_reg])
dst_off_ir = ReilImmediateOperand(offset, self._address_size)
matches.append({
"src": [dst_reg_ir, dst_off_ir, src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir],
"op": op_name
})
# Check for "m[offset] <- m[offset] OP src_reg" pattern.
for op_name, op_fn in self._binary_ops.items():
for size in [8, 16, 32, 64]:
for addr in mem_fini.get_addresses():
success_read_curr, val_curr = mem_fini.try_read(addr, size // 8)
success_read_prev, val_prev = mem_fini.try_read_prev(addr, size // 8)
if success_read_curr and success_read_prev:
for src_reg, src_val in regs_init.items():
# Make sure the *src* register was read.
if src_reg not in read_regs:
continue
# Check restrictions.
if self._arch_regs_size[src_reg] != size:
continue
if val_curr == op_fn(src_val, val_prev) & (2**size - 1):
src_reg_ir = ReilRegisterOperand(src_reg, self._arch_regs_size[src_reg])
dst_reg_ir = ReilEmptyOperand()
dst_off_ir = ReilImmediateOperand(addr, self._address_size)
matches.append({
"src": [dst_reg_ir, dst_off_ir, src_reg_ir],
"dst": [dst_reg_ir, dst_off_ir],
"op": op_name
})
return matches | [
"def",
"_classify_arithmetic_store",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
",",
"mem_fini",
",",
"written_regs",
",",
"read_regs",
")",
":",
"matches",
"=",
"[",
"]",
"# Check for \"m[dst_reg + offset] <- m[dst_reg + offset] OP src_reg\" pattern.",
"for",
"op_n... | Classify arithmetic-store gadgets. | [
"Classify",
"arithmetic",
"-",
"store",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L463-L536 | train | 198,480 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._init_regs_random | def _init_regs_random(self):
"""Initialize register with random values.
"""
# Generate random values and make sure they are all different.
values = set()
while len(values) != len(self._arch_regs_parent):
values.add(random.randint(0, 2**self._arch_info.operand_size - 1))
values = list(values)
# Assign random values to registers.
regs = {}
for idx, reg in enumerate(self._arch_regs_parent):
regs[reg] = values[idx] & (2**self._arch_regs_size[reg] - 1)
return regs | python | def _init_regs_random(self):
"""Initialize register with random values.
"""
# Generate random values and make sure they are all different.
values = set()
while len(values) != len(self._arch_regs_parent):
values.add(random.randint(0, 2**self._arch_info.operand_size - 1))
values = list(values)
# Assign random values to registers.
regs = {}
for idx, reg in enumerate(self._arch_regs_parent):
regs[reg] = values[idx] & (2**self._arch_regs_size[reg] - 1)
return regs | [
"def",
"_init_regs_random",
"(",
"self",
")",
":",
"# Generate random values and make sure they are all different.",
"values",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"self",
".",
"_arch_regs_parent",
")",
":",
"values",
".",
... | Initialize register with random values. | [
"Initialize",
"register",
"with",
"random",
"values",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L665-L682 | train | 198,481 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._compute_mod_regs | def _compute_mod_regs(self, regs_init, regs_fini):
"""Compute modified registers.
"""
assert regs_init.keys() == regs_fini.keys()
modified_regs = []
for reg in regs_init:
if regs_init[reg] != regs_fini[reg]:
modified_regs.append(reg)
return modified_regs | python | def _compute_mod_regs(self, regs_init, regs_fini):
"""Compute modified registers.
"""
assert regs_init.keys() == regs_fini.keys()
modified_regs = []
for reg in regs_init:
if regs_init[reg] != regs_fini[reg]:
modified_regs.append(reg)
return modified_regs | [
"def",
"_compute_mod_regs",
"(",
"self",
",",
"regs_init",
",",
"regs_fini",
")",
":",
"assert",
"regs_init",
".",
"keys",
"(",
")",
"==",
"regs_fini",
".",
"keys",
"(",
")",
"modified_regs",
"=",
"[",
"]",
"for",
"reg",
"in",
"regs_init",
":",
"if",
"... | Compute modified registers. | [
"Compute",
"modified",
"registers",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L684-L695 | train | 198,482 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._invert_dictionary | def _invert_dictionary(self, d):
"""Invert a dictionary.
"""
inv_dict = {}
for k, v in d.items():
inv_dict[v] = inv_dict.get(v, [])
inv_dict[v] += [k]
return inv_dict | python | def _invert_dictionary(self, d):
"""Invert a dictionary.
"""
inv_dict = {}
for k, v in d.items():
inv_dict[v] = inv_dict.get(v, [])
inv_dict[v] += [k]
return inv_dict | [
"def",
"_invert_dictionary",
"(",
"self",
",",
"d",
")",
":",
"inv_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"inv_dict",
"[",
"v",
"]",
"=",
"inv_dict",
".",
"get",
"(",
"v",
",",
"[",
"]",
")",
"inv_... | Invert a dictionary. | [
"Invert",
"a",
"dictionary",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L697-L706 | train | 198,483 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._print_memory | def _print_memory(self, memory):
"""Print memory.
"""
for addr, value in memory.items():
print(" 0x%08x : 0x%08x (%d)" % (addr, value, value)) | python | def _print_memory(self, memory):
"""Print memory.
"""
for addr, value in memory.items():
print(" 0x%08x : 0x%08x (%d)" % (addr, value, value)) | [
"def",
"_print_memory",
"(",
"self",
",",
"memory",
")",
":",
"for",
"addr",
",",
"value",
"in",
"memory",
".",
"items",
"(",
")",
":",
"print",
"(",
"\" 0x%08x : 0x%08x (%d)\"",
"%",
"(",
"addr",
",",
"value",
",",
"value",
")",
")"
] | Print memory. | [
"Print",
"memory",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L708-L712 | train | 198,484 |
programa-stic/barf-project | barf/analysis/gadgets/classifier.py | GadgetClassifier._print_registers | def _print_registers(self, registers):
"""Print registers.
"""
for reg, value in registers.items():
print(" %s : 0x%08x (%d)" % (reg, value, value)) | python | def _print_registers(self, registers):
"""Print registers.
"""
for reg, value in registers.items():
print(" %s : 0x%08x (%d)" % (reg, value, value)) | [
"def",
"_print_registers",
"(",
"self",
",",
"registers",
")",
":",
"for",
"reg",
",",
"value",
"in",
"registers",
".",
"items",
"(",
")",
":",
"print",
"(",
"\" %s : 0x%08x (%d)\"",
"%",
"(",
"reg",
",",
"value",
",",
"value",
")",
")"
] | Print registers. | [
"Print",
"registers",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/classifier.py#L714-L718 | train | 198,485 |
programa-stic/barf-project | barf/analysis/graphs/basicblock.py | bb_get_instr_max_width | def bb_get_instr_max_width(basic_block):
"""Get maximum instruction mnemonic width
"""
asm_mnemonic_max_width = 0
for instr in basic_block:
if len(instr.mnemonic) > asm_mnemonic_max_width:
asm_mnemonic_max_width = len(instr.mnemonic)
return asm_mnemonic_max_width | python | def bb_get_instr_max_width(basic_block):
"""Get maximum instruction mnemonic width
"""
asm_mnemonic_max_width = 0
for instr in basic_block:
if len(instr.mnemonic) > asm_mnemonic_max_width:
asm_mnemonic_max_width = len(instr.mnemonic)
return asm_mnemonic_max_width | [
"def",
"bb_get_instr_max_width",
"(",
"basic_block",
")",
":",
"asm_mnemonic_max_width",
"=",
"0",
"for",
"instr",
"in",
"basic_block",
":",
"if",
"len",
"(",
"instr",
".",
"mnemonic",
")",
">",
"asm_mnemonic_max_width",
":",
"asm_mnemonic_max_width",
"=",
"len",
... | Get maximum instruction mnemonic width | [
"Get",
"maximum",
"instruction",
"mnemonic",
"width"
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/basicblock.py#L30-L39 | train | 198,486 |
programa-stic/barf-project | barf/analysis/graphs/basicblock.py | BasicBlock.end_address | def end_address(self):
"""Get basic block end address.
"""
if self._instrs is []:
return None
return self._instrs[-1].address + self._instrs[-1].size - 1 | python | def end_address(self):
"""Get basic block end address.
"""
if self._instrs is []:
return None
return self._instrs[-1].address + self._instrs[-1].size - 1 | [
"def",
"end_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instrs",
"is",
"[",
"]",
":",
"return",
"None",
"return",
"self",
".",
"_instrs",
"[",
"-",
"1",
"]",
".",
"address",
"+",
"self",
".",
"_instrs",
"[",
"-",
"1",
"]",
".",
"size",
... | Get basic block end address. | [
"Get",
"basic",
"block",
"end",
"address",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/basicblock.py#L146-L152 | train | 198,487 |
programa-stic/barf-project | barf/analysis/graphs/basicblock.py | BasicBlock.size | def size(self):
"""Get basic block size.
"""
if self._instrs is []:
return None
return sum([instr.size for instr in self._instrs]) | python | def size(self):
"""Get basic block size.
"""
if self._instrs is []:
return None
return sum([instr.size for instr in self._instrs]) | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instrs",
"is",
"[",
"]",
":",
"return",
"None",
"return",
"sum",
"(",
"[",
"instr",
".",
"size",
"for",
"instr",
"in",
"self",
".",
"_instrs",
"]",
")"
] | Get basic block size. | [
"Get",
"basic",
"block",
"size",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/basicblock.py#L155-L161 | train | 198,488 |
programa-stic/barf-project | barf/analysis/graphs/basicblock.py | BasicBlock.branches | def branches(self):
"""Get basic block branches.
"""
branches = []
if self._taken_branch:
branches += [(self._taken_branch, 'taken')]
if self._not_taken_branch:
branches += [(self._not_taken_branch, 'not-taken')]
if self._direct_branch:
branches += [(self._direct_branch, 'direct')]
return branches | python | def branches(self):
"""Get basic block branches.
"""
branches = []
if self._taken_branch:
branches += [(self._taken_branch, 'taken')]
if self._not_taken_branch:
branches += [(self._not_taken_branch, 'not-taken')]
if self._direct_branch:
branches += [(self._direct_branch, 'direct')]
return branches | [
"def",
"branches",
"(",
"self",
")",
":",
"branches",
"=",
"[",
"]",
"if",
"self",
".",
"_taken_branch",
":",
"branches",
"+=",
"[",
"(",
"self",
".",
"_taken_branch",
",",
"'taken'",
")",
"]",
"if",
"self",
".",
"_not_taken_branch",
":",
"branches",
"... | Get basic block branches. | [
"Get",
"basic",
"block",
"branches",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/basicblock.py#L200-L214 | train | 198,489 |
programa-stic/barf-project | barf/arch/arm/translator.py | ArmTranslationBuilder._compute_register_list | def _compute_register_list(self, operand):
"""Return operand register list.
"""
ret = []
for reg_range in operand.reg_list:
if len(reg_range) == 1:
ret.append(ReilRegisterOperand(reg_range[0].name, reg_range[0].size))
else:
reg_num = int(reg_range[0].name[1:]) # Assuming the register is named with one letter + number
reg_end = int(reg_range[1].name[1:])
if reg_num > reg_end:
raise NotImplementedError("Instruction Not Implemented: Invalid register range.")
while reg_num <= reg_end:
ret.append(ReilRegisterOperand(reg_range[0].name[0] + str(reg_num), reg_range[0].size))
reg_num = reg_num + 1
return ret | python | def _compute_register_list(self, operand):
"""Return operand register list.
"""
ret = []
for reg_range in operand.reg_list:
if len(reg_range) == 1:
ret.append(ReilRegisterOperand(reg_range[0].name, reg_range[0].size))
else:
reg_num = int(reg_range[0].name[1:]) # Assuming the register is named with one letter + number
reg_end = int(reg_range[1].name[1:])
if reg_num > reg_end:
raise NotImplementedError("Instruction Not Implemented: Invalid register range.")
while reg_num <= reg_end:
ret.append(ReilRegisterOperand(reg_range[0].name[0] + str(reg_num), reg_range[0].size))
reg_num = reg_num + 1
return ret | [
"def",
"_compute_register_list",
"(",
"self",
",",
"operand",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"reg_range",
"in",
"operand",
".",
"reg_list",
":",
"if",
"len",
"(",
"reg_range",
")",
"==",
"1",
":",
"ret",
".",
"append",
"(",
"ReilRegisterOperand",... | Return operand register list. | [
"Return",
"operand",
"register",
"list",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/arm/translator.py#L208-L225 | train | 198,490 |
programa-stic/barf-project | barf/arch/arm/translator.py | ArmTranslator.translate | def translate(self, instruction):
"""Return IR representation of an instruction.
"""
try:
trans_instrs = self.__translate(instruction)
except NotImplementedError:
unkn_instr = self._builder.gen_unkn()
unkn_instr.address = instruction.address << 8 | (0x0 & 0xff)
trans_instrs = [unkn_instr]
self._log_not_supported_instruction(instruction)
except Exception:
self._log_translation_exception(instruction)
raise
return trans_instrs | python | def translate(self, instruction):
"""Return IR representation of an instruction.
"""
try:
trans_instrs = self.__translate(instruction)
except NotImplementedError:
unkn_instr = self._builder.gen_unkn()
unkn_instr.address = instruction.address << 8 | (0x0 & 0xff)
trans_instrs = [unkn_instr]
self._log_not_supported_instruction(instruction)
except Exception:
self._log_translation_exception(instruction)
raise
return trans_instrs | [
"def",
"translate",
"(",
"self",
",",
"instruction",
")",
":",
"try",
":",
"trans_instrs",
"=",
"self",
".",
"__translate",
"(",
"instruction",
")",
"except",
"NotImplementedError",
":",
"unkn_instr",
"=",
"self",
".",
"_builder",
".",
"gen_unkn",
"(",
")",
... | Return IR representation of an instruction. | [
"Return",
"IR",
"representation",
"of",
"an",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/arm/translator.py#L359-L375 | train | 198,491 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemory.read | def read(self, address, size):
"""Read arbitrary size content from memory.
"""
value = 0x0
for i in range(0, size):
value |= self._read_byte(address + i) << (i * 8)
return value | python | def read(self, address, size):
"""Read arbitrary size content from memory.
"""
value = 0x0
for i in range(0, size):
value |= self._read_byte(address + i) << (i * 8)
return value | [
"def",
"read",
"(",
"self",
",",
"address",
",",
"size",
")",
":",
"value",
"=",
"0x0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"value",
"|=",
"self",
".",
"_read_byte",
"(",
"address",
"+",
"i",
")",
"<<",
"(",
"i",
"*",
... | Read arbitrary size content from memory. | [
"Read",
"arbitrary",
"size",
"content",
"from",
"memory",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L59-L67 | train | 198,492 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemory._read_byte | def _read_byte(self, address):
"""Read a byte from memory.
"""
# Initialize memory location with a random value.
if address not in self._memory:
self._memory[address] = random.randint(0x00, 0xff)
return self._memory[address] | python | def _read_byte(self, address):
"""Read a byte from memory.
"""
# Initialize memory location with a random value.
if address not in self._memory:
self._memory[address] = random.randint(0x00, 0xff)
return self._memory[address] | [
"def",
"_read_byte",
"(",
"self",
",",
"address",
")",
":",
"# Initialize memory location with a random value.",
"if",
"address",
"not",
"in",
"self",
".",
"_memory",
":",
"self",
".",
"_memory",
"[",
"address",
"]",
"=",
"random",
".",
"randint",
"(",
"0x00",... | Read a byte from memory. | [
"Read",
"a",
"byte",
"from",
"memory",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L69-L76 | train | 198,493 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemory.write | def write(self, address, size, value):
"""Write arbitrary size content to memory.
"""
for i in range(0, size):
self.__write_byte(address + i, (value >> (i * 8)) & 0xff) | python | def write(self, address, size, value):
"""Write arbitrary size content to memory.
"""
for i in range(0, size):
self.__write_byte(address + i, (value >> (i * 8)) & 0xff) | [
"def",
"write",
"(",
"self",
",",
"address",
",",
"size",
",",
"value",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"self",
".",
"__write_byte",
"(",
"address",
"+",
"i",
",",
"(",
"value",
">>",
"(",
"i",
"*",
"8",
... | Write arbitrary size content to memory. | [
"Write",
"arbitrary",
"size",
"content",
"to",
"memory",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L80-L84 | train | 198,494 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemoryEx.read_inverse | def read_inverse(self, value, size):
"""Return a list of memory addresses that contain the specified
value.
"""
addr_candidates = [addr for addr, val in self._memory.items() if val == (value & 0xff)]
addr_matches = []
for addr in addr_candidates:
match = True
for i in range(0, size):
byte_curr = (value >> (i * 8)) & 0xff
try:
match = self._memory[addr + i] == byte_curr
except KeyError:
match = False
if not match:
break
if match:
addr_matches += [addr]
return addr_matches | python | def read_inverse(self, value, size):
"""Return a list of memory addresses that contain the specified
value.
"""
addr_candidates = [addr for addr, val in self._memory.items() if val == (value & 0xff)]
addr_matches = []
for addr in addr_candidates:
match = True
for i in range(0, size):
byte_curr = (value >> (i * 8)) & 0xff
try:
match = self._memory[addr + i] == byte_curr
except KeyError:
match = False
if not match:
break
if match:
addr_matches += [addr]
return addr_matches | [
"def",
"read_inverse",
"(",
"self",
",",
"value",
",",
"size",
")",
":",
"addr_candidates",
"=",
"[",
"addr",
"for",
"addr",
",",
"val",
"in",
"self",
".",
"_memory",
".",
"items",
"(",
")",
"if",
"val",
"==",
"(",
"value",
"&",
"0xff",
")",
"]",
... | Return a list of memory addresses that contain the specified
value. | [
"Return",
"a",
"list",
"of",
"memory",
"addresses",
"that",
"contain",
"the",
"specified",
"value",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L123-L147 | train | 198,495 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemoryEx.try_read | def try_read(self, address, size):
"""Try to read memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content).
"""
value = 0x0
for i in range(0, size):
addr = address + i
if addr in self._memory:
value |= self._read_byte(addr) << (i * 8)
else:
return False, None
return True, value | python | def try_read(self, address, size):
"""Try to read memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content).
"""
value = 0x0
for i in range(0, size):
addr = address + i
if addr in self._memory:
value |= self._read_byte(addr) << (i * 8)
else:
return False, None
return True, value | [
"def",
"try_read",
"(",
"self",
",",
"address",
",",
"size",
")",
":",
"value",
"=",
"0x0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"addr",
"=",
"address",
"+",
"i",
"if",
"addr",
"in",
"self",
".",
"_memory",
":",
"value",
... | Try to read memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content). | [
"Try",
"to",
"read",
"memory",
"content",
"at",
"specified",
"address",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L149-L166 | train | 198,496 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemoryEx.try_read_prev | def try_read_prev(self, address, size):
"""Try to read previous memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content).
"""
value = 0x0
for i in range(0, size):
addr = address + i
if addr in self.__memory_prev:
_, val_byte = self.__try_read_byte_prev(addr)
value |= val_byte << (i * 8)
else:
return False, None
return True, value | python | def try_read_prev(self, address, size):
"""Try to read previous memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content).
"""
value = 0x0
for i in range(0, size):
addr = address + i
if addr in self.__memory_prev:
_, val_byte = self.__try_read_byte_prev(addr)
value |= val_byte << (i * 8)
else:
return False, None
return True, value | [
"def",
"try_read_prev",
"(",
"self",
",",
"address",
",",
"size",
")",
":",
"value",
"=",
"0x0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"addr",
"=",
"address",
"+",
"i",
"if",
"addr",
"in",
"self",
".",
"__memory_prev",
":",
... | Try to read previous memory content at specified address.
If any location was not written before, it returns a tuple
(False, None). Otherwise, it returns (True, memory content). | [
"Try",
"to",
"read",
"previous",
"memory",
"content",
"at",
"specified",
"address",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L168-L186 | train | 198,497 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemoryEx.__try_read_byte_prev | def __try_read_byte_prev(self, address):
"""Read previous value for memory location.
Return a tuple (True, Byte) in case of successful read,
(False, None) otherwise.
"""
# Initialize memory location with a random value
if address not in self.__memory_prev:
return False, None
return True, self.__memory_prev[address] | python | def __try_read_byte_prev(self, address):
"""Read previous value for memory location.
Return a tuple (True, Byte) in case of successful read,
(False, None) otherwise.
"""
# Initialize memory location with a random value
if address not in self.__memory_prev:
return False, None
return True, self.__memory_prev[address] | [
"def",
"__try_read_byte_prev",
"(",
"self",
",",
"address",
")",
":",
"# Initialize memory location with a random value",
"if",
"address",
"not",
"in",
"self",
".",
"__memory_prev",
":",
"return",
"False",
",",
"None",
"return",
"True",
",",
"self",
".",
"__memory... | Read previous value for memory location.
Return a tuple (True, Byte) in case of successful read,
(False, None) otherwise. | [
"Read",
"previous",
"value",
"for",
"memory",
"location",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L188-L199 | train | 198,498 |
programa-stic/barf-project | barf/core/reil/emulator/memory.py | ReilMemoryEx.__write_byte | def __write_byte(self, address, value):
"""Write byte in memory.
"""
# Save previous address content.
if address in self._memory:
self.__memory_prev[address] = self._memory[address]
self._memory[address] = value & 0xff | python | def __write_byte(self, address, value):
"""Write byte in memory.
"""
# Save previous address content.
if address in self._memory:
self.__memory_prev[address] = self._memory[address]
self._memory[address] = value & 0xff | [
"def",
"__write_byte",
"(",
"self",
",",
"address",
",",
"value",
")",
":",
"# Save previous address content.",
"if",
"address",
"in",
"self",
".",
"_memory",
":",
"self",
".",
"__memory_prev",
"[",
"address",
"]",
"=",
"self",
".",
"_memory",
"[",
"address"... | Write byte in memory. | [
"Write",
"byte",
"in",
"memory",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/memory.py#L211-L218 | train | 198,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.