text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, path): """ Creates a new Registry key. @type path: str @param path: Registry key path. @rtype: L{RegistryKey} @return: The newly created Registry key. """
path = self._sanitize_path(path) hive, subpath = self._parse_path(path) handle = win32.RegCreateKey(hive, subpath) return RegistryKey(path, handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subkeys(self, path): """ Returns a list of subkeys for the given Registry key. @type path: str @param path: Registry key path. @rtype: list(str) @return: List of subkey names. """
result = list() hive, subpath = self._parse_path(path) with win32.RegOpenKey(hive, subpath) as handle: index = 0 while 1: name = win32.RegEnumKey(handle, index) if name is None: break result.append(name) index += 1 return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate(self, path): """ Returns a recursive iterator on the specified key and its subkeys. @type path: str @param path: Registry key path. @rtype: iterator @return: Recursive iterator that returns Registry key paths. @raise KeyError: The specified path does not exist. """
if path.endswith('\\'): path = path[:-1] if not self.has_key(path): raise KeyError(path) stack = collections.deque() stack.appendleft(path) return self.__iterate(stack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterkeys(self): """ Returns an iterator that crawls the entire Windows Registry. """
stack = collections.deque(self._hives) stack.reverse() return self.__iterate(stack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_command_line(argv): """ parses the arguments. removes our arguments from the command line """
setup = {} for handler in ACCEPTED_ARG_HANDLERS: setup[handler.arg_name] = handler.default_val setup['file'] = '' setup['qt-support'] = '' i = 0 del argv[0] while i < len(argv): handler = ARGV_REP_TO_HANDLER.get(argv[i]) if handler is not None: handler.handle_argv(argv, i, setup) elif argv[i].startswith('--qt-support'): # The --qt-support is special because we want to keep backward compatibility: # Previously, just passing '--qt-support' meant that we should use the auto-discovery mode # whereas now, if --qt-support is passed, it should be passed as --qt-support=<mode>, where # mode can be one of 'auto', 'none', 'pyqt5', 'pyqt4', 'pyside'. if argv[i] == '--qt-support': setup['qt-support'] = 'auto' elif argv[i].startswith('--qt-support='): qt_support = argv[i][len('--qt-support='):] valid_modes = ('none', 'auto', 'pyqt5', 'pyqt4', 'pyside') if qt_support not in valid_modes: raise ValueError("qt-support mode invalid: " + qt_support) if qt_support == 'none': # On none, actually set an empty string to evaluate to False. setup['qt-support'] = '' else: setup['qt-support'] = qt_support else: raise ValueError("Unexpected definition for qt-support flag: " + argv[i]) del argv[i] elif argv[i] == '--file': # --file is special because it's the last one (so, no handler for it). del argv[i] setup['file'] = argv[i] i = len(argv) # pop out, file is our last argument elif argv[i] == '--DEBUG': from pydevd import set_debug del argv[i] set_debug(setup) else: raise ValueError("Unexpected option: " + argv[i]) return setup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVariable(dbg, thread_id, frame_id, scope, attrs): """ returns the value of a variable :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME BY_ID means we'll traverse the list of all objects alive to get the object. :attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :note: when BY_ID is used, the frame_id is considered the id of the object to find and not the frame (as we don't care about the frame in this case). """
if scope == 'BY_ID': if thread_id != get_current_thread_id(threading.currentThread()): raise VariableError("getVariable: must execute on same thread") try: import gc objects = gc.get_objects() except: pass # Not all python variants have it. else: frame_id = int(frame_id) for var in objects: if id(var) == frame_id: if attrs is not None: attrList = attrs.split('\t') for k in attrList: _type, _typeName, resolver = get_type(var) var = resolver.resolve(var, k) return var # If it didn't return previously, we coudn't find it by id (i.e.: alrceady garbage collected). sys.stderr.write('Unable to find object with id: %s\n' % (frame_id,)) return None frame = dbg.find_frame(thread_id, frame_id) if frame is None: return {} if attrs is not None: attrList = attrs.split('\t') else: attrList = [] for attr in attrList: attr.replace("@_@TAB_CHAR@_@", '\t') if scope == 'EXPRESSION': for count in xrange(len(attrList)): if count == 0: # An Expression can be in any scope (globals/locals), therefore it needs to evaluated as an expression var = evaluate_expression(dbg, frame, attrList[count], False) else: _type, _typeName, resolver = get_type(var) var = resolver.resolve(var, attrList[count]) else: if scope == "GLOBAL": var = frame.f_globals del attrList[0] # globals are special, and they get a single dummy unused attribute else: # in a frame access both locals and globals as Python does var = {} var.update(frame.f_globals) var.update(frame.f_locals) for k in attrList: _type, _typeName, resolver = get_type(var) var = resolver.resolve(var, k) return var
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs): """ Resolve compound variable in debugger scopes by its name and attributes :param thread_id: id of the variable's thread :param frame_id: id of the variable's frame :param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME :param attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields """
var = getVariable(dbg, thread_id, frame_id, scope, attrs) try: _type, _typeName, resolver = get_type(var) return _typeName, resolver.get_dictionary(var) except: pydev_log.exception('Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s.', thread_id, frame_id, scope, attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_var_object(var, attrs): """ Resolve variable's attribute :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a value of resolved variable's attribute """
if attrs is not None: attr_list = attrs.split('\t') else: attr_list = [] for k in attr_list: type, _typeName, resolver = get_type(var) var = resolver.resolve(var, k) return var
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_compound_var_object_fields(var, attrs): """ Resolve compound variable by its object and attributes :param var: an object of variable :param attrs: a sequence of variable's attributes separated by \t (i.e.: obj\tattr1\tattr2) :return: a dictionary of variables's fields """
attr_list = attrs.split('\t') for k in attr_list: type, _typeName, resolver = get_type(var) var = resolver.resolve(var, k) try: type, _typeName, resolver = get_type(var) return resolver.get_dictionary(var) except: pydev_log.exception()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_operation(dbg, thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name): """ We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var. code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed. operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint) """
expressionValue = getVariable(dbg, thread_id, frame_id, scope, attrs) try: namespace = {'__name__': '<custom_operation>'} if style == "EXECFILE": namespace['__file__'] = code_or_file execfile(code_or_file, namespace, namespace) else: # style == EXEC namespace['__file__'] = '<customOperationCode>' Exec(code_or_file, namespace, namespace) return str(namespace[operation_fn_name](expressionValue)) except: pydev_log.exception()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def evaluate_expression(dbg, frame, expression, is_exec): '''returns the result of the evaluated expression @param is_exec: determines if we should do an exec or an eval ''' if frame is None: return # Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329 # (Names not resolved in generator expression in method) # See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html updated_globals = {} updated_globals.update(frame.f_globals) updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals try: expression = str(expression.replace('@LINE@', '\n')) if is_exec: try: # try to make it an eval (if it is an eval we can print it, otherwise we'll exec it and # it will have whatever the user actually did) compiled = compile(expression, '<string>', 'eval') except: Exec(expression, updated_globals, frame.f_locals) pydevd_save_locals.save_locals(frame) else: result = eval(compiled, updated_globals, frame.f_locals) if result is not None: # Only print if it's not None (as python does) sys.stdout.write('%s\n' % (result,)) return else: return eval_in_context(expression, updated_globals, frame.f_locals) finally: # Should not be kept alive if an exception happens and this frame is kept in the stack. del updated_globals del frame
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def change_attr_expression(frame, attr, expression, dbg, value=SENTINEL_VALUE): '''Changes some attribute in a given frame. ''' if frame is None: return try: expression = expression.replace('@LINE@', '\n') if dbg.plugin and value is SENTINEL_VALUE: result = dbg.plugin.change_variable(frame, attr, expression) if result: return result if attr[:7] == "Globals": attr = attr[8:] if attr in frame.f_globals: if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) frame.f_globals[attr] = value return frame.f_globals[attr] else: if '.' not in attr: # i.e.: if we have a '.', we're changing some attribute of a local var. if pydevd_save_locals.is_save_locals_available(): if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) frame.f_locals[attr] = value pydevd_save_locals.save_locals(frame) return frame.f_locals[attr] # default way (only works for changing it in the topmost frame) if value is SENTINEL_VALUE: value = eval(expression, frame.f_globals, frame.f_locals) result = value Exec('%s=%s' % (attr, expression), frame.f_globals, frame.f_locals) return result except Exception: pydev_log.exception()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_condition(self, condition = True): """ Sets a new condition callback for the breakpoint. @see: L{__init__} @type condition: function @param condition: (Optional) Condition callback function. """
if condition is None: self.__condition = True else: self.__condition = condition
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_condition(self, event): """ Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise. """
condition = self.get_condition() if condition is True: # shortcut for unconditional breakpoints return True if callable(condition): try: return bool( condition(event) ) except Exception: e = sys.exc_info()[1] msg = ("Breakpoint condition callback %r" " raised an exception: %s") msg = msg % (condition, traceback.format_exc(e)) warnings.warn(msg, BreakpointCallbackWarning) return False return bool( condition )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_action(self, event): """ Executes the breakpoint action callback, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. """
action = self.get_action() if action is not None: try: return bool( action(event) ) except Exception: e = sys.exc_info()[1] msg = ("Breakpoint action callback %r" " raised an exception: %s") msg = msg % (action, traceback.format_exc(e)) warnings.warn(msg, BreakpointCallbackWarning) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hit(self, event): """ Notify a breakpoint that it's been hit. This triggers the corresponding state transition and sets the C{breakpoint} property of the given L{Event} object. @see: L{disable}, L{enable}, L{one_shot}, L{running} @type event: L{Event} @param event: Debug event to handle (depends on the breakpoint type). @raise AssertionError: Disabled breakpoints can't be hit. """
aProcess = event.get_process() aThread = event.get_thread() state = self.get_state() event.breakpoint = self if state == self.ENABLED: self.running(aProcess, aThread) elif state == self.RUNNING: self.enable(aProcess, aThread) elif state == self.ONESHOT: self.disable(aProcess, aThread) elif state == self.DISABLED: # this should not happen msg = "Hit a disabled breakpoint at address %s" msg = msg % HexDump.address( self.get_address() ) warnings.warn(msg, BreakpointWarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __set_bp(self, aProcess): """ Writes a breakpoint instruction at the target address. @type aProcess: L{Process} @param aProcess: Process object. """
address = self.get_address() self.__previousValue = aProcess.read(address, len(self.bpInstruction)) if self.__previousValue == self.bpInstruction: msg = "Possible overlapping code breakpoints at %s" msg = msg % HexDump.address(address) warnings.warn(msg, BreakpointWarning) aProcess.write(address, self.bpInstruction)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __set_bp(self, aProcess): """ Sets the target pages as guard pages. @type aProcess: L{Process} @param aProcess: Process object. """
lpAddress = self.get_address() dwSize = self.get_size() flNewProtect = aProcess.mquery(lpAddress).Protect flNewProtect = flNewProtect | win32.PAGE_GUARD aProcess.mprotect(lpAddress, dwSize, flNewProtect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __clear_bp(self, aProcess): """ Restores the original permissions of the target pages. @type aProcess: L{Process} @param aProcess: Process object. """
lpAddress = self.get_address() flNewProtect = aProcess.mquery(lpAddress).Protect flNewProtect = flNewProtect & (0xFFFFFFFF ^ win32.PAGE_GUARD) # DWORD aProcess.mprotect(lpAddress, self.get_size(), flNewProtect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __clear_bp(self, aThread): """ Clears this breakpoint from the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """
if self.__slot is not None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) DebugRegister.clear_bp(ctx, self.__slot) aThread.set_context(ctx) self.__slot = None finally: aThread.resume()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __set_bp(self, aThread): """ Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """
if self.__slot is None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) self.__slot = DebugRegister.find_slot(ctx) if self.__slot is None: msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread.get_tid() raise RuntimeError(msg) DebugRegister.set_bp(ctx, self.__slot, self.get_address(), self.__trigger, self.__watch) aThread.set_context(ctx) finally: aThread.resume()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __postCallAction_hwbp(self, event): """ Handles hardware breakpoint events on return from the function. @type event: L{ExceptionEvent} @param event: Single step event. """
# Remove the one shot hardware breakpoint # at the return address location in the stack. tid = event.get_tid() address = event.breakpoint.get_address() event.debug.erase_hardware_breakpoint(tid, address) # Call the "post" callback. try: self.__postCallAction(event) # Forget the parameters. finally: self.__pop_params(tid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __postCallAction_codebp(self, event): """ Handles code breakpoint events on return from the function. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. """
# If the breakpoint was accidentally hit by another thread, # pass it to the debugger instead of calling the "post" callback. # # XXX FIXME: # I suppose this check will fail under some weird conditions... # tid = event.get_tid() if tid not in self.__paramStack: return True # Remove the code breakpoint at the return address. pid = event.get_pid() address = event.breakpoint.get_address() event.debug.dont_break_at(pid, address) # Call the "post" callback. try: self.__postCallAction(event) # Forget the parameters. finally: self.__pop_params(tid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __postCallAction(self, event): """ Calls the "post" callback. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. """
aThread = event.get_thread() retval = self._get_return_value(aThread) self.__callHandler(self.__postCB, event, retval)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __callHandler(self, callback, event, *params): """ Calls a "pre" or "post" handler, if set. @type callback: function @param callback: Callback function to call. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. @type params: tuple @param params: Parameters for the callback function. """
if callback is not None: event.hook = self callback(event, *params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __push_params(self, tid, params): """ Remembers the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. @param params: Tuple of arguments. """
stack = self.__paramStack.get( tid, [] ) stack.append(params) self.__paramStack[tid] = stack
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __pop_params(self, tid): """ Forgets the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. """
stack = self.__paramStack[tid] stack.pop() if not stack: del self.__paramStack[tid]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_params(self, tid): """ Returns the parameters found in the stack when the hooked function was last called by this thread. @type tid: int @param tid: Thread global ID. @return: Tuple of arguments. """
try: params = self.get_params_stack(tid)[-1] except IndexError: msg = "Hooked function called from thread %d already returned" raise IndexError(msg % tid) return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_params_stack(self, tid): """ Returns the parameters found in the stack each time the hooked function was called by this thread and hasn't returned yet. @type tid: int @param tid: Thread global ID. @return: List of argument tuples. """
try: stack = self.__paramStack[tid] except KeyError: msg = "Hooked function was not called from thread %d" raise KeyError(msg % tid) return stack
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook(self, debug, pid, address): """ Installs the function hook at a given process and address. @see: L{unhook} @warning: Do not call from an function hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. @type address: int @param address: Function address. """
return debug.break_at(pid, address, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook(self, debug, pid): """ Installs the API hook on a given process and module. @warning: Do not call from an API hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. """
label = "%s!%s" % (self.__modName, self.__procName) try: hook = self.__hook[pid] except KeyError: try: aProcess = debug.system.get_process(pid) except KeyError: aProcess = Process(pid) hook = Hook(self.__preCB, self.__postCB, self.__paramCount, self.__signature, aProcess.get_arch() ) self.__hook[pid] = hook hook.hook(debug, pid, label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unhook(self, debug, pid): """ Removes the API hook from the given process and module. @warning: Do not call from an API hook callback. @type debug: L{Debug} @param debug: Debug object. @type pid: int @param pid: Process ID. """
try: hook = self.__hook[pid] except KeyError: return label = "%s!%s" % (self.__modName, self.__procName) hook.unhook(debug, pid, label) del self.__hook[pid]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, bw): """ Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed. """
try: self.__ranges.remove(bw) except KeyError: if not bw.oneshot: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_last_match(self, address, size): """ Removes the last buffer from the watch object to match the given address and size. @type address: int @param address: Memory address of buffer to stop watching. @type size: int @param size: Size in bytes of buffer to stop watching. @rtype: int @return: Number of matching elements found. Only the last one to be added is actually deleted upon calling this method. This counter allows you to know if there are more matching elements and how many. """
count = 0 start = address end = address + size - 1 matched = None for item in self.__ranges: if item.match(start) and item.match(end): matched = item count += 1 self.__ranges.remove(matched) return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_code_breakpoint(self, dwProcessId, address, condition = True, action = None): """ Creates a disabled code breakpoint at the given address. @see: L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint}, L{erase_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of the code instruction to break at. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{CodeBreakpoint} @return: The code breakpoint object. """
process = self.system.get_process(dwProcessId) bp = CodeBreakpoint(address, condition, action) key = (dwProcessId, bp.get_address()) if key in self.__codeBP: msg = "Already exists (PID %d) : %r" raise KeyError(msg % (dwProcessId, self.__codeBP[key])) self.__codeBP[key] = bp return bp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_page_breakpoint(self, dwProcessId, address, pages = 1, condition = True, action = None): """ Creates a disabled page breakpoint at the given address. @see: L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint}, L{erase_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of the first page to watch. @type pages: int @param pages: Number of pages to watch. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{PageBreakpoint} @return: The page breakpoint object. """
process = self.system.get_process(dwProcessId) bp = PageBreakpoint(address, pages, condition, action) begin = bp.get_address() end = begin + bp.get_size() address = begin pageSize = MemoryAddresses.pageSize while address < end: key = (dwProcessId, address) if key in self.__pageBP: msg = "Already exists (PID %d) : %r" msg = msg % (dwProcessId, self.__pageBP[key]) raise KeyError(msg) address = address + pageSize address = begin while address < end: key = (dwProcessId, address) self.__pageBP[key] = bp address = address + pageSize return bp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_hardware_breakpoint(self, dwThreadId, address, triggerFlag = BP_BREAK_ON_ACCESS, sizeFlag = BP_WATCH_DWORD, condition = True, action = None): """ Creates a disabled hardware breakpoint at the given address. @see: L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint}, L{erase_hardware_breakpoint} @note: Hardware breakpoints do not seem to work properly on VirtualBox. See U{http://www.virtualbox.org/ticket/477}. @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address to watch. @type triggerFlag: int @param triggerFlag: Trigger of breakpoint. Must be one of the following: - L{BP_BREAK_ON_EXECUTION} Break on code execution. - L{BP_BREAK_ON_WRITE} Break on memory read or write. - L{BP_BREAK_ON_ACCESS} Break on memory write. @type sizeFlag: int @param sizeFlag: Size of breakpoint. Must be one of the following: - L{BP_WATCH_BYTE} One (1) byte in size. - L{BP_WATCH_WORD} Two (2) bytes in size. - L{BP_WATCH_DWORD} Four (4) bytes in size. - L{BP_WATCH_QWORD} Eight (8) bytes in size. @type condition: function @param condition: (Optional) Condition callback function. The callback signature is:: def condition_callback(event): return True # returns True or False Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @type action: function @param action: (Optional) Action callback function. If specified, the event is handled by this callback instead of being dispatched normally. The callback signature is:: def action_callback(event): pass # no return value Where B{event} is an L{Event} object, and the return value is a boolean (C{True} to dispatch the event, C{False} otherwise). @rtype: L{HardwareBreakpoint} @return: The hardware breakpoint object. """
thread = self.system.get_thread(dwThreadId) bp = HardwareBreakpoint(address, triggerFlag, sizeFlag, condition, action) begin = bp.get_address() end = begin + bp.get_size() if dwThreadId in self.__hardwareBP: bpSet = self.__hardwareBP[dwThreadId] for oldbp in bpSet: old_begin = oldbp.get_address() old_end = old_begin + oldbp.get_size() if MemoryAddresses.do_ranges_intersect(begin, end, old_begin, old_end): msg = "Already exists (TID %d) : %r" % (dwThreadId, oldbp) raise KeyError(msg) else: bpSet = set() self.__hardwareBP[dwThreadId] = bpSet bpSet.add(bp) return bp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_hardware_breakpoint(self, dwThreadId, address): """ Checks if a hardware breakpoint is defined at the given address. @see: L{define_hardware_breakpoint}, L{get_hardware_breakpoint}, L{erase_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. @rtype: bool @return: C{True} if the breakpoint is defined, C{False} otherwise. """
if dwThreadId in self.__hardwareBP: bpSet = self.__hardwareBP[dwThreadId] for bp in bpSet: if bp.get_address() == address: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_page_breakpoint(self, dwProcessId, address): """ Returns the internally used breakpoint object, for the page breakpoint defined at the given address. @warning: It's usually best to call the L{Debug} methods instead of accessing the breakpoint objects directly. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint}, L{erase_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address where the breakpoint is defined. @rtype: L{PageBreakpoint} @return: The page breakpoint object. """
key = (dwProcessId, address) if key not in self.__pageBP: msg = "No breakpoint at process %d, address %s" address = HexDump.addresS(address) raise KeyError(msg % (dwProcessId, address)) return self.__pageBP[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_code_breakpoint(self, dwProcessId, address): """ Enables the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint} L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_page_breakpoint(self, dwProcessId, address): """ Enables the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint} L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_hardware_breakpoint(self, dwThreadId, address): """ Enables the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} L{erase_hardware_breakpoint}, @note: Do not set hardware breakpoints while processing the system breakpoint event. @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """
t = self.system.get_thread(dwThreadId) bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(None, t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_one_shot_code_breakpoint(self, dwProcessId, address): """ Enables the code breakpoint at the given address for only one shot. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{disable_code_breakpoint} L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_one_shot_page_breakpoint(self, dwProcessId, address): """ Enables the page breakpoint at the given address for only one shot. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{disable_page_breakpoint} L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_one_shot_hardware_breakpoint(self, dwThreadId, address): """ Enables the hardware breakpoint at the given address for only one shot. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{disable_hardware_breakpoint} L{erase_hardware_breakpoint}, @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """
t = self.system.get_thread(dwThreadId) bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.one_shot(None, t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_code_breakpoint(self, dwProcessId, address): """ Disables the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint} L{enable_one_shot_code_breakpoint}, L{erase_code_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_code_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.disable(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_page_breakpoint(self, dwProcessId, address): """ Disables the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint} L{enable_one_shot_page_breakpoint}, L{erase_page_breakpoint}, @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
p = self.system.get_process(dwProcessId) bp = self.get_page_breakpoint(dwProcessId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.disable(p, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_hardware_breakpoint(self, dwThreadId, address): """ Disables the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint} L{enable_one_shot_hardware_breakpoint}, L{erase_hardware_breakpoint}, @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """
t = self.system.get_thread(dwThreadId) p = t.get_process() bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp(dwThreadId, bp) bp.disable(p, t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_code_breakpoint(self, dwProcessId, address): """ Erases the code breakpoint at the given address. @see: L{define_code_breakpoint}, L{has_code_breakpoint}, L{get_code_breakpoint}, L{enable_code_breakpoint}, L{enable_one_shot_code_breakpoint}, L{disable_code_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
bp = self.get_code_breakpoint(dwProcessId, address) if not bp.is_disabled(): self.disable_code_breakpoint(dwProcessId, address) del self.__codeBP[ (dwProcessId, address) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_page_breakpoint(self, dwProcessId, address): """ Erases the page breakpoint at the given address. @see: L{define_page_breakpoint}, L{has_page_breakpoint}, L{get_page_breakpoint}, L{enable_page_breakpoint}, L{enable_one_shot_page_breakpoint}, L{disable_page_breakpoint} @type dwProcessId: int @param dwProcessId: Process global ID. @type address: int @param address: Memory address of breakpoint. """
bp = self.get_page_breakpoint(dwProcessId, address) begin = bp.get_address() end = begin + bp.get_size() if not bp.is_disabled(): self.disable_page_breakpoint(dwProcessId, address) address = begin pageSize = MemoryAddresses.pageSize while address < end: del self.__pageBP[ (dwProcessId, address) ] address = address + pageSize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_hardware_breakpoint(self, dwThreadId, address): """ Erases the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} @type dwThreadId: int @param dwThreadId: Thread global ID. @type address: int @param address: Memory address of breakpoint. """
bp = self.get_hardware_breakpoint(dwThreadId, address) if not bp.is_disabled(): self.disable_hardware_breakpoint(dwThreadId, address) bpSet = self.__hardwareBP[dwThreadId] bpSet.remove(bp) if not bpSet: del self.__hardwareBP[dwThreadId]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_breakpoints(self): """ Returns all breakpoint objects as a list of tuples. Each tuple contains: - Process global ID to which the breakpoint applies. - Thread global ID to which the breakpoint applies, or C{None}. - The L{Breakpoint} object itself. @note: If you're only interested in a specific breakpoint type, or in breakpoints for a specific process or thread, it's probably faster to call one of the following methods: - L{get_all_code_breakpoints} - L{get_all_page_breakpoints} - L{get_all_hardware_breakpoints} - L{get_process_code_breakpoints} - L{get_process_page_breakpoints} - L{get_process_hardware_breakpoints} - L{get_thread_hardware_breakpoints} @rtype: list of tuple( pid, tid, bp ) @return: List of all breakpoints. """
bplist = list() # Get the code breakpoints. for (pid, bp) in self.get_all_code_breakpoints(): bplist.append( (pid, None, bp) ) # Get the page breakpoints. for (pid, bp) in self.get_all_page_breakpoints(): bplist.append( (pid, None, bp) ) # Get the hardware breakpoints. for (tid, bp) in self.get_all_hardware_breakpoints(): pid = self.system.get_thread(tid).get_pid() bplist.append( (pid, tid, bp) ) # Return the list of breakpoints. return bplist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_process_breakpoints(self, dwProcessId): """ Returns all breakpoint objects for the given process as a list of tuples. Each tuple contains: - Process global ID to which the breakpoint applies. - Thread global ID to which the breakpoint applies, or C{None}. - The L{Breakpoint} object itself. @note: If you're only interested in a specific breakpoint type, or in breakpoints for a specific process or thread, it's probably faster to call one of the following methods: - L{get_all_code_breakpoints} - L{get_all_page_breakpoints} - L{get_all_hardware_breakpoints} - L{get_process_code_breakpoints} - L{get_process_page_breakpoints} - L{get_process_hardware_breakpoints} - L{get_thread_hardware_breakpoints} @type dwProcessId: int @param dwProcessId: Process global ID. @rtype: list of tuple( pid, tid, bp ) @return: List of all breakpoints for the given process. """
bplist = list() # Get the code breakpoints. for bp in self.get_process_code_breakpoints(dwProcessId): bplist.append( (dwProcessId, None, bp) ) # Get the page breakpoints. for bp in self.get_process_page_breakpoints(dwProcessId): bplist.append( (dwProcessId, None, bp) ) # Get the hardware breakpoints. for (tid, bp) in self.get_process_hardware_breakpoints(dwProcessId): pid = self.system.get_thread(tid).get_pid() bplist.append( (dwProcessId, tid, bp) ) # Return the list of breakpoints. return bplist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_all_breakpoints(self): """ Enables all disabled breakpoints in all processes. @see: enable_code_breakpoint, enable_page_breakpoint, enable_hardware_breakpoint """
# disable code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): if bp.is_disabled(): self.enable_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): if bp.is_disabled(): self.enable_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): if bp.is_disabled(): self.enable_hardware_breakpoint(tid, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_one_shot_all_breakpoints(self): """ Enables for one shot all disabled breakpoints in all processes. @see: enable_one_shot_code_breakpoint, enable_one_shot_page_breakpoint, enable_one_shot_hardware_breakpoint """
# disable code breakpoints for one shot for (pid, bp) in self.get_all_code_breakpoints(): if bp.is_disabled(): self.enable_one_shot_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for one shot for (pid, bp) in self.get_all_page_breakpoints(): if bp.is_disabled(): self.enable_one_shot_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for one shot for (tid, bp) in self.get_all_hardware_breakpoints(): if bp.is_disabled(): self.enable_one_shot_hardware_breakpoint(tid, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_all_breakpoints(self): """ Disables all breakpoints in all processes. @see: disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint """
# disable code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): self.disable_code_breakpoint(pid, bp.get_address()) # disable page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): self.disable_page_breakpoint(pid, bp.get_address()) # disable hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): self.disable_hardware_breakpoint(tid, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_all_breakpoints(self): """ Erases all breakpoints in all processes. @see: erase_code_breakpoint, erase_page_breakpoint, erase_hardware_breakpoint """
# This should be faster but let's not trust the GC so much :P # self.disable_all_breakpoints() # self.__codeBP = dict() # self.__pageBP = dict() # self.__hardwareBP = dict() # self.__runningBP = dict() # self.__hook_objects = dict() ## # erase hooks ## for (pid, address, hook) in self.get_all_hooks(): ## self.dont_hook_function(pid, address) # erase code breakpoints for (pid, bp) in self.get_all_code_breakpoints(): self.erase_code_breakpoint(pid, bp.get_address()) # erase page breakpoints for (pid, bp) in self.get_all_page_breakpoints(): self.erase_page_breakpoint(pid, bp.get_address()) # erase hardware breakpoints for (tid, bp) in self.get_all_hardware_breakpoints(): self.erase_hardware_breakpoint(tid, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_process_breakpoints(self, dwProcessId): """ Enables all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """
# enable code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_code_breakpoint(dwProcessId, bp.get_address()) # enable page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_page_breakpoint(dwProcessId, bp.get_address()) # enable hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): if bp.is_disabled(): self.enable_hardware_breakpoint(dwThreadId, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_one_shot_process_breakpoints(self, dwProcessId): """ Enables for one shot all disabled breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """
# enable code breakpoints for one shot for bp in self.get_process_code_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_one_shot_code_breakpoint(dwProcessId, bp.get_address()) # enable page breakpoints for one shot for bp in self.get_process_page_breakpoints(dwProcessId): if bp.is_disabled(): self.enable_one_shot_page_breakpoint(dwProcessId, bp.get_address()) # enable hardware breakpoints for one shot if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): if bp.is_disabled(): self.enable_one_shot_hardware_breakpoint(dwThreadId, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_process_breakpoints(self, dwProcessId): """ Disables all breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """
# disable code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): self.disable_code_breakpoint(dwProcessId, bp.get_address()) # disable page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): self.disable_page_breakpoint(dwProcessId, bp.get_address()) # disable hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): self.disable_hardware_breakpoint(dwThreadId, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_process_breakpoints(self, dwProcessId): """ Erases all breakpoints for the given process. @type dwProcessId: int @param dwProcessId: Process global ID. """
# disable breakpoints first # if an error occurs, no breakpoint is erased self.disable_process_breakpoints(dwProcessId) ## # erase hooks ## for address, hook in self.get_process_hooks(dwProcessId): ## self.dont_hook_function(dwProcessId, address) # erase code breakpoints for bp in self.get_process_code_breakpoints(dwProcessId): self.erase_code_breakpoint(dwProcessId, bp.get_address()) # erase page breakpoints for bp in self.get_process_page_breakpoints(dwProcessId): self.erase_page_breakpoint(dwProcessId, bp.get_address()) # erase hardware breakpoints if self.system.has_process(dwProcessId): aProcess = self.system.get_process(dwProcessId) else: aProcess = Process(dwProcessId) aProcess.scan_threads() for aThread in aProcess.iter_threads(): dwThreadId = aThread.get_tid() for bp in self.get_thread_hardware_breakpoints(dwThreadId): self.erase_hardware_breakpoint(dwThreadId, bp.get_address())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _notify_guard_page(self, event): """ Notify breakpoints of a guard page exception event. @type event: L{ExceptionEvent} @param event: Guard page exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
address = event.get_fault_address() pid = event.get_pid() bCallHandler = True # Align address to page boundary. mask = ~(MemoryAddresses.pageSize - 1) address = address & mask # Do we have an active page breakpoint there? key = (pid, address) if key in self.__pageBP: bp = self.__pageBP[key] if bp.is_enabled() or bp.is_one_shot(): # Breakpoint is ours. event.continueStatus = win32.DBG_CONTINUE ## event.continueStatus = win32.DBG_EXCEPTION_HANDLED # Hit the breakpoint. bp.hit(event) # Remember breakpoints in RUNNING state. if bp.is_running(): tid = event.get_tid() self.__add_running_bp(tid, bp) # Evaluate the breakpoint condition. bCondition = bp.eval_condition(event) # If the breakpoint is automatic, run the action. # If not, notify the user. if bCondition and bp.is_automatic(): bp.run_action(event) bCallHandler = False else: bCallHandler = bCondition # If we don't have a breakpoint here pass the exception to the debugee. # This is a normally occurring exception so we shouldn't swallow it. else: event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED return bCallHandler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _notify_breakpoint(self, event): """ Notify breakpoints of a breakpoint exception event. @type event: L{ExceptionEvent} @param event: Breakpoint exception event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """
address = event.get_exception_address() pid = event.get_pid() bCallHandler = True # Do we have an active code breakpoint there? key = (pid, address) if key in self.__codeBP: bp = self.__codeBP[key] if not bp.is_disabled(): # Change the program counter (PC) to the exception address. # This accounts for the change in PC caused by # executing the breakpoint instruction, no matter # the size of it. aThread = event.get_thread() aThread.set_pc(address) # Swallow the exception. event.continueStatus = win32.DBG_CONTINUE # Hit the breakpoint. bp.hit(event) # Remember breakpoints in RUNNING state. if bp.is_running(): tid = event.get_tid() self.__add_running_bp(tid, bp) # Evaluate the breakpoint condition. bCondition = bp.eval_condition(event) # If the breakpoint is automatic, run the action. # If not, notify the user. if bCondition and bp.is_automatic(): bCallHandler = bp.run_action(event) else: bCallHandler = bCondition # Handle the system breakpoint. # TODO: examine the stack trace to figure out if it's really a # system breakpoint or an antidebug trick. The caller should be # inside ntdll if it's legit. elif event.get_process().is_system_defined_breakpoint(address): event.continueStatus = win32.DBG_CONTINUE # In hostile mode, if we don't have a breakpoint here pass the # exception to the debugee. In normal mode assume all breakpoint # exceptions are to be handled by the debugger. else: if self.in_hostile_mode(): event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED else: event.continueStatus = win32.DBG_CONTINUE return bCallHandler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __set_deferred_breakpoints(self, event): """ Used internally. Sets all deferred breakpoints for a DLL when it's loaded. @type event: L{LoadDLLEvent} @param event: Load DLL event. """
pid = event.get_pid() try: deferred = self.__deferredBP[pid] except KeyError: return aProcess = event.get_process() for (label, (action, oneshot)) in deferred.items(): try: address = aProcess.resolve_label(label) except Exception: continue del deferred[label] try: self.__set_break(pid, address, action, oneshot) except Exception: msg = "Can't set deferred breakpoint %s at process ID %d" msg = msg % (label, pid) warnings.warn(msg, BreakpointWarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stalk_at(self, pid, address, action = None): """ Sets a one shot code breakpoint at the given process and address. If instead of an address you pass a label, the breakpoint may be deferred until the DLL it points to is loaded. @see: L{break_at}, L{dont_stalk_at} @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type action: function @param action: (Optional) Action callback function. See L{define_code_breakpoint} for more details. @rtype: bool @return: C{True} if the breakpoint was set immediately, or C{False} if it was deferred. """
bp = self.__set_break(pid, address, action, oneshot = True) return bp is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def break_at(self, pid, address, action = None): """ Sets a code breakpoint at the given process and address. If instead of an address you pass a label, the breakpoint may be deferred until the DLL it points to is loaded. @see: L{stalk_at}, L{dont_break_at} @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type action: function @param action: (Optional) Action callback function. See L{define_code_breakpoint} for more details. @rtype: bool @return: C{True} if the breakpoint was set immediately, or C{False} if it was deferred. """
bp = self.__set_break(pid, address, action, oneshot = False) return bp is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook_function(self, pid, address, preCB = None, postCB = None, paramCount = None, signature = None): """ Sets a function hook at the given address. If instead of an address you pass a label, the hook may be deferred until the DLL it points to is loaded. @type pid: int @param pid: Process global ID. @type address: int or str @param address: Memory address of code instruction to break at. It can be an integer value for the actual address or a string with a label to be resolved. @type preCB: function @param preCB: (Optional) Callback triggered on function entry. The signature for the callback should be something like this:: def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags): # return address ra = params[0] szFilename = event.get_process().peek_string(lpFilename) Note that all pointer types are treated like void pointers, so your callback won't get the string or structure pointed to by it, but the remote memory address instead. This is so to prevent the ctypes library from being "too helpful" and trying to dereference the pointer. To get the actual data being pointed to, use one of the L{Process.read} methods. @type postCB: function @param postCB: (Optional) Callback triggered on function exit. The signature for the callback should be something like this:: def post_LoadLibraryEx(event, return_value): @type paramCount: int @param paramCount: (Optional) Number of parameters for the C{preCB} callback, not counting the return address. Parameters are read from the stack and assumed to be DWORDs in 32 bits and QWORDs in 64. This is a faster way to pull stack parameters in 32 bits, but in 64 bits (or with some odd APIs in 32 bits) it won't be useful, since not all arguments to the hooked function will be of the same size. For a more reliable and cross-platform way of hooking use the C{signature} argument instead. @type signature: tuple @param signature: (Optional) Tuple of C{ctypes} data types that constitute the hooked function signature. When the function is called, this will be used to parse the arguments from the stack. Overrides the C{paramCount} argument. @rtype: bool @return: C{True} if the hook was set immediately, or C{False} if it was deferred. """
try: aProcess = self.system.get_process(pid) except KeyError: aProcess = Process(pid) arch = aProcess.get_arch() hookObj = Hook(preCB, postCB, paramCount, signature, arch) bp = self.break_at(pid, address, hookObj) return bp is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_variable(self, tid, address, size, action = None): """ Sets a hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable to watch. The only supported sizes are: byte (1), word (2), dword (4) and qword (8). @type action: function @param action: (Optional) Action callback function. See L{define_hardware_breakpoint} for more details. """
bp = self.__set_variable_watch(tid, address, size, action) if not bp.is_enabled(): self.enable_hardware_breakpoint(tid, address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stalk_variable(self, tid, address, size, action = None): """ Sets a one-shot hardware breakpoint at the given thread, address and size. @see: L{dont_watch_variable} @type tid: int @param tid: Thread global ID. @type address: int @param address: Memory address of variable to watch. @type size: int @param size: Size of variable to watch. The only supported sizes are: byte (1), word (2), dword (4) and qword (8). @type action: function @param action: (Optional) Action callback function. See L{define_hardware_breakpoint} for more details. """
bp = self.__set_variable_watch(tid, address, size, action) if not bp.is_one_shot(): self.enable_one_shot_hardware_breakpoint(tid, address)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_buffer(self, pid, address, size, action = None): """ Sets a page breakpoint and notifies when the given buffer is accessed. @see: L{dont_watch_variable} @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to watch. @type size: int @param size: Size in bytes of buffer to watch. @type action: function @param action: (Optional) Action callback function. See L{define_page_breakpoint} for more details. @rtype: L{BufferWatch} @return: Buffer watch identifier. """
self.__set_buffer_watch(pid, address, size, action, False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stalk_buffer(self, pid, address, size, action = None): """ Sets a one-shot page breakpoint and notifies when the given buffer is accessed. @see: L{dont_watch_variable} @type pid: int @param pid: Process global ID. @type address: int @param address: Memory address of buffer to watch. @type size: int @param size: Size in bytes of buffer to watch. @type action: function @param action: (Optional) Action callback function. See L{define_page_breakpoint} for more details. @rtype: L{BufferWatch} @return: Buffer watch identifier. """
self.__set_buffer_watch(pid, address, size, action, True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_tracing(self, tid): """ Start tracing mode in the given thread. @type tid: int @param tid: Global ID of thread to start tracing. """
if not self.is_tracing(tid): thread = self.system.get_thread(tid) self.__start_tracing(thread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_tracing(self, tid): """ Stop tracing mode in the given thread. @type tid: int @param tid: Global ID of thread to stop tracing. """
if self.is_tracing(tid): thread = self.system.get_thread(tid) self.__stop_tracing(thread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_tracing_process(self, pid): """ Start tracing mode for all threads in the given process. @type pid: int @param pid: Global ID of process to start tracing. """
for thread in self.system.get_process(pid).iter_threads(): self.__start_tracing(thread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_tracing_process(self, pid): """ Stop tracing mode for all threads in the given process. @type pid: int @param pid: Global ID of process to stop tracing. """
for thread in self.system.get_process(pid).iter_threads(): self.__stop_tracing(thread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def break_on_error(self, pid, errorCode): """ Sets or clears the system breakpoint for a given Win32 error code. Use L{Process.is_system_defined_breakpoint} to tell if a breakpoint exception was caused by a system breakpoint or by the application itself (for example because of a failed assertion in the code). @note: This functionality is only available since Windows Server 2003. In 2003 it only breaks on error values set externally to the kernel32.dll library, but this was fixed in Windows Vista. @warn: This method will fail if the debug symbols for ntdll (kernel32 in Windows 2003) are not present. For more information see: L{System.fix_symbol_store_path}. @see: U{http://www.nynaeve.net/?p=147} @type pid: int @param pid: Process ID. @type errorCode: int @param errorCode: Win32 error code to stop on. Set to C{0} or C{ERROR_SUCCESS} to clear the breakpoint instead. @raise NotImplementedError: The functionality is not supported in this system. @raise WindowsError: An error occurred while processing this request. """
aProcess = self.system.get_process(pid) address = aProcess.get_break_on_error_ptr() if not address: raise NotImplementedError( "The functionality is not supported in this system.") aProcess.write_dword(address, errorCode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_exported_function(self, pid, modName, procName): """ Resolves the exported DLL function for the given process. @type pid: int @param pid: Process global ID. @type modName: str @param modName: Name of the module that exports the function. @type procName: str @param procName: Name of the exported function to resolve. @rtype: int, None @return: On success, the address of the exported function. On failure, returns C{None}. """
aProcess = self.system.get_process(pid) aModule = aProcess.get_module_by_name(modName) if not aModule: aProcess.scan_modules() aModule = aProcess.get_module_by_name(modName) if aModule: address = aModule.resolve(procName) return address return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process_net_command(self, py_db, cmd_id, seq, text): '''Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command ''' meaning = ID_TO_MEANING[str(cmd_id)] # print('Handling %s (%s)' % (meaning, text)) method_name = meaning.lower() on_command = getattr(self, method_name.lower(), None) if on_command is None: # I have no idea what this is all about cmd = py_db.cmd_factory.make_error_message(seq, "unexpected command " + str(cmd_id)) py_db.writer.add_command(cmd) return py_db._main_lock.acquire() try: cmd = on_command(py_db, cmd_id, seq, text) if cmd is not None: py_db.writer.add_command(cmd) except: if traceback is not None and sys is not None and pydev_log_exception is not None: pydev_log_exception() stream = StringIO() traceback.print_exc(file=stream) cmd = py_db.cmd_factory.make_error_message( seq, "Unexpected exception in process_net_command.\nInitial params: %s. Exception: %s" % ( ((cmd_id, seq, text), stream.getvalue()) ) ) if cmd is not None: py_db.writer.add_command(cmd) finally: py_db._main_lock.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_pattern(self): """Compiles self.PATTERN into self.pattern. Subclass may override if it doesn't want to use self.{pattern,PATTERN} in .match(). """
if self.PATTERN is not None: PC = PatternCompiler() self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN, with_tree=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_filename(self, filename): """Set the filename, and a logger derived from it. The main refactoring tool should call this. """
self.filename = filename self.logger = logging.getLogger(filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, node): """Returns match for a given parse tree node. Should return a true or false object (not necessarily a bool). It may return a non-empty dict of matching sub-nodes as returned by a matching pattern. Subclass may override. """
results = {"node": node} return self.pattern.match(node, results) and results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_name(self, template=u"xxx_todo_changeme"): """Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers. """
name = template while name in self.used_names: name = template + unicode(self.numbers.next()) self.used_names.add(name) return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cannot_convert(self, node, reason=None): """Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. """
lineno = node.get_lineno() for_output = node.clone() for_output.prefix = u"" msg = "Line %d: could not convert: %s" self.log_message(msg % (lineno, for_output)) if reason: self.log_message(reason)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def warning(self, node, reason): """Used for warning the user about possible uncertainty in the translation. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. """
lineno = node.get_lineno() self.log_message("Line %d: %s" % (lineno, reason))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from. """
self.used_names = tree.used_names self.set_filename(filename) self.numbers = itertools.count(1) self.first_log = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_quit(self, arg): """ quit - close the debugging session q - close the debugging session """
if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.confirm_quit: count = self.debug.get_debugee_count() if count > 0: if count == 1: msg = "There's a program still running." else: msg = "There are %s programs still running." % count if not self.ask_user(msg): return False self.debuggerExit = True return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_continue(self, arg): """ continue - continue execution g - continue execution go - continue execution """
if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.debug.get_debugee_count() > 0: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_gh(self, arg): """ gh - go with exception handled """
if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.lastEvent: self.lastEvent.continueStatus = win32.DBG_EXCEPTION_HANDLED return self.do_go(arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_gn(self, arg): """ gn - go with exception not handled """
if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") if self.lastEvent: self.lastEvent.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED return self.do_go(arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_processlist(self, arg): """ pl - show the processes being debugged processlist - show the processes being debugged """
if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") system = self.debug.system pid_list = self.debug.get_debugee_pids() if pid_list: print("Process ID File name") for pid in pid_list: if pid == 0: filename = "System Idle Process" elif pid == 4: filename = "System" else: filename = system.get_process(pid).get_filename() filename = PathOperations.pathname_to_filename(filename) print("%-12d %s" % (pid, filename))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_threadlist(self, arg): """ tl - show the threads being debugged threadlist - show the threads being debugged """
if arg: raise CmdError("too many arguments") if self.cmdprefix: process = self.get_process_from_prefix() for thread in process.iter_threads(): tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name)) else: system = self.debug.system pid_list = self.debug.get_debugee_pids() if pid_list: print("Thread ID Thread name") for pid in pid_list: process = system.get_process(pid) for thread in process.iter_threads(): tid = thread.get_tid() name = thread.get_name() print("%-12d %s" % (tid, name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_step(self, arg): """ p - step on the current assembly instruction next - step on the current assembly instruction step - step on the current assembly instruction """
if self.cmdprefix: raise CmdError("prefix not allowed") if self.lastEvent is None: raise CmdError("no current process set") if arg: # XXX this check is to be removed raise CmdError("too many arguments") pid = self.lastEvent.get_pid() thread = self.lastEvent.get_thread() pc = thread.get_pc() code = thread.disassemble(pc, 16)[0] size = code[1] opcode = code[2].lower() if ' ' in opcode: opcode = opcode[ : opcode.find(' ') ] if opcode in self.jump_instructions or opcode in ('int', 'ret', 'retn'): return self.do_trace(arg) address = pc + size ## print(hex(pc), hex(address), size # XXX DEBUG self.debug.stalk_at(pid, address) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_trace(self, arg): """ t - trace at the current assembly instruction trace - trace at the current assembly instruction """
if arg: # XXX this check is to be removed raise CmdError("too many arguments") if self.lastEvent is None: raise CmdError("no current thread set") self.lastEvent.get_thread().set_tf() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer(token): """ Convert numeric strings into integers. @type token: str @param token: String to parse. @rtype: int @return: Parsed integer value. """
token = token.strip() neg = False if token.startswith(compat.b('-')): token = token[1:] neg = True if token.startswith(compat.b('0x')): result = int(token, 16) # hexadecimal elif token.startswith(compat.b('0b')): result = int(token[2:], 2) # binary elif token.startswith(compat.b('0o')): result = int(token, 8) # octal else: try: result = int(token) # decimal except ValueError: result = int(token, 16) # hexadecimal (no "0x" prefix) if neg: result = -result return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexadecimal(token): """ Convert a strip of hexadecimal numbers into binary data. @type token: str @param token: String to parse. @rtype: str @return: Parsed string value. """
token = ''.join([ c for c in token if c.isalnum() ]) if len(token) % 2 != 0: raise ValueError("Missing characters in hex data") data = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] d = int(x, 16) s = struct.pack('<B', d) data += s return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pattern(token): """ Convert an hexadecimal search pattern into a POSIX regular expression. For example, the following pattern:: "B8 0? ?0 ?? ??" Would match the following data:: "B8 0D F0 AD BA" # mov eax, 0xBAADF00D @type token: str @param token: String to parse. @rtype: str @return: Parsed string value. """
token = ''.join([ c for c in token if c == '?' or c.isalnum() ]) if len(token) % 2 != 0: raise ValueError("Missing characters in hex data") regexp = '' for i in compat.xrange(0, len(token), 2): x = token[i:i+2] if x == '??': regexp += '.' elif x[0] == '?': f = '\\x%%.1x%s' % x[1] x = ''.join([ f % c for c in compat.xrange(0, 0x10) ]) regexp = '%s[%s]' % (regexp, x) elif x[1] == '?': f = '\\x%s%%.1x' % x[0] x = ''.join([ f % c for c in compat.xrange(0, 0x10) ]) regexp = '%s[%s]' % (regexp, x) else: regexp = '%s\\x%s' % (regexp, x) return regexp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer_list_file(cls, filename): """ Read a list of integers from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - integers can be specified as: - decimal numbers ("100" is 100) - hexadecimal numbers ("0x100" is 256) - binary numbers ("0b100" is 4) - octal numbers ("0100" is 64) @type filename: str @param filename: Name of the file to read. @rtype: list( int ) @return: List of integers read from the file. """
count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: try: value = cls.integer(line) except ValueError: e = sys.exc_info()[1] msg = "Error in line %d of %s: %s" msg = msg % (count, filename, str(e)) raise ValueError(msg) result.append(value) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_list_file(cls, filename): """ Read a list of string values from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - strings cannot span over a single line @type filename: str @param filename: Name of the file to read. @rtype: list @return: List of integers and strings read from the file. """
count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: result.append(line) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mixed_list_file(cls, filename): """ Read a list of mixed values from a file. The file format is: - # anywhere in the line begins a comment - leading and trailing spaces are ignored - empty lines are ignored - strings cannot span over a single line - integers can be specified as: - decimal numbers ("100" is 100) - hexadecimal numbers ("0x100" is 256) - binary numbers ("0b100" is 4) - octal numbers ("0100" is 64) @type filename: str @param filename: Name of the file to read. @rtype: list @return: List of integers and strings read from the file. """
count = 0 result = list() fd = open(filename, 'r') for line in fd: count = count + 1 if '#' in line: line = line[ : line.find('#') ] line = line.strip() if line: try: value = cls.integer(line) except ValueError: value = line result.append(value) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer_list_file(cls, filename, values, bits = None): """ Write a list of integers to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.integer_list_file} for a description of the file format. @type filename: str @param filename: Name of the file to write. @type values: list( int ) @param values: List of integers to write to the file. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexOutput.integer_size} """
fd = open(filename, 'w') for integer in values: print >> fd, cls.integer(integer, bits) fd.close()