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 string_list_file(cls, filename, values): """ Write a list of strings to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.string_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 strings to write to the file. """
fd = open(filename, 'w') for string in values: print >> fd, string fd.close()
<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, values, bits): """ Write a list of mixed values to a file. If a file of the same name exists, it's contents are replaced. See L{HexInput.mixed_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 mixed values 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 original in values: try: parsed = cls.integer(original, bits) except TypeError: parsed = repr(original) print >> fd, parsed fd.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printable(data): """ Replace unprintable characters with dots. @type data: str @param data: Binary data. @rtype: str @return: Printable text. """
result = '' for c in data: if 32 < ord(c) < 128: result += c else: 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 hexa_word(data, separator = ' '): """ Convert binary data to a string of hexadecimal WORDs. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each WORD. @rtype: str @return: Hexadecimal representation. """
if len(data) & 1 != 0: data += '\0' return separator.join( [ '%.4x' % struct.unpack('<H', data[i:i+2])[0] \ for i in compat.xrange(0, len(data), 2) ] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexline(cls, data, separator = ' ', width = None): """ Dump a line of hexadecimal numbers from binary data. @type data: str @param data: Binary data. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. This value is also used for padding. @rtype: str @return: Multiline output text. """
if width is None: fmt = '%s %s' else: fmt = '%%-%ds %%-%ds' % ((len(separator)+2)*width-1, width) return fmt % (cls.hexadecimal(data, separator), cls.printable(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 hexblock(cls, data, address = None, bits = None, separator = ' ', width = 8): """ Dump a block of hexadecimal numbers from binary data. Also show a printable text version of the data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. @rtype: str @return: Multiline output text. """
return cls.hexblock_cb(cls.hexline, data, address, bits, width, cb_kwargs = {'width' : width, 'separator' : separator})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexblock_cb(cls, callback, data, address = None, bits = None, width = 16, cb_args = (), cb_kwargs = {}): """ Dump a block of binary data using a callback function to convert each line of text. @type callback: function @param callback: Callback function to convert each line of data. @type data: str @param data: Binary data. @type address: str @param address: (Optional) Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type cb_args: str @param cb_args: (Optional) Arguments to pass to the callback function. @type cb_kwargs: str @param cb_kwargs: (Optional) Keyword arguments to pass to the callback function. @type width: int @param width: (Optional) Maximum number of bytes to convert per text line. @rtype: str @return: Multiline output text. """
result = '' if address is None: for i in compat.xrange(0, len(data), width): result = '%s%s\n' % ( result, \ callback(data[i:i+width], *cb_args, **cb_kwargs) ) else: for i in compat.xrange(0, len(data), width): result = '%s%s: %s\n' % ( result, cls.address(address, bits), callback(data[i:i+width], *cb_args, **cb_kwargs) ) address += width 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 hexblock_byte(cls, data, address = None, bits = None, separator = ' ', width = 16): """ Dump a block of hexadecimal BYTEs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each BYTE. @type width: int @param width: (Optional) Maximum number of BYTEs to convert per text line. @rtype: str @return: Multiline output text. """
return cls.hexblock_cb(cls.hexadecimal, data, address, bits, width, cb_kwargs = {'separator': separator})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexblock_word(cls, data, address = None, bits = None, separator = ' ', width = 8): """ Dump a block of hexadecimal WORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each WORD. @type width: int @param width: (Optional) Maximum number of WORDs to convert per text line. @rtype: str @return: Multiline output text. """
return cls.hexblock_cb(cls.hexa_word, data, address, bits, width * 2, cb_kwargs = {'separator': separator})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexblock_dword(cls, data, address = None, bits = None, separator = ' ', width = 4): """ Dump a block of hexadecimal DWORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each DWORD. @type width: int @param width: (Optional) Maximum number of DWORDs to convert per text line. @rtype: str @return: Multiline output text. """
return cls.hexblock_cb(cls.hexa_dword, data, address, bits, width * 4, cb_kwargs = {'separator': separator})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hexblock_qword(cls, data, address = None, bits = None, separator = ' ', width = 2): """ Dump a block of hexadecimal QWORDs from binary data. @type data: str @param data: Binary data. @type address: str @param address: Memory address where the data was read from. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @type separator: str @param separator: Separator between the hexadecimal representation of each QWORD. @type width: int @param width: (Optional) Maximum number of QWORDs to convert per text line. @rtype: str @return: Multiline output text. """
return cls.hexblock_cb(cls.hexa_qword, data, address, bits, width * 8, cb_kwargs = {'separator': separator})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def default(cls): "Make the current foreground color the default." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREY wAttributes &= ~win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def light(cls): "Make the current foreground color light." wAttributes = cls._get_text_attributes() wAttributes |= win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dark(cls): "Make the current foreground color dark." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def black(cls): "Make the text foreground color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK #wAttributes |= win32.FOREGROUND_BLACK cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def white(cls): "Make the text foreground color white." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def red(cls): "Make the text foreground color red." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_RED cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def green(cls): "Make the text foreground color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_GREEN cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def blue(cls): "Make the text foreground color blue." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_BLUE cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cyan(cls): "Make the text foreground color cyan." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_CYAN cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def magenta(cls): "Make the text foreground color magenta." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_MAGENTA cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def yellow(cls): "Make the text foreground color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_YELLOW cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_default(cls): "Make the current background color the default." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK wAttributes &= ~win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_light(cls): "Make the current background color light." wAttributes = cls._get_text_attributes() wAttributes |= win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_dark(cls): "Make the current background color dark." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_black(cls): "Make the text background color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_white(cls): "Make the text background color white." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREY cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_red(cls): "Make the text background color red." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_RED cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_green(cls): "Make the text background color green." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_GREEN cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_blue(cls): "Make the text background color blue." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_BLUE cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_cyan(cls): "Make the text background color cyan." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_CYAN cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_magenta(cls): "Make the text background color magenta." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_MAGENTA cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bk_yellow(cls): "Make the text background color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_YELLOW cls._set_text_attributes(wAttributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addRow(self, *row): """ Add a row to the table. All items are converted to strings. @type row: tuple @keyword row: Each argument is a cell in the table. """
row = [ str(item) for item in row ] len_row = [ len(item) for item in row ] width = self.__width len_old = len(width) len_new = len(row) known = min(len_old, len_new) missing = len_new - len_old if missing > 0: width.extend( len_row[ -missing : ] ) elif missing < 0: len_row.extend( [0] * (-missing) ) self.__width = [ max( width[i], len_row[i] ) for i in compat.xrange(len(len_row)) ] self.__cols.append(row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def justify(self, column, direction): """ Make the text in a column left or right justified. @type column: int @param column: Index of the column. @type direction: int @param direction: C{-1} to justify left, C{1} to justify right. @raise IndexError: Bad column index. @raise ValueError: Bad direction value. """
if direction == -1: self.__width[column] = abs(self.__width[column]) elif direction == 1: self.__width[column] = - abs(self.__width[column]) else: raise ValueError("Bad direction value.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getWidth(self): """ Get the width of the text output for the table. @rtype: int @return: Width in characters for the text output, including the newline character. """
width = 0 if self.__width: width = sum( abs(x) for x in self.__width ) width = width + len(self.__width) * len(self.__sep) + 1 return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yieldOutput(self): """ Generate the text output for the table. @rtype: generator of str @return: Text output. """
width = self.__width if width: num_cols = len(width) fmt = ['%%%ds' % -w for w in width] if width[-1] > 0: fmt[-1] = '%s' fmt = self.__sep.join(fmt) for row in self.__cols: row.extend( [''] * (num_cols - len(row)) ) yield fmt % tuple(row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_registers_peek(registers, data, separator = ' ', width = 16): """ Dump data pointed to by the given registers, if any. @type registers: dict( str S{->} int ) @param registers: Dictionary mapping register names to their values. This value is returned by L{Thread.get_context}. @type data: dict( str S{->} str ) @param data: Dictionary mapping register names to the data they point to. This value is returned by L{Thread.peek_pointers_in_registers}. @rtype: str @return: Text suitable for logging. """
if None in (registers, data): return '' names = compat.keys(data) names.sort() result = '' for reg_name in names: tag = reg_name.lower() dumped = HexDump.hexline(data[reg_name], separator, width) result += '%s -> %s\n' % (tag, dumped) 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 dump_data_peek(data, base = 0, separator = ' ', width = 16, bits = None): """ Dump data from pointers guessed within the given binary data. @type data: str @param data: Dictionary mapping offsets to the data they point to. @type base: int @param base: Base offset. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """
if data is None: return '' pointers = compat.keys(data) pointers.sort() result = '' for offset in pointers: dumped = HexDump.hexline(data[offset], separator, width) address = HexDump.address(base + offset, bits) result += '%s -> %s\n' % (address, dumped) 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 dump_stack_peek(data, separator = ' ', width = 16, arch = None): """ Dump data from pointers guessed within the given stack dump. @type data: str @param data: Dictionary mapping stack offsets to the data they point to. @type separator: str @param separator: Separator between the hexadecimal representation of each character. @type width: int @param width: (Optional) Maximum number of characters to convert per text line. This value is also used for padding. @type arch: str @param arch: Architecture of the machine whose registers were dumped. Defaults to the current architecture. @rtype: str @return: Text suitable for logging. """
if data is None: return '' if arch is None: arch = win32.arch pointers = compat.keys(data) pointers.sort() result = '' if pointers: if arch == win32.ARCH_I386: spreg = 'esp' elif arch == win32.ARCH_AMD64: spreg = 'rsp' else: spreg = 'STACK' # just a generic tag tag_fmt = '[%s+0x%%.%dx]' % (spreg, len( '%x' % pointers[-1] ) ) for offset in pointers: dumped = HexDump.hexline(data[offset], separator, width) tag = tag_fmt % offset result += '%s -> %s\n' % (tag, dumped) 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 dump_code(disassembly, pc = None, bLowercase = True, bits = None): """ Dump a disassembly. Optionally mark where the program counter is. @type disassembly: list of tuple( int, int, str, str ) @param disassembly: Disassembly dump as returned by L{Process.disassemble} or L{Thread.disassemble_around_pc}. @type pc: int @param pc: (Optional) Program counter. @type bLowercase: bool @param bLowercase: (Optional) If C{True} convert the code to lowercase. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """
if not disassembly: return '' table = Table(sep = ' | ') for (addr, size, code, dump) in disassembly: if bLowercase: code = code.lower() if addr == pc: addr = ' * %s' % HexDump.address(addr, bits) else: addr = ' %s' % HexDump.address(addr, bits) table.addRow(addr, dump, code) table.justify(1, 1) return table.getOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_memory_map(memoryMap, mappedFilenames = None, bits = None): """ Dump the memory map of a process. Optionally show the filenames for memory mapped files as well. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: Memory map returned by L{Process.get_memory_map}. @type mappedFilenames: dict( int S{->} str ) @param mappedFilenames: (Optional) Memory mapped filenames returned by L{Process.get_mapped_filenames}. @type bits: int @param bits: (Optional) Number of bits of the target architecture. The default is platform dependent. See: L{HexDump.address_size} @rtype: str @return: Text suitable for logging. """
if not memoryMap: return '' table = Table() if mappedFilenames: table.addRow("Address", "Size", "State", "Access", "Type", "File") else: table.addRow("Address", "Size", "State", "Access", "Type") # For each memory block in the map... for mbi in memoryMap: # Address and size of memory block. BaseAddress = HexDump.address(mbi.BaseAddress, bits) RegionSize = HexDump.address(mbi.RegionSize, bits) # State (free or allocated). mbiState = mbi.State if mbiState == win32.MEM_RESERVE: State = "Reserved" elif mbiState == win32.MEM_COMMIT: State = "Commited" elif mbiState == win32.MEM_FREE: State = "Free" else: State = "Unknown" # Page protection bits (R/W/X/G). if mbiState != win32.MEM_COMMIT: Protect = "" else: mbiProtect = mbi.Protect if mbiProtect & win32.PAGE_NOACCESS: Protect = "--- " elif mbiProtect & win32.PAGE_READONLY: Protect = "R-- " elif mbiProtect & win32.PAGE_READWRITE: Protect = "RW- " elif mbiProtect & win32.PAGE_WRITECOPY: Protect = "RC- " elif mbiProtect & win32.PAGE_EXECUTE: Protect = "--X " elif mbiProtect & win32.PAGE_EXECUTE_READ: Protect = "R-X " elif mbiProtect & win32.PAGE_EXECUTE_READWRITE: Protect = "RWX " elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY: Protect = "RCX " else: Protect = "??? " if mbiProtect & win32.PAGE_GUARD: Protect += "G" else: Protect += "-" if mbiProtect & win32.PAGE_NOCACHE: Protect += "N" else: Protect += "-" if mbiProtect & win32.PAGE_WRITECOMBINE: Protect += "W" else: Protect += "-" # Type (file mapping, executable image, or private memory). mbiType = mbi.Type if mbiType == win32.MEM_IMAGE: Type = "Image" elif mbiType == win32.MEM_MAPPED: Type = "Mapped" elif mbiType == win32.MEM_PRIVATE: Type = "Private" elif mbiType == 0: Type = "" else: Type = "Unknown" # Output a row in the table. if mappedFilenames: FileName = mappedFilenames.get(mbi.BaseAddress, '') table.addRow( BaseAddress, RegionSize, State, Protect, Type, FileName ) else: table.addRow( BaseAddress, RegionSize, State, Protect, Type ) # Return the table output. return table.getOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_text(text): """ Log lines of text, inserting a timestamp. @type text: str @param text: Text to log. @rtype: str @return: Log line. """
if text.endswith('\n'): text = text[:-len('\n')] #text = text.replace('\n', '\n\t\t') # text CSV ltime = time.strftime("%X") msecs = (time.time() % 1) * 1000 return '[%s.%04d] %s' % (ltime, msecs, text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __logfile_error(self, e): """ Shows an error message to standard error if the log file can't be written to. Used internally. @type e: Exception @param e: Exception raised when trying to write to the log file. """
from sys import stderr msg = "Warning, error writing log file %s: %s\n" msg = msg % (self.logfile, str(e)) stderr.write(DebugLog.log_text(msg)) self.logfile = None self.fd = 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 log_request(self, code='-', size='-'): """Selectively log an accepted request."""
if self.server.logRequests: BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def versionok_for_gui(): ''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ''' # We require Python 2.6+ ... if sys.hexversion < 0x02060000: return False # Or Python 3.2+ if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000: return False # Not supported under Jython nor IronPython if sys.platform.startswith("java") or sys.platform.startswith('cli'): 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 RaiseIfNotErrorSuccess(result, func = None, arguments = ()): """ Error checking for Win32 Registry API calls. The function is assumed to return a Win32 error code. If the code is not C{ERROR_SUCCESS} then a C{WindowsError} exception is raised. """
if result != ERROR_SUCCESS: raise ctypes.WinError(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 do(self, arg): ".example - This is an example plugin for the command line debugger" print "This is an example command." print "%s.do(%r, %r):" % (__name__, self, arg) print " last event", self.lastEvent print " prefix", self.cmdprefix print " arguments", self.split_tokens(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 set_process(self, process = None): """ Manually set the parent Process object. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process. """
if process is None: self.dwProcessId = None self.__process = None else: self.__load_Process_class() if not isinstance(process, Process): msg = "Parent process must be a Process instance, " msg += "got %s instead" % type(process) raise TypeError(msg) self.dwProcessId = process.get_pid() self.__process = process
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS): """ Opens a new handle to the thread, closing the previous one. The new handle is stored in the L{hThread} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.THREAD_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx} @raise WindowsError: It's not possible to open a handle to the thread with the requested access rights. This tipically happens because the target thread belongs to system process and the debugger is not runnning with administrative rights. """
hThread = win32.OpenThread(dwDesiredAccess, win32.FALSE, self.dwThreadId) # In case hThread was set to an actual handle value instead of a Handle # object. This shouldn't happen unless the user tinkered with it. if not hasattr(self.hThread, '__del__'): self.close_handle() self.hThread = hThread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_handle(self): """ Closes the handle to the thread. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. """
try: if hasattr(self.hThread, 'close'): self.hThread.close() elif self.hThread not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hThread) finally: self.hThread = 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 kill(self, dwExitCode = 0): """ Terminates the thread execution. @note: If the C{lpInjectedMemory} member contains a valid pointer, the memory is freed. @type dwExitCode: int @param dwExitCode: (Optional) Thread exit code. """
hThread = self.get_handle(win32.THREAD_TERMINATE) win32.TerminateThread(hThread, dwExitCode) # Ugliest hack ever, won't work if many pieces of code are injected. # Seriously, what was I thinking? Lame! :( if self.pInjectedMemory is not None: try: self.get_process().free(self.pInjectedMemory) self.pInjectedMemory = None except Exception: ## raise # XXX DEBUG pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suspend(self): """ Suspends the thread execution. @rtype: int @return: Suspend count. If zero, the thread is running. """
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME) if self.is_wow64(): # FIXME this will be horribly slow on XP 64 # since it'll try to resolve a missing API every time try: return win32.Wow64SuspendThread(hThread) except AttributeError: pass return win32.SuspendThread(hThread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(self): """ Resumes the thread execution. @rtype: int @return: Suspend count. If zero, the thread is running. """
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME) return win32.ResumeThread(hThread)
<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_context(self, context, bSuspend = False): """ Sets the values of the registers. @see: L{get_context} @type context: dict( str S{->} int ) @param context: Dictionary mapping register names to their values. @type bSuspend: bool @param bSuspend: C{True} to automatically suspend the thread before setting its context, C{False} otherwise. Defaults to C{False} because suspending the thread during some debug events (like thread creation or destruction) may lead to strange errors. Note that WinAppDbg 1.4 used to suspend the thread automatically always. This behavior was changed in version 1.5. """
# Get the thread handle. dwAccess = win32.THREAD_SET_CONTEXT if bSuspend: dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME hThread = self.get_handle(dwAccess) # Suspend the thread if requested. if bSuspend: self.suspend() # No fix for the exit process event bug. # Setting the context of a dead thread is pointless anyway. # Set the thread context. try: if win32.bits == 64 and self.is_wow64(): win32.Wow64SetThreadContext(hThread, context) else: win32.SetThreadContext(hThread, context) # Resume the thread if we suspended it. finally: if bSuspend: self.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_register(self, register, value): """ Sets the value of a specific register. @type register: str @param register: Register name. @rtype: int @return: Register value. """
context = self.get_context() context[register] = value self.set_context(context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_wow64(self): """ Determines if the thread is running under WOW64. @rtype: bool @return: C{True} if the thread is running under WOW64. That is, it belongs to a 32-bit application running in a 64-bit Windows. C{False} if the thread belongs to either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows. @raise WindowsError: On error an exception is raised. @see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} """
try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: wow64 = self.get_process().is_wow64() self.__wow64 = wow64 return wow64
<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_teb_address(self): """ Returns a remote pointer to the TEB. @rtype: int @return: Remote pointer to the L{TEB} structure. @raise WindowsError: An exception is raised on error. """
try: return self._teb_ptr except AttributeError: try: hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION) tbi = win32.NtQueryInformationThread( hThread, win32.ThreadBasicInformation) address = tbi.TebBaseAddress except WindowsError: address = self.get_linear_address('SegFs', 0) # fs:[0] if not address: raise self._teb_ptr = address return 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 get_linear_address(self, segment, address): """ Translates segment-relative addresses to linear addresses. Linear addresses can be used to access a process memory, calling L{Process.read} and L{Process.write}. @type segment: str @param segment: Segment register name. @type address: int @param address: Segment relative memory address. @rtype: int @return: Linear memory address. @raise ValueError: Address is too large for selector. @raise WindowsError: The current architecture does not support selectors. Selectors only exist in x86-based systems. """
hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION) selector = self.get_register(segment) ldt = win32.GetThreadSelectorEntry(hThread, selector) BaseLow = ldt.BaseLow BaseMid = ldt.HighWord.Bytes.BaseMid << 16 BaseHi = ldt.HighWord.Bytes.BaseHi << 24 Base = BaseLow | BaseMid | BaseHi LimitLow = ldt.LimitLow LimitHi = ldt.HighWord.Bits.LimitHi << 16 Limit = LimitLow | LimitHi if address > Limit: msg = "Address %s too large for segment %s (selector %d)" msg = msg % (HexDump.address(address, self.get_bits()), segment, selector) raise ValueError(msg) return Base + 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 get_seh_chain_pointer(self): """ Get the pointer to the first structured exception handler block. @rtype: int @return: Remote pointer to the first block of the structured exception handlers linked list. If the list is empty, the returned value is C{0xFFFFFFFF}. @raise NotImplementedError: This method is only supported in 32 bits versions of Windows. """
if win32.arch != win32.ARCH_I386: raise NotImplementedError( "SEH chain parsing is only supported in 32-bit Windows.") process = self.get_process() address = self.get_linear_address( 'SegFs', 0 ) return process.read_pointer( 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 set_seh_chain_pointer(self, value): """ Change the pointer to the first structured exception handler block. @type value: int @param value: Value of the remote pointer to the first block of the structured exception handlers linked list. To disable SEH set the value C{0xFFFFFFFF}. @raise NotImplementedError: This method is only supported in 32 bits versions of Windows. """
if win32.arch != win32.ARCH_I386: raise NotImplementedError( "SEH chain parsing is only supported in 32-bit Windows.") process = self.get_process() address = self.get_linear_address( 'SegFs', 0 ) process.write_pointer( address, value )
<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_stack_frame_range(self): """ Returns the starting and ending addresses of the stack frame. Only works for functions with standard prologue and epilogue. @rtype: tuple( int, int ) @return: Stack frame range. May not be accurate, depending on the compiler used. @raise RuntimeError: The stack frame is invalid, or the function doesn't have a standard prologue and epilogue. @raise WindowsError: An error occured when getting the thread context. """
st, sb = self.get_stack_range() # top, bottom sp = self.get_sp() fp = self.get_fp() size = fp - sp if not st <= sp < sb: raise RuntimeError('Stack pointer lies outside the stack') if not st <= fp < sb: raise RuntimeError('Frame pointer lies outside the stack') if sp > fp: raise RuntimeError('No valid stack frame found') return (sp, fp)
<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_stack_frame(self, max_size = None): """ Reads the contents of the current stack frame. Only works for functions with standard prologue and epilogue. @type max_size: int @param max_size: (Optional) Maximum amount of bytes to read. @rtype: str @return: Stack frame data. May not be accurate, depending on the compiler used. May return an empty string. @raise RuntimeError: The stack frame is invalid, or the function doesn't have a standard prologue and epilogue. @raise WindowsError: An error occured when getting the thread context or reading data from the process memory. """
sp, fp = self.get_stack_frame_range() size = fp - sp if max_size and size > max_size: size = max_size return self.get_process().peek(sp, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stack_data(self, size = 128, offset = 0): """ Reads the contents of the top of the stack. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: str @return: Stack data. @raise WindowsError: Could not read the requested data. """
aProcess = self.get_process() return aProcess.read(self.get_sp() + offset, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_stack_data(self, size = 128, offset = 0): """ Tries to read the contents of the top of the stack. @type size: int @param size: Number of bytes to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @rtype: str @return: Stack data. Returned data may be less than the requested size. """
aProcess = self.get_process() return aProcess.peek(self.get_sp() + offset, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stack_dwords(self, count, offset = 0): """ Reads DWORDs from the top of the stack. @type count: int @param count: Number of DWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @return: Tuple of integers read from the stack. @raise WindowsError: Could not read the requested data. """
if count > 0: stackData = self.read_stack_data(count * 4, offset) return struct.unpack('<'+('L'*count), stackData) return ()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_stack_dwords(self, count, offset = 0): """ Tries to read DWORDs from the top of the stack. @type count: int @param count: Number of DWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @return: Tuple of integers read from the stack. May be less than the requested number of DWORDs. """
stackData = self.peek_stack_data(count * 4, offset) if len(stackData) & 3: stackData = stackData[:-len(stackData) & 3] if not stackData: return () return struct.unpack('<'+('L'*count), stackData)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stack_qwords(self, count, offset = 0): """ Reads QWORDs from the top of the stack. @type count: int @param count: Number of QWORDs to read. @type offset: int @param offset: Offset from the stack pointer to begin reading. @return: Tuple of integers read from the stack. @raise WindowsError: Could not read the requested data. """
stackData = self.read_stack_data(count * 8, offset) return struct.unpack('<'+('Q'*count), stackData)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stack_structure(self, structure, offset = 0): """ Reads the given structure at the top of the stack. @type structure: ctypes.Structure @param structure: Structure of the data to read from the stack. @type offset: int @param offset: Offset from the stack pointer to begin reading. The stack pointer is the same returned by the L{get_sp} method. @rtype: tuple @return: Tuple of elements read from the stack. The type of each element matches the types in the stack frame structure. """
aProcess = self.get_process() stackData = aProcess.read_structure(self.get_sp() + offset, structure) return tuple([ stackData.__getattribute__(name) for (name, type) in stackData._fields_ ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stack_frame(self, structure, offset = 0): """ Reads the stack frame of the thread. @type structure: ctypes.Structure @param structure: Structure of the stack frame. @type offset: int @param offset: Offset from the frame pointer to begin reading. The frame pointer is the same returned by the L{get_fp} method. @rtype: tuple @return: Tuple of elements read from the stack frame. The type of each element matches the types in the stack frame structure. """
aProcess = self.get_process() stackData = aProcess.read_structure(self.get_fp() + offset, structure) return tuple([ stackData.__getattribute__(name) for (name, type) in stackData._fields_ ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek_pointers_in_registers(self, peekSize = 16, context = None): """ Tries to guess which values in the registers are valid pointers, and reads some data from them. @type peekSize: int @param peekSize: Number of bytes to read from each pointer found. @type context: dict( str S{->} int ) @param context: (Optional) Dictionary mapping register names to their values. If not given, the current thread context will be used. @rtype: dict( str S{->} str ) @return: Dictionary mapping register names to the data they point to. """
peekable_registers = ( 'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp' ) if not context: context = self.get_context(win32.CONTEXT_CONTROL | \ win32.CONTEXT_INTEGER) aProcess = self.get_process() data = dict() for (reg_name, reg_value) in compat.iteritems(context): if reg_name not in peekable_registers: continue ## if reg_name == 'Ebp': ## stack_begin, stack_end = self.get_stack_range() ## print hex(stack_end), hex(reg_value), hex(stack_begin) ## if stack_begin and stack_end and stack_end < stack_begin and \ ## stack_begin <= reg_value <= stack_end: ## continue reg_data = aProcess.peek(reg_value, peekSize) if reg_data: data[reg_name] = reg_data 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 find_threads_by_name(self, name, bExactMatch = True): """ Find threads by name, using different search methods. @type name: str, None @param name: Name to look for. Use C{None} to find nameless threads. @type bExactMatch: bool @param bExactMatch: C{True} if the name must be B{exactly} as given, C{False} if the name can be loosely matched. This parameter is ignored when C{name} is C{None}. @rtype: list( L{Thread} ) @return: All threads matching the given name. """
found_threads = list() # Find threads with no name. if name is None: for aThread in self.iter_threads(): if aThread.get_name() is None: found_threads.append(aThread) # Find threads matching the given name exactly. elif bExactMatch: for aThread in self.iter_threads(): if aThread.get_name() == name: found_threads.append(aThread) # Find threads whose names match the given substring. else: for aThread in self.iter_threads(): t_name = aThread.get_name() if t_name is not None and name in t_name: found_threads.append(aThread) return found_threads
<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_thread(self, lpStartAddress, lpParameter=0, bSuspended = False): """ Remotely creates a new thread in the process. @type lpStartAddress: int @param lpStartAddress: Start address for the new thread. @type lpParameter: int @param lpParameter: Optional argument for the new thread. @type bSuspended: bool @param bSuspended: C{True} if the new thread should be suspended. In that case use L{Thread.resume} to start execution. """
if bSuspended: dwCreationFlags = win32.CREATE_SUSPENDED else: dwCreationFlags = 0 hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD | win32.PROCESS_QUERY_INFORMATION | win32.PROCESS_VM_OPERATION | win32.PROCESS_VM_WRITE | win32.PROCESS_VM_READ ) hThread, dwThreadId = win32.CreateRemoteThread( hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags) aThread = Thread(dwThreadId, hThread, self) self._add_thread(aThread) return aThread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_threads(self): """ Populates the snapshot with running threads. """
# Ignore special process IDs. # PID 0: System Idle Process. Also has a special meaning to the # toolhelp APIs (current process). # PID 4: System Integrity Group. See this forum post for more info: # http://tinyurl.com/ycza8jo # (points to social.technet.microsoft.com) # Only on XP and above # PID 8: System (?) only in Windows 2000 and below AFAIK. # It's probably the same as PID 4 in XP and above. dwProcessId = self.get_pid() if dwProcessId in (0, 4, 8): return ## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan dead_tids = self._get_thread_ids() dwProcessId = self.get_pid() hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD, dwProcessId) try: te = win32.Thread32First(hSnapshot) while te is not None: if te.th32OwnerProcessID == dwProcessId: dwThreadId = te.th32ThreadID if dwThreadId in dead_tids: dead_tids.remove(dwThreadId) ## if not self.has_thread(dwThreadId): # XXX triggers a scan if not self._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = self) self._add_thread(aThread) te = win32.Thread32Next(hSnapshot) finally: win32.CloseHandle(hSnapshot) for tid in dead_tids: self._del_thread(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 clear_dead_threads(self): """ Remove Thread objects from the snapshot referring to threads no longer running. """
for tid in self.get_thread_ids(): aThread = self.get_thread(tid) if not aThread.is_alive(): self._del_thread(aThread)
<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_threads(self): """ Clears the threads snapshot. """
for aThread in compat.itervalues(self.__threadDict): aThread.clear() self.__threadDict = dict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_thread_handles(self): """ Closes all open handles to threads in the snapshot. """
for aThread in self.iter_threads(): try: aThread.close_handle() except Exception: try: e = sys.exc_info()[1] msg = "Cannot close thread handle %s, reason: %s" msg %= (aThread.hThread.value, str(e)) warnings.warn(msg) except Exception: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_thread(self, aThread): """ Private method to add a thread object to the snapshot. @type aThread: L{Thread} @param aThread: Thread object. """
## if not isinstance(aThread, Thread): ## if hasattr(aThread, '__class__'): ## typename = aThread.__class__.__name__ ## else: ## typename = str(type(aThread)) ## msg = "Expected Thread, got %s instead" % typename ## raise TypeError(msg) dwThreadId = aThread.dwThreadId ## if dwThreadId in self.__threadDict: ## msg = "Already have a Thread object with ID %d" % dwThreadId ## raise KeyError(msg) aThread.set_process(self) self.__threadDict[dwThreadId] = aThread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _del_thread(self, dwThreadId): """ Private method to remove a thread object from the snapshot. @type dwThreadId: int @param dwThreadId: Global thread ID. """
try: aThread = self.__threadDict[dwThreadId] del self.__threadDict[dwThreadId] except KeyError: aThread = None msg = "Unknown thread ID %d" % dwThreadId warnings.warn(msg, RuntimeWarning) if aThread: aThread.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __add_created_thread(self, event): """ Private method to automatically add new thread objects from debug events. @type event: L{Event} @param event: Event object. """
dwThreadId = event.get_tid() hThread = event.get_thread_handle() ## if not self.has_thread(dwThreadId): # XXX this would trigger a scan if not self._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, hThread, self) teb_ptr = event.get_teb() # remember the TEB pointer if teb_ptr: aThread._teb_ptr = teb_ptr self._add_thread(aThread)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list): """ This function appends values of the attribute `attribute_name` of the inserted code to the original values, and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument number i, after modification it calls argument n + i, where n - length of the values in the original code. So it helps to avoid variables mixing between two pieces of code. :param original_code: code to modify :param insert_code: code to insert :param insert_code_obj: bytes sequence of inserted code, which should be modified too :param attribute_name: name of attribute to modify ('co_names', 'co_consts' or 'co_varnames') :param op_list: sequence of bytecodes whose arguments should be changed :return: modified bytes sequence of the code to insert and new values of the attribute `attribute_name` for original code """
orig_value = getattr(original_code, attribute_name) insert_value = getattr(insert_code, attribute_name) orig_names_len = len(orig_value) code_with_new_values = list(insert_code_list) offset = 0 while offset < len(code_with_new_values): op = code_with_new_values[offset] if op in op_list: new_val = code_with_new_values[offset + 1] + orig_names_len if new_val > MAX_BYTE: code_with_new_values[offset + 1] = new_val & MAX_BYTE code_with_new_values = code_with_new_values[:offset] + [EXTENDED_ARG, new_val >> 8] + \ code_with_new_values[offset:] offset += 2 else: code_with_new_values[offset + 1] = new_val offset += 2 new_values = orig_value + insert_value return bytes(code_with_new_values), new_values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _insert_code(code_to_modify, code_to_insert, before_line): """ Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the instruction on this line by modifying original bytecode :param code_to_modify: Code to modify :param code_to_insert: Code to insert :param before_line: Number of line for code insertion :return: boolean flag whether insertion was successful, modified code """
linestarts = dict(dis.findlinestarts(code_to_modify)) if not linestarts: return False, code_to_modify if code_to_modify.co_name == '<module>': # There's a peculiarity here: if a breakpoint is added in the first line of a module, we # can't replace the code because we require a line event to stop and the line event # was already generated, so, fallback to tracing. if before_line == min(linestarts.values()): return False, code_to_modify if before_line not in linestarts.values(): return False, code_to_modify offset = None for off, line_no in linestarts.items(): if line_no == before_line: offset = off break code_to_insert_list = add_jump_instruction(offset, code_to_insert) try: code_to_insert_list, new_names = \ _add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_names', dis.hasname) code_to_insert_list, new_consts = \ _add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_consts', [opmap['LOAD_CONST']]) code_to_insert_list, new_vars = \ _add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_varnames', dis.haslocal) new_bytes, all_inserted_code = _update_label_offsets(code_to_modify.co_code, offset, list(code_to_insert_list)) new_lnotab = _modify_new_lines(code_to_modify, offset, code_to_insert_list) if new_lnotab is None: return False, code_to_modify except ValueError: pydev_log.exception() return False, code_to_modify new_code = CodeType( code_to_modify.co_argcount, # integer code_to_modify.co_kwonlyargcount, # integer len(new_vars), # integer code_to_modify.co_stacksize, # integer code_to_modify.co_flags, # integer new_bytes, # bytes new_consts, # tuple new_names, # tuple new_vars, # tuple code_to_modify.co_filename, # string code_to_modify.co_name, # string code_to_modify.co_firstlineno, # integer new_lnotab, # bytes code_to_modify.co_freevars, # tuple code_to_modify.co_cellvars # tuple ) return True, new_code
<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_thread(self, thread = None): """ Manually set the thread process. Use with care! @type thread: L{Thread} @param thread: (Optional) Thread object. Use C{None} to autodetect. """
if thread is None: self.__thread = None else: self.__load_Thread_class() if not isinstance(thread, Thread): msg = "Parent thread must be a Thread instance, " msg += "got %s instead" % type(thread) raise TypeError(msg) self.dwThreadId = thread.get_tid() self.__thread = 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 __get_window(self, hWnd): """ User internally to get another Window from this one. It'll try to copy the parent Process and Thread references if possible. """
window = Window(hWnd) if window.get_pid() == self.get_pid(): window.set_process( self.get_process() ) if window.get_tid() == self.get_tid(): window.set_thread( self.get_thread() ) return window
<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_client_rect(self): """ Get the window's client area coordinates in the desktop. @rtype: L{win32.Rect} @return: Rectangle occupied by the window's client area in the desktop. @raise WindowsError: An error occured while processing this request. """
cr = win32.GetClientRect( self.get_handle() ) cr.left, cr.top = self.client_to_screen(cr.left, cr.top) cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom) return cr
<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_child_at(self, x, y, bAllowTransparency = True): """ Get the child window located at the given coordinates. If no such window exists an exception is raised. @see: L{get_children} @type x: int @param x: Horizontal coordinate. @type y: int @param y: Vertical coordinate. @type bAllowTransparency: bool @param bAllowTransparency: If C{True} transparent areas in windows are ignored, returning the window behind them. If C{False} transparent areas are treated just like any other area. @rtype: L{Window} @return: Child window at the requested position, or C{None} if there is no window at those coordinates. """
try: if bAllowTransparency: hWnd = win32.RealChildWindowFromPoint( self.get_handle(), (x, y) ) else: hWnd = win32.ChildWindowFromPoint( self.get_handle(), (x, y) ) if hWnd: return self.__get_window(hWnd) except WindowsError: pass 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 show(self, bAsync = True): """ Make the window visible. @see: L{hide} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """
if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_SHOW ) else: win32.ShowWindow( self.get_handle(), win32.SW_SHOW )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hide(self, bAsync = True): """ Make the window invisible. @see: L{show} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """
if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE ) else: win32.ShowWindow( self.get_handle(), win32.SW_HIDE )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximize(self, bAsync = True): """ Maximize the window. @see: L{minimize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """
if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_MAXIMIZE ) else: win32.ShowWindow( self.get_handle(), win32.SW_MAXIMIZE )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimize(self, bAsync = True): """ Minimize the window. @see: L{maximize}, L{restore} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """
if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_MINIMIZE ) else: win32.ShowWindow( self.get_handle(), win32.SW_MINIMIZE )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, bAsync = True): """ Unmaximize and unminimize the window. @see: L{maximize}, L{minimize} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request. """
if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE ) else: win32.ShowWindow( self.get_handle(), win32.SW_RESTORE )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None): """ Send a low-level window message syncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam: The type and meaning of this parameter depends on the message. @param dwTimeout: Optional timeout for the operation. Use C{None} to wait indefinitely. @rtype: int @return: The meaning of the return value depends on the window message. Typically a value of C{0} means an error occured. You can get the error code by calling L{win32.GetLastError}. """
if dwTimeout is None: return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam) return win32.SendMessageTimeout( self.get_handle(), uMsg, wParam, lParam, win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, uMsg, wParam = None, lParam = None): """ Post a low-level window message asyncronically. @type uMsg: int @param uMsg: Message code. @param wParam: The type and meaning of this parameter depends on the message. @param lParam: The type and meaning of this parameter depends on the message. @raise WindowsError: An error occured while sending the message. """
win32.PostMessage(self.get_handle(), uMsg, wParam, lParam)
<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_json(self, py_db, json_contents): ''' Processes a debug adapter protocol json command. ''' DEBUG = False try: request = self.from_json(json_contents, update_ids_from_dap=True) except KeyError as e: request = self.from_json(json_contents, update_ids_from_dap=False) error_msg = str(e) if error_msg.startswith("'") and error_msg.endswith("'"): error_msg = error_msg[1:-1] # This means a failure updating ids from the DAP (the client sent a key we didn't send). def on_request(py_db, request): error_response = { 'type': 'response', 'request_seq': request.seq, 'success': False, 'command': request.command, 'message': error_msg, } return NetCommand(CMD_RETURN, 0, error_response, is_json=True) else: if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS and DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: pydev_log.info('Process %s: %s\n' % ( request.__class__.__name__, json.dumps(request.to_dict(), indent=4, sort_keys=True),)) assert request.type == 'request' method_name = 'on_%s_request' % (request.command.lower(),) on_request = getattr(self, method_name, None) if on_request is None: print('Unhandled: %s not available in _PyDevJsonCommandProcessor.\n' % (method_name,)) return if DEBUG: print('Handled in pydevd: %s (in _PyDevJsonCommandProcessor).\n' % (method_name,)) py_db._main_lock.acquire() try: cmd = on_request(py_db, request) 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 _get_hit_condition_expression(self, hit_condition): '''Following hit condition values are supported * x or == x when breakpoint is hit x times * >= x when breakpoint is hit more than or equal to x times * % x when breakpoint is hit multiple of x times Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits ''' if not hit_condition: return None expr = hit_condition.strip() try: int(expr) return '@HIT@ == {}'.format(expr) except ValueError: pass if expr.startswith('%'): return '@HIT@ {} == 0'.format(expr) if expr.startswith('==') or \ expr.startswith('>') or \ expr.startswith('<'): return '@HIT@ {}'.format(expr) return hit_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 inputhook_wx2(): """Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. """
try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable elr = EventLoopRunner() # As this time is made shorter, keyboard response improves, but idle # CPU load goes up. 10 ms seems like a good compromise. elr.Run(time=10) # CHANGE time here to control polling interval except KeyboardInterrupt: pass return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _modname(path): """Return a plausible module name for the path"""
base = os.path.basename(path) filename, ext = os.path.splitext(base) return 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 enable_gtk(self, app=None): """Enable event loop integration with PyGTK. Parameters app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for PyGTK, which allows the PyGTK to integrate with terminal based applications like IPython. """
from pydev_ipython.inputhookgtk import create_inputhook_gtk self.set_inputhook(create_inputhook_gtk(self._stdin_file)) self._current_gui = GUI_GTK
<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_tk(self, app=None): """Enable event loop integration with Tk. Parameters app : toplevel :class:`Tkinter.Tk` widget, optional. Running toplevel widget to use. If not given, we probe Tk for an existing one, and create a new one if none is found. Notes ----- If you have already created a :class:`Tkinter.Tk` object, the only thing done by this method is to register with the :class:`InputHookManager`, since creating that object automatically sets ``PyOS_InputHook``. """
self._current_gui = GUI_TK if app is None: try: import Tkinter as _TK except: # Python 3 import tkinter as _TK # @UnresolvedImport app = _TK.Tk() app.withdraw() self._apps[GUI_TK] = app from pydev_ipython.inputhooktk import create_inputhook_tk self.set_inputhook(create_inputhook_tk(app)) return app
<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_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """
import OpenGL.GLUT as glut # @UnresolvedImport from pydev_ipython.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self._apps: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(sys.argv[0]) glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.set_inputhook(inputhook_glut) self._current_gui = GUI_GLUT self._apps[GUI_GLUT] = True