Example #1
0
    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            raise gdb.GdbError('offsets-of takes exactly 1 argument.')

        stype = gdb.lookup_type(argv[0])

        print argv[0], '{'
        for field in stype.fields():
            print '    %s => %d' % (field.name, field.bitpos//8)
        print '}'
Example #2
0
 def call(prompt, *args):
     cmd = [
         sys.executable,
         os.path.join(gdb.PYTHONDIR, 'readinput.py'), '-p', prompt
     ]
     cmd.extend(list(args))
     try:
         proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
         out = proc.communicate()[1]
     except OSError, e:
         raise gdb.GdbError('cannot run readinput: ' + str(e))
    def __init__(self, address):
        if address != NULL_PTR:
            self.address = address
            self.task_lst_ptr = address + TaskOffsets.TASK_NEXT.value
            self.threads_lst_ptr = address + TaskOffsets.THREAD_LST_FROM_TASK.value
            self.bsd_info_ptr = getPointerAt(address +
                                             TaskOffsets.BSD_INFO.value)

            self.bsdinfo_object = BsdInfo(self.bsd_info_ptr)
        else:
            raise gdb.GdbError(f"Null pointer in {__name__}")
Example #4
0
def get_target_endianness():
    global target_endianness
    if target_endianness is None:
        endian = gdb.execute("show endian", to_string=True)
        if "little endian" in endian:
            target_endianness = LITTLE_ENDIAN
        elif "big endian" in endian:
            target_endianness = BIG_ENDIAN
        else:
            raise gdb.GdbError("unknown endianness '{0}'".format(str(endian)))
    return target_endianness
Example #5
0
	def __init__(self):
		super(NX_show_heap, self).__init__('show heap', gdb.COMMAND_USER)
		struct_mm_allocnode_s = gdb.lookup_type('struct mm_allocnode_s')
		preceding_size = struct_mm_allocnode_s['preceding'].type.sizeof
		if preceding_size == 2:
			self._allocflag = 0x8000
		elif preceding_size == 4:
			self._allocflag = 0x80000000
		else:
			raise gdb.GdbError('invalid mm_allocnode_s.preceding size %u' % preceding_size)
			self._allocnodesize = struct_mm_allocnode_s.sizeof
Example #6
0
def execute_get_val(val, size):
    try:
        check_arguments(size)
        command = f"x /1x{size} {hex(val)}"
        LOGGER.debug("Going to excute %s ", command)
        res = gdb.execute(command, to_string=True)
        res = int(res.split()[1], 0)
        LOGGER.debug("Got a result %s ", str(res))
        return res
    except Exception:
        raise gdb.GdbError(f"{traceback.format_exc()}")
Example #7
0
 def invoke(self, arg, from_tty):
     try:
         argv = gdb.string_to_argv(arg)
         if len(argv) == 1 and sys_info.is_valid_ptr(int(argv[0], 0)):
             voucher = int(argv[0], 0)
             gdb.write(
                 types.ThreadVoucher(voucher).print_voucher_info() + '\n')
         else:
             gdb.write("wrong args\n")
     except Exception:
         raise gdb.GdbError(traceback.format_exc())
Example #8
0
    def invoke(self, args, from_tty):
        if isinstance(args, BYTES):
            args = args.decode(_filesystemencoding)
        for arg in string_to_argv(args):
            try:
                f = open(arg)
            except OSError as e:
                raise gdb.GdbError('Unable to open file %r: %s' %
                                   (args, e.args[1]))

            t = etree.parse(f)

            for module in t.getroot():
                cython_module = CythonModule(**module.attrib)
                self.cy.cython_namespace[cython_module.name] = cython_module

                for variable in module.find('Globals'):
                    d = variable.attrib
                    cython_module.globals[d['name']] = CythonVariable(**d)

                for function in module.find('Functions'):
                    cython_function = CythonFunction(module=cython_module,
                                                     **function.attrib)

                    # update the global function mappings
                    name = cython_function.name
                    qname = cython_function.qualified_name

                    self.cy.functions_by_name[name].append(cython_function)
                    self.cy.functions_by_qualified_name[
                        cython_function.qualified_name] = cython_function
                    self.cy.functions_by_cname[
                        cython_function.cname] = cython_function

                    d = cython_module.functions[qname] = cython_function

                    for local in function.find('Locals'):
                        d = local.attrib
                        cython_function.locals[d['name']] = CythonVariable(**d)

                    for step_into_func in function.find('StepIntoFunctions'):
                        d = step_into_func.attrib
                        cython_function.step_into_functions.add(d['name'])

                    cython_function.arguments.extend(
                        funcarg.tag for funcarg in function.find('Arguments'))

                for marker in module.find('LineNumberMapping'):
                    cython_lineno = int(marker.attrib['cython_lineno'])
                    c_linenos = list(
                        map(int, marker.attrib['c_linenos'].split()))
                    cython_module.lineno_cy2c[cython_lineno] = min(c_linenos)
                    for c_lineno in c_linenos:
                        cython_module.lineno_c2cy[c_lineno] = cython_lineno
Example #9
0
    def _find_first_cython_or_python_frame(self):
        frame = gdb.selected_frame()
        while frame:
            if (self.is_cython_function(frame)
                    or self.is_python_function(frame)):
                frame.select()
                return frame

            frame = frame.older()

        raise gdb.GdbError("There is no Cython or Python frame on the stack.")
Example #10
0
 def invoke(self, arg, from_tty):
     """ print info """
     try:
         argv = gdb.string_to_argv(arg)
         if len(argv) == 1 and sys_info.is_valid_ptr(int(argv[0], 0)):
             ipc_port = int(argv[0], 0)
             gdb.write(types.IPCPort(ipc_port).print_ipc_port_info() + '\n')
         else:
             gdb.write("wrong args\n")
     except Exception:
         raise gdb.GdbError(traceback.format_exc())
Example #11
0
def parseDwarfExpression(variableName, variableLength, address, lines,
                         startLine):
    """Parse a DWARF expression to get location of a variable"""

    validTarget = False
    index = startLine
    while dwarfExprPrefixMatcher.match(lines[index]):
        tokens = lines[index].split()
        tokenLen = len(tokens[1])
        if tokens[1] == "DW_OP_addr":
            # Address of variable is as specified by the DWARF op operand
            validTarget = True
            target = tokens[2]
        elif tokenLen > 9 and tokens[1][0:10] == "DW_OP_breg":
            # Value of variable is specified register + offset
            validTarget = True
            target = "( %" + tokens[3][2:5] + " + " + tokens[2] + " )"
        elif tokens[1] == "DW_OP_bregx":
            # Value of variable is specified register + offset
            # remaining tokens are probably
            # register %s [$%s] offset %s
            # see http://www.cygwin.com/ml/gdb-patches/2010-06/msg00011.html
            validTarget = True
            target = "( %" + tokens[4][2:5] + " + " + tokens[6] + " )"
        elif tokenLen > 8 and tokens[1][0:9] == "DW_OP_reg":
            # The variable value is in the specified register
            validTarget = True
            target = "%" + tokens[2][2:5]
        elif tokens[1] == "DW_OP_regx":
            # The variable value is in the specified register
            # remaining tokens are probably
            # %s [$%s]
            # see http://www.cygwin.com/ml/gdb-patches/2010-06/msg00011.html
            validTarget = True
            target = "%" + tokens[1][2:5]
        elif tokens[1] != "DW_OP_stack_value":
            # The DWARF opcode does not represent a
            # specific register or memory address, so
            # it invalidates the target in the case where
            # the value of the register or memory
            # location is important (pin break ...)
            validTarget = False
        index = index + 1

        # If target is a register then no variable length is returned
    if validTarget:
        if target[0] == "%":
            return (target, "")
        else:
            return (target, variableLength)
    else:
        raise gdb.GdbError(
            "ERROR: Unable to resolve variable %s, representation in DWARF debug info too complex"
            % variableName)
  def _awk(self, script, command):
    args = ["awk", "-f", self._awk_script_path(script), str(command)]

    if self.verbose:
      print "### awk command: " + str(args)

    awk_output = ""
    try:
      awk_output = check_output(args)
    except subprocess.CalledProcessError, e:
      raise gdb.GdbError("### Error in subprocess awk " + str(args))
Example #13
0
    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            raise gdb.GdbError('offsets-of takes exactly 1 argument.')

        stype = gdb.lookup_type(argv[0])
        print("@@@@start")

        for field in stype.fields():
            print('    [0x%x] %s' % (field.bitpos // 8, field.name))
        print("@@@@end")
Example #14
0
def list_for_each(head):
    if head.type == list_head.get_type().pointer():
        head = head.dereference()
    elif head.type != list_head.get_type():
        raise gdb.GdbError("Must be struct list_head not {}"
                           .format(head.type))

    node = head['next'].dereference()
    while node.address != head.address:
        yield node.address
        node = node['next'].dereference()
Example #15
0
    def invoke(self, cyname, frame=None):
        globals_dict = self.get_cython_globals_dict()
        cython_function = self.get_cython_function(frame)

        if self.is_initialized(cython_function, cyname):
            cname = super(CyCValue, self).invoke(cyname, frame=frame)
            return gdb.parse_and_eval(cname)
        elif cyname in globals_dict:
            return globals_dict[cyname]._gdbval
        else:
            raise gdb.GdbError("Variable %s is not initialized." % cyname)
Example #16
0
        def invoke(self, args, fromTty):
            self.dont_repeat()

            parser = GdbOptionParser("show citizen")
            if False:
                parser.add_option("object", help="The object in question")

                opts = parser.parse_args(args)
                if opts.help:
                    return
            else:
                opts, args = parser.parse_args(args)
                if opts.help:
                    return

                if not args:
                    raise gdb.GdbError("Please specify an object")
                opts.object = args.pop(0)

                if args:
                    raise gdb.GdbError("Unrecognised trailing arguments: %s" %
                                       " ".join(args))

            var = gdb.parse_and_eval(opts.object)
            if re.search(r"shared_ptr<", str(var.type)):
                var = var["px"]

            if var.type.code != gdb.TYPE_CODE_PTR:
                var = var.address

            citizen = var.dynamic_cast(
                gdb.lookup_type("lsst::daf::base::Citizen").pointer())

            if not citizen:
                raise gdb.GdbError(
                    "Failed to cast %s to Citizen -- is it a subclass?" %
                    opts.object)

            citizen = citizen.dereference()

            print(citizen)
Example #17
0
    def open(self, args: str, from_tty: bool) -> None:
        argv = shlex.split(args)
        if len(argv) < 2:
            raise gdb.GdbError("kdumpfile target requires kernel image and vmcore")

        vmlinux = argv[0]
        filename = argv[1]

        try:
            self.kdump = kdumpfile(file=filename)
        except Exception as e:
            raise gdb.GdbError("Failed to open `{}': {}"
                               .format(filename, str(e)))

        # pylint: disable=unsupported-assignment-operation
        self.kdump.attr['addrxlat.ostype'] = 'linux'

        KERNELOFFSET = "linux.vmcoreinfo.lines.KERNELOFFSET"
        try:
            attr = self.kdump.attr.get(KERNELOFFSET, "0") # pylint: disable=no-member
            self.base_offset = int(attr, base=16)
        except (TypeError, ValueError):
            pass

        # Load the kernel at the relocated address
        # Unfortunately, the percpu section has an offset of 0 and
        # ends up getting placed at the offset base.  This is easy
        # enough to handle in the percpu code.
        result = gdb.execute("symbol-file {} -o {:#x}"
                             .format(vmlinux, self.base_offset),
                             to_string=True)

        if self.debug:
            print(result)

        # We don't have an exec-file so we need to set the architecture
        # explicitly.
        arch = gdb.objfiles()[0].architecture.name()
        result = gdb.execute("set architecture {}".format(arch), to_string=True)
        if self.debug:
            print(result)
Example #18
0
def get_reads_content(fd: int) -> bytes:
    """
    Searches in recorded history for all writes to `fd` and returns the content that was read from
    that file (until end of history or until the file is closed).
    """
    content = bytearray()
    seen_any_read = False
    unsigned_char_p = gdb.lookup_type("unsigned char").pointer()

    for _ in iterate_events("name in ('close', 'read')"):
        syscall_name = get_syscall_name()
        # Both close and read accept the fd as first argument, see close(2) and read(2).
        actual_fd = int(get_syscall_argument(0))
        if actual_fd != fd:
            # Not for the file we are interested in.
            continue

        if syscall_name == "read":
            seen_any_read = True
            # The return value is the number of bytes read.
            n_read = int(get_syscall_result())
            # The second argument is a buffer where the syscall wrote n_read bytes.
            buff_p = get_syscall_argument(1).cast(unsigned_char_p)
            # gdb.Value.string (with length set to n_read) can convert the buffer to a Python
            # string, but we need to deal with non-Unicode content which is not supported directly
            # by gdb.Value. Instead, we convert one byte at a time.
            for i in range(n_read):
                char_value = int(buff_p[i])
                content.append(char_value)

        elif syscall_name == "close":
            # The file is being closed so there are not going to be further reads.
            break

        else:
            raise gdb.GdbError(f"Unexpected syscall {syscall_name} encountered")

    if not seen_any_read:
        raise gdb.GdbError(f"Cannot find any read from file descriptor {fd}.")

    return bytes(content)
Example #19
0
def from_numpy(expr, array):
    info = expr_to_info(expr)

    rows, cols, rowMajor, innerType, data = info
    eigen_sizeof = rows * cols * innerType.sizeof

    if array.shape[0] != rows and array.shape[1] != cols:
        raise gdb.GdbError(
            "array dimensions {}x{} mismatch with eigen object {}x{}" %
            (array.shape[0], array.shape[1], rows, cols))

    if rowMajor:
        v = array.astype(innerType.name, order='C', copy=False)
    else:
        v = array.T.astype(innerType.name, order='C', copy=False)

    if eigen_sizeof != v.nbytes:
        raise gdb.GdbError("size mismatch, cannot correct")

    z = gdb.selected_inferior().write_memory(data, v, v.nbytes)
    return array
Example #20
0
    def invoke(self, arg_str, from_tty):
        if ExploreUtils.check_args("explore value", arg_str) == False:
            return

        value = ExploreUtils.get_value_from_str(arg_str)
        if value is None:
            raise gdb.GdbError(
                (" '%s' does not evaluate to a value in the current "
                 "context." % arg_str))
            return

        Explorer.explore_expr(arg_str, value, False)
Example #21
0
    def get_remote_cython_globals_dict(self):
        m = gdb.parse_and_eval('__pyx_m')

        try:
            PyModuleObject = gdb.lookup_type('PyModuleObject')
        except RuntimeError:
            raise gdb.GdbError(textwrap.dedent("""\
                Unable to lookup type PyModuleObject, did you compile python
                with debugging support (-g)?"""))

        m = m.cast(PyModuleObject.pointer())
        return m['md_dict']
Example #22
0
 def invoke(self, arg, from_tty):
     """ Go over task iterator and print all task data """
     if sys_info.is_in_kernel_space() is False:
         gdb.write("\nYou are currently in user space, "
                   "this functionality is not available here.\n\n")
         return
     try:
         max_length_proc = types.get_max_length_proc_name()
         for task in iter(types.TasksIterator()):
             gdb.write(task.print_task_info_short(max_length_proc)+'\n')
     except Exception:
         raise gdb.GdbError(traceback.format_exc())
Example #23
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)
        if len(argv) != 1:
            raise gdb.GdbError("Usage: lgc lua_State")

        self.type_lookup()

        m = re.match('0[xX][0-9a-fA-F]+', argv[0])
        if m:
            L = gdb.Value(int(argv[0], 16)).cast(self.lua_State_pointer_type)

        else:
            L = gdb.parse_and_eval(argv[0])

        if not L:
            print "L empty"
            return
        g = L['glref']['ptr32'].cast(self.global_State_pointer_type)
        root = g['gc']['root']['gcptr32'].cast(self.GCObj_pointer_type)
        u = root
        table_num = 0
        if u:
            u = u['gch']['nextgc']['gcptr32'].cast(self.GCObj_pointer_type)
            agg = Aggregate()
            #print u  == root
            while u != root:
                #print u['gch']['gct']
                if u['gch']['nextgc']['gcptr32'] == 0:
                    break

                u = u['gch']['nextgc']['gcptr32'].cast(self.GCObj_pointer_type)
                if u['gch']['gct'] == 11:
                    table_num += 1
                    tab = u['tab']
                    #sys.stdout.write("<tab: %s>(%s, %s)\n" % (tab.address, tab['asize'], tab['hmask']))
                    nodes = tab['node']['ptr32'].cast(self.Node_pointer_type)
                    idx_list = []
                    node_num = 0
                    for i in xrange(tab['hmask'] + 1):
                        if nodes[i]['val']['it'] != self.LJ_TNIL:
                            idx = self.hashkey(tab, nodes[i]['key'])
                            idx_list.append(int(idx.__str__()))
                            node_num += 1
                            #print "node[%s] idx=%s" % (i, idx)
                    #print "list = %s" % idx_list
                    collide_num = self.dup_num(idx_list)
                    if node_num > 0:
                        agg << self.histogram(idx_list)
                        #self.hist_log_calc(self.histogram(idx_list))
            #print "sum, count:%d %d" %(self.sum_total, self.collide_count)
            print "table number: %d" % table_num
            print "collusion distribution:"
            agg.hist_log_print()
Example #24
0
def chooseDevice():
    # identify device
    devs = getDevices()

    # wait for a device if no device is found
    while not devs:
        try:
            print 'ADB: waiting for device... (Ctrl+C to stop)'
            waitForDevice()
        except gdb.GdbError, KeyboardInterrupt:
            raise gdb.GdbError(' ADB: no device')
        devs = getDevices()
Example #25
0
def get_current_cpu():
    if utils.get_gdbserver_type() == utils.GDBSERVER_QEMU:
        return gdb.selected_thread().num - 1
    elif utils.get_gdbserver_type() == utils.GDBSERVER_KGDB:
        tid = gdb.selected_thread().ptid[2]
        if tid > (0x100000000 - MAX_CPUS - 2):
            return 0x100000000 - tid - 2
        else:
            return tasks.get_thread_info(tasks.get_task_by_pid(tid))['cpu']
    else:
        raise gdb.GdbError("Sorry, obtaining the current CPU is not yet "
                           "supported with this gdb server.")
Example #26
0
    def invoke(self, arg, from_tty):
        "Invoke the command."

        args = gdb.string_to_argv(arg)
        if not 0 < len(args) < 3:
            raise gdb.GdbError("ty-config: bad number of arguments")

        key = args[0]
        if len(args) == 1:
            print("ctycat config: %s = %d" % (key, config_get(key)))
        else:
            config_set(key, args[1])
Example #27
0
def func_and_offset(addr):
    '''Return the function and offset into that function of `addr`.

    If failed to find the function at the given address, return (None, None).

    '''
    # If given @plt addresses (or other problematic functions) just ignore
    # them and return an error message -- (better than raising an error?)
    try:
        block = gdb.block_for_pc(addr)
    except RuntimeError as e:
        # If this is an exception we don't know about, raise.
        if e.args != ('Cannot locate object file for block.',):
            raise

        # Attempt to work with symbols that don't have debugging information.
        retval = gdb.execute('info symbol {}'.format(addr),
                            False, True)
        # Checking for section ".text" removes @plt stubs and variables.
        if 'in section .text' not in retval:
            print('{} is not a .text location'.format(addr))
            return (None, None)

        # At the moment I believe that all awkward output (i.e. of the form
        # funcname(function, argument, types) in section .text of /home/matthew/temp_dir/gdb/gdb/gdb
        # are avoided because when there is debug info we've used the alternate
        # method. Hence, the output should be of the form
        # <funcname> + <offset> in section .text of <objfile>
        # If this isn't the case, alert user so I know there's a problem and
        # can investigate what I've missed.
        #
        # NOTE: I believe that digits are always printed in decimal -- can't
        # find any way to change this, so I believe there isn't one.
        # If this isn't the case, then I hopefully will notice the problem when
        # this function fails.
        sym_match = re.match('(\S+)( \+ (\d+))? in section .text', retval)
        if not sym_match:
            print('Cannot parse output from command `info symbol {}`.'.format(
                addr))
            return (None, None)

        offset = int(sym_match.group(3)) if sym_match.group(3) else 0
        return (sym_match.group(1), offset)

    while block.function is None:
        if block.superblock:
            block = block.superblock
        else:
            raise gdb.GdbError('Could not find enclosing function of '
                                '{} ({})'.format(addr, arg))

    offset = addr - block.start
    return (block.function.name, offset)
Example #28
0
 def invoke(self, arg, from_tty):
     args = gdb.string_to_argv(arg)
     if len(args) >= 1:
         if args[0] not in self.vendors:
             raise gdb.GdbError("Invalid vendor name")
             return
         vendor_name = args[0]
         vendor_filenames = self.vendors[vendor_name]
         if len(args) == 1:
             raise gdb.GdbError("Usage: svd_load <vendor-name> <filename.svd>")
         elif len(args) >= 2:
             filename = args[1]
             try:
                 parser = SVDParser.for_packaged_svd(vendor_name, filename)
                 _svd_printer.set_device(parser.get_device())
             except IOError:
                 raise gdb.GdbError("Failed to load SVD file")
             else:
                 print("Loaded {}/{}".format(vendor_name, filename))
     else:
         raise gdb.GdbError("Usage: svd_load <vendor-name> <filename.svd>")
Example #29
0
 def invoke(self, arg, from_tty):
     argv = gdb.string_to_argv(arg)
     if len(argv) != 1:
         raise gdb.GdbError('offsets-of takes exactly 1 argument.')
     stype = gdb.lookup_type(argv[0])
     str0 = argv[0]
     words = str0.split()
     f = open(words[1] + ".struct", 'w')
     #print argv[0], '{'
     self.printFields(f, stype, "", 0)
     #print '}'
     f.close()
Example #30
0
 def invoke(self, arg, from_tty):
     try:
         args = gdb.string_to_argv(arg)
         answer = ask_user_confirmation(args[0])
         if answer == "y":
             print("User confirmed action ...")
         elif answer == "n":
             raise gdb.GdbError("User declined action ... Aborting")
         else:
             return
     except KeyboardInterrupt:
         pass