Beispiel #1
0
    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            gdb.write('usage: qemu coroutine <coroutine-pointer>\n')
            return

        bt_jmpbuf(coroutine_to_jmpbuf(gdb.parse_and_eval(argv[0])))
    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 2:
            raise gdb.GdbError('hex-dump takes exactly 2 arguments.')
        addr = gdb.parse_and_eval(argv[0]).cast(
            gdb.lookup_type('void').pointer())
        try:
            bytes = int(gdb.parse_and_eval(argv[1]))
        except ValueError:
            raise gdb.GdbError('Byte count numst be an integer value.')

        inferior = gdb.selected_inferior()

        align = gdb.parameter('hex-dump-align')
        width = gdb.parameter('hex-dump-width')
        if width == 0:
            width = 16

        mem = inferior.read_memory(addr, bytes)
        pr_addr = int(str(addr), 16)
        pr_offset = width

        if align:
            pr_offset = width - (pr_addr % width)
            pr_addr -= pr_addr % width

        for group in groups_of(mem, width, pr_offset):
            print '0x%x: ' % (pr_addr,) + '   '*(width - pr_offset),
            print ' '.join(['%02X' % (ord(g),) for g in group]) + \
                '   ' * (width - len(group) if pr_offset == width else 0) + ' ',
            print ' '*(width - pr_offset) +  ''.join(
                [g if isgraph(g) or g == ' ' else '.' for g in group])
            pr_addr += width
            pr_offset = width
Beispiel #3
0
    def invoke (self, arg_str, from_tty):
        argv = gdb.string_to_argv(arg_str)

        if len (argv) == 0:
            raise gdb.GdbError ("Provide at least one parameter with the "
                                + "breakpoint specification");
      
        self.bspec = argv[0]

        if "clones" in argv:
            self.clones = True
            pass
        else:
            self.clones = False
            pass

        if "nonames" in argv:
            self.only_orders = True
            pass
        else:
            self.only_orders = False
            pass

        if "onlyreftof" in argv:
            self.only_ref_to_f = True
            pass
        else:
            self.only_ref_to_f = False
            pass
      
        bp = self.SnapshotBreakpoint (self.bspec)
        bp.cmd = self
Beispiel #4
0
    def invoke(self, args, isatty):

        if not self.repeat:
            self.dont_repeat()

        self.parser.set_defaults(isatty=isatty)

        # Not sure we trust gdb to split the line as we want it, but
        # until there are problems we'll let him give it a shot.
        args = gdb.string_to_argv(args)

        try:
            args = self.parser.parse_args(args)
            self.run(args)
        except KeyboardInterrupt as e:
            pass
        except SystemExit as e:
            if isinstance(e.code, int):
                raise gdb.GdbError("command exited with status %s." % e.code)
            elif e.code:
                raise gdb.GdbError(str(e))
        except gdb.GdbError:
            # This type of error can be used to repport failure to gdb.
            # We let is pass through so that applications can print errors.
            # Still, the prefered way for an extension to do this
            # would be to simply use exit().
            raise
        except BaseException as e:
            if getattr(args, "isatty", True):
                # Gdb can't give us a full traceback. If this is a tty
                # or if error occured during argument parsing we do it.
                print("%s" % (traceback.format_exc(),), end="")
            else:
                raise gdb.GdbError(e)
Beispiel #5
0
    def invoke (self, args, from_tty):
        argv = gdb.string_to_argv(args)
        newestFrame = gdb.newest_frame()
        print ("the newest frame is : " + newestFrame.name())

        architecture = newestFrame.architecture()
        print ("this architecture is : " + architecture.name())
Beispiel #6
0
    def invoke(self, args, from_tty):

        # Prepare
        flash_prepare_and_show()

        # param
        argv = gdb.string_to_argv(args)
        if len(argv) == 0:
            begin = 0
            length = flash_size - flash_sector_size # last is CPFT data
        elif len(argv) == 2:
            begin = int(argv[0]) * 1024
            length = int(argv[1]) * 1024
        else:
            raise gdb.GdbError('Invalid params, "help flash_erase" for more infomation')

        # Info
        print("Erase begin={}kB length={}kB".format(begin/1024, length/1024))

        # Erase
        print("  Erase...")
        gdb.execute('set $res=flash_erase({}, {}, 0)'.format(begin, length))

        # Finish
        print("Finish")
        flash_finish()
Beispiel #7
0
  def invoke(self, arg, from_tty):
    argv = gdb.string_to_argv(arg)
    state.restore()

    #gdb.execute("thread 15", False, True)
    #cur_os_thread = gdb.selected_thread().num

    frame = gdb.newest_frame()

    handle_attach = False
    count = 0
    while True:
        function = frame.function()
        if function and function.name == "hpx::util::command_line_handling::handle_attach_debugger()":
          handle_attach = True
          break
        frame = frame.older()
        if not frame or count > 5:
          break
        count = count + 1

    if handle_attach:
      frame.select()
      gdb.execute("set var i = 1", True)


    #gdb.execute("thread %d" % cur_os_thread, False, True)

    if len(argv) == 0:
      print "Continuing..."
      gdb.execute("continue")
    else:
      if argv[0] != "hook":
          print "wrong argument ..."
Beispiel #8
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)

        if len(argv) != 1:
            raise gdb.GdbError('solib takes 1 arg')

        Strongdb.run_cmd('set solib-search-path %s' % (argv[0]))
Beispiel #9
0
def parse_xm_command_args(arg):
    """Parses the arguments passed to a xmethod command.

    Arguments:
        arg: The argument string passed to a xmethod command.

    Returns:
        A 3-tuple: (<locus matching regular expression>,
                    <matcher matching regular expression>,
                    <name matching regular experession>)
    """
    argv = gdb.string_to_argv(arg)
    argc = len(argv)
    if argc > 2:
        raise SyntaxError("Too many arguments to command.")
    locus_regexp = ""
    matcher_name_regexp = ""
    xm_name_regexp = None
    if argc >= 1:
        locus_regexp = argv[0]
    if argc == 2:
        parts = argv[1].split(";", 1)
        matcher_name_regexp = parts[0]
        if len(parts) > 1:
            xm_name_regexp = parts[1]
    if xm_name_regexp:
        name_re = validate_xm_regexp("xmethod name", xm_name_regexp)
    else:
        name_re = None
    return (validate_xm_regexp("locus", locus_regexp),
            validate_xm_regexp("matcher name", matcher_name_regexp),
            name_re)
Beispiel #10
0
    def invoke(self, argument, from_tty):
        # parse arguments
        args = gdb.string_to_argv(argument)
        if not args:
            print "Error: Missing arguments"
            return
        else:

            if issm.jp_data is not None:
                tab_name = args[0]
                tabs = issm.jp_data['Tabs']
                for tab in tabs:
                    if tab['name'] == tab_name:
                        if 'command' in tab:
                            json_string = gdb.execute(tab['command'], True, True)
                            # TODO: get nice way to display data to user in CMD
                            json_list = ast.literal_eval(json_string)
                            issm.json_printer(json_list)
                            # print json.dumps(json_list, sort_keys=False, indent=4, separators=(',',': '))
                            return
                        else:
                            print "Error: No 'command' tag found for tab '" + tab_name + "'"
                            return
                else:
                    print "Error: Tab not found"
            else:
                print "Error: Invalid layout file"
Beispiel #11
0
 def invoke(self, arg, from_tty):
     args = gdb.string_to_argv(arg)
     
     
     # generally, we type "plot someimage" in the GDB commandline
     # where "someimage" is an instance of cv::Mat
     v = gdb.parse_and_eval(args[0])
     
     # the value v is a gdb.Value object of C++
     # code's cv::Mat, we need to translate to
     # a python object under cv2.cv
     image_size =  (v['cols'],v['rows'])
     # print v
     # these two below lines do not work. I don't know why
     # channel = gdb.execute("call "+ args[0] + ".channels()", False, True)
     # channel = v.channels();
     CV_8U =0
     CV_8S =1
     CV_16U=2
     CV_16S=3
     CV_32S=4
     CV_32F=5
     CV_64F=6
     CV_USRTYPE1=7
     CV_CN_MAX = 512
     CV_CN_SHIFT = 3
     CV_MAT_CN_MASK = (CV_CN_MAX - 1) << CV_CN_SHIFT
     flags = v['flags']
     channel = (((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1
     CV_DEPTH_MAX = (1 << CV_CN_SHIFT)
     CV_MAT_DEPTH_MASK = CV_DEPTH_MAX - 1
     depth = (flags) & CV_MAT_DEPTH_MASK
     IPL_DEPTH_SIGN = 0x80000000
     cv_elem_size = (((4<<28)|0x8442211) >> depth*4) & 15
     if (depth == CV_8S or depth == CV_16S or depth == CV_32S):
             mask = IPL_DEPTH_SIGN
     else:
             mask = 0
     ipl_depth = cv_elem_size*8 | mask     
     img = cv.CreateImageHeader(image_size, ipl_depth, channel)
     
     # conver the v['data'] type to "char*" type
     char_type = gdb.lookup_type("char")
     char_pointer_type =char_type.pointer()
     buffer = v['data'].cast(char_pointer_type)
     
     # read bytes from inferior's memory, because
     # we run the opencv-python module in GDB's own process
     # otherwise, we use memory corss processes        
     buf = v['step']['buf']
     bytes = buf[0] * v['rows'] # buf[0] is the step? Not quite sure.
     inferior = gdb.selected_inferior()
     mem = inferior.read_memory(buffer, bytes)
     
     # set the img's raw data
     cv.SetData(img, mem)
     mat = np.asarray(img[:,:])
     
     print ("Type: {}".format(mat.dtype))
     print (mat)
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)

        v = gdb.parse_and_eval(args[0])
        strType = gdb.execute("print "+ args[0] + ".type()", False, True)
        # strType contains gdb answers as a string of the form "$2 = 42"
        img = cv.CreateMat(v['rows'], v['cols'], int(strType.split(" ")[2]))

        # convert v['data'] to char*
        char_type = gdb.lookup_type("char")
        char_pointer_type = char_type.pointer()
        buffer = v['data'].cast(char_pointer_type)

        # read bytes from inferior's process memory
        buf = v['step']['buf']
        bytes = buf[0] * v['rows']
        inferior = gdb.selected_inferior()
        mem = inferior.read_memory(buffer, bytes)

        # set the matrix raw data
        cv.SetData(img, mem)

        # save matrix as an xml file and open it with matrix viewer
        cv.Save("/tmp/dump.xml", img, "matrix")
        call(["matrix-viewer", "/tmp/dump.xml"])
Beispiel #13
0
    def invoke(self, arg, from_tty):
        ports = False
        wanted = False
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) > 1 or \
           (len(arg_list) == 1 and arg_list[0] != "ports" and
           arg_list[0] != "wanted"):
            print("usage: ovs_dump_bridge {ports|wanted}")
            return
        elif len(arg_list) == 1:
            if arg_list[0] == "ports":
                ports = True
            else:
                wanted = True

        all_bridges = get_global_variable('all_bridges')
        if all_bridges is None:
            return

        for node in ForEachHMAP(all_bridges,
                                "struct bridge", "node"):
            print("(struct bridge *) {}: name = {}, type = {}".
                  format(node, node['name'].string(),
                         node['type'].string()))

            if ports:
                for port in ForEachHMAP(node['ports'],
                                        "struct port", "hmap_node"):
                    CmdDumpBridgePorts.display_single_port(port, 4)

            if wanted:
                for port in ForEachSHASH(node['wanted_ports'],
                                         typeobj="struct ovsrec_port"):
                    print("    (struct ovsrec_port *) {}: name = {}".
                          format(port, port['name'].string()))
Beispiel #14
0
    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        all_udpifs = get_global_variable('all_udpifs')
        if all_udpifs is None:
            return

        udpifs = dict()
        for udpif in ForEachLIST(all_udpifs, "struct udpif", "list_node"):
            udpifs[udpif['dpif']['full_name'].string()] = udpif

            if len(arg_list) == 0:
                print("(struct udpif *) {}: name = {}, total keys = {}".
                      format(udpif, udpif['dpif']['full_name'].string(),
                             self.count_all_ukeys(udpif)))

        if len(arg_list) == 0:
            return

        if arg_list[0] in udpifs:
            udpif = udpifs[arg_list[0]]
        else:
            try:
                udpif = gdb.parse_and_eval(arg_list[0]).cast(
                    gdb.lookup_type('struct udpif').pointer())
            except Exception:
                udpif = None

        if udpif is None:
            print("Can't find provided udpif address!")
            return

        self.dump_all_ukeys(udpif, 0, "short" in arg_list[1:])
Beispiel #15
0
    def invoke(self, argument, from_tty):
        # parse arguments
        args = gdb.string_to_argv(argument)
        if not args:
            print "Error: Missing arguments"
            print help(self)
            return

        # check for valid layout data
        if issm.jp_data is not None:
            tab_name = args[0]
            tabs = issm.jp_data['Tabs']
            for tab in tabs:
                if tab['name'] == tab_name:
                    if 'command' in tab:
                        json_string = gdb.execute(tab['command'], False, True)
                        print json_string
                        return
                    else:
                        print "Error: No 'command' tag found for tab '" + tab_name + "'"
                        return
            else:
                print "Error: Tab not found"
        else:
            print "Error: Invalid layout file"
Beispiel #16
0
  def invoke(self, arg, from_tty): 
    argv = gdb.string_to_argv(arg)
    
    qTypes = []     
    if( len(argv) > 0 ):
      for a in argv: 
        try: 
          qType = QueueMode.Map[a]
          qTypes.append(qType)
        except KeyError: 
          print("Arg %s does not map to a Queue Type!" % a)
    
    reg = HandleRegistry()
    qToShow = []
    if ( len(qTypes) > 0 ):
      # We will only print info about queues 
      for qType in qTypes: 
        qObjs = reg.FilterBy(qType)
        qToShow.extend(qObjs)
    else: 
      qToShow = reg.FilterBy(None)

    print("Num Queues: %d" % len(qToShow))
    print("%20s %4s %16s %16s" % ("NAME", "CNT", "SEND", "RECEIVE") )
    for q in qToShow:
      self.PrintQueueInfo(q)
Beispiel #17
0
    def invoke(self, _args, from_tty):
        args = gdb.string_to_argv(_args)
        start_node = args[0]

        if len(args) > 1:
            max_iter = int(args[1])
        else:
            max_iter = self.MAX_ITER

        if len(args) > 2:
            lvl = int(args[2])
        else:
            lvl = 0
        
        p_node_t = gdb.lookup_type('node_t').pointer()
        long_t = gdb.lookup_type('long')
        node = gdb.parse_and_eval(start_node)
        print node

        for i in xrange(max_iter):
            nexts = node['next']
            nxt = gdb.Value(nexts[lvl]).cast(long_t)
            nxt = nxt & ~1
            node = gdb.Value(nxt).cast(p_node_t).dereference()
            nexts = node['next']
            print node['k'], node['level'], node['inserting'],
            k = 0
            while k < node['level']:
                print(nexts[k]),
                k+=1
            print("")
Beispiel #18
0
def parse_unwinder_command_args(arg):
    """Internal utility to parse unwinder command argv.

    Arguments:
        arg: The arguments to the command. The format is:
             [locus-regexp [name-regexp]]

    Returns:
        A 2-tuple of compiled regular expressions.

    Raises:
        SyntaxError: an error processing ARG
    """

    argv = gdb.string_to_argv(arg)
    argc = len(argv)
    if argc > 2:
        raise SyntaxError("Too many arguments.")
    locus_regexp = ""
    name_regexp = ""
    if argc >= 1:
        locus_regexp = argv[0]
        if argc >= 2:
            name_regexp = argv[1]
    return (validate_regexp(locus_regexp, "locus"),
            validate_regexp(name_regexp, "unwinder"))
Beispiel #19
0
    def invoke (self, args, from_tty):
        argv = gdb.string_to_argv(args)
        if len(argv) > 1:
            err("Usage: lvmst [L]")

        if len(argv) == 1:
            L = gdbutils.parse_ptr(argv[0], "lua_State*")
            if not L or str(L) == "void":
                raise gdb.GdbError("L empty")
        else:
            L = get_cur_L()

        #print "g: ", hex(int(L['glref']['ptr32']))

        g = G(L)

        vmstate = int(g['vmstate'])
        if vmstate >= 0:
            out("Compiled (trace #%d)\n" % vmstate)

        elif ~vmstate >= LJ_VMST__MAX:
            raise gdb.GdbError("Invalid VM state: ", ~vmstate)

        else:
            #print "vmstate = %d" % vmstate
            out("current VM state: %s\n" % vmstates[~vmstate])
Beispiel #20
0
    def invoke(self, argument, from_tty):
        parser = self.NoexitArgumentParser(prog=self._command,
                description=self.__doc__)
        parser.add_argument('limit', metavar='limit', type=int, nargs='?',
                default=sys.maxsize, help='Only consider [limit] stack frames')
        parser.add_argument('--skip', metavar='N', nargs='?', type=int,
                default=0, help='Skip first [N] stack frames')
        parser.add_argument('--ignore-pc', action='store_true', default=False,
                help='Ignore program counter for frame equivalence')
        parser.add_argument('--show-source', action='store_true', default=False,
                help='Show source file and line info, if available')

        args = parser.parse_args(gdb.string_to_argv(argument))

        traces = []
        for thread in gdb.inferiors()[0].threads():
            traces.append(stacks.StackTrace(thread, args.skip, args.limit,
                args.ignore_pc, args.show_source))

        uniq = {}
        for stack in traces:
            uniq.setdefault(stack,[]).append(stack.gdb_thread_id)

        sorter = lambda d: sorted(d.items(), key=lambda item: len(item[1]),
                reverse=True)

        gdb.write("\n== Printing {} unique stacks from {} threads\n\n".format(
            len(uniq), len(traces)))

        for k, v in sorter(uniq):
            gdb.write("Stack for thread ids {}\n".format(sorted(v)))
            gdb.write(str(k))
            gdb.write("\n\n")

        gdb.flush()
Beispiel #21
0
    def invoke(self, argument, from_tty):
        # parse arguments
        args = gdb.string_to_argv(argument)
        if not args:
            print "Error: Missing arguments"
            print help(self)
            return

        expr = args[0]
        follow_key = args[1]
        print_keys = args[2::]

        # initialize list of elements in linked list
        elements_container = []
        gdb_value_llist = gdb.parse_and_eval(expr)

        # walk linked list
        if is_pointer_init(gdb_value_llist):
            follow_link_list(gdb_value_llist, follow_key, print_keys, elements_container)

            if from_tty:
                print elements_container
            else:
                print ISSM_START + json.dumps(elements_container) + ISSM_END

        else:
            error = "Error: No initialized pointer"
            if from_tty:
                print error
            else:
                print ISSM_START + json.dumps([error]) + ISSM_END
Beispiel #22
0
 def invoke(self, argstr, from_tty):
     argv = gdb.string_to_argv(argstr)
     try:
         args = self.parser.parse_args(argv)
         self.execute(args)
     except SystemExit:
         return
Beispiel #23
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)

        redmagic_info = gdb.execute('info shared redmagic', to_string=True).split('\n')[-2].split()
        redmagic_start = int(redmagic_info[0], 16)
        redmagic_end = int(redmagic_info[1], 16)

        search = argv[0]

        verbose = False

        gdb.execute('break red_asm_resume_eval_block')

        while True:
            rip = int(gdb.parse_and_eval('$rip'))
            if redmagic_start < rip < redmagic_end:
                li = gdb.execute('x/i {}'.format(rip), to_string=True)
                if 'red_asm_resume_eval_block' in li:
                    gdb.execute('si', to_string=True)
                else:
                    gdb.execute('n', to_string=True)
            else:
                regs_info = gdb.execute('info all-registers', to_string=True)
                if search in regs_info:
                    stack = gdb.execute('bt', to_string=True)
                    # filter out methods that are called from the tracer such as memcpy etc
                    if 'red_asm_begin_block' not in stack:
                        sr = '\n\t'.join([r for r in regs_info.split('\n') if search in r])
                        gdb.write('search pattern found in: \n\t{}'.format(sr))
                        return
                gdb.execute('si', to_string=True)
Beispiel #24
0
    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        typeobj = None
        member = None
        dump = False

        if len(arg_list) != 1 and len(arg_list) != 3 and len(arg_list) != 4:
            print("usage: ovs_dump_ovs_list <struct ovs_list *> "
                  "{[<structure>] [<member>] {dump}]}")
            return

        header = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct ovs_list').pointer())

        if len(arg_list) >= 3:
            typeobj = arg_list[1]
            member = arg_list[2]
            if len(arg_list) == 4 and arg_list[3] == "dump":
                dump = True

        for node in ForEachLIST(header.dereference()):
            if typeobj is None or member is None:
                print("(struct ovs_list *) {}".format(node))
            else:
                print("({} *) {} =".format(
                    typeobj,
                    container_of(node,
                                 gdb.lookup_type(typeobj).pointer(), member)))
                if dump:
                    print("  {}\n".format(container_of(
                        node,
                        gdb.lookup_type(typeobj).pointer(),
                        member).dereference()))
Beispiel #25
0
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
	zero = 0
        if len(args) < 1:
            print 'Usage: kgraph <object> [zeropoint]'
            return
        
        x = gdb.parse_and_eval(args[0])
	if len(args) > 1:
       	    zero = int(gdb.parse_and_eval(args[1]))

        data = self.kk.crunch(x)

        (rms, maxi, mini) = self.kk.calcrms(data, zero)
        
        fig = plot.figure()
        ax = fig.add_subplot(111)
        ax.grid(True)
        label = "%s RMS=%f" % (args[0], rms)
        ax.plot(data, '.', label=label)
        ax.plot((maxi, mini), (data[maxi], data[mini]), "kD", label="max-min")
        plot.figtext(0.01,0.01, "RMS=%f max:%d, min:%d, start=%d" % (rms, max(data), min(data), zero))
        print("rms: %f max:%d, min:%d" % (rms, max(data), min(data)))
        print("maxi/mini at ", maxi, mini)
        leg = ax.legend()#label, 'upper right', shadow=False)
        leg.get_frame().set_alpha(0.5)
        plot.show()
Beispiel #26
0
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)

        v = gdb.parse_and_eval(args[0])
        cols, rows = int(v['cols']), int(v['rows'])
        channel, depth = self.decode_flag(v['flags'])
        if depth != CV_8U:
            print("support CV_8U only")
            return

        # conver the v['data'] type to "char*" type
        char_type = gdb.lookup_type("char")
        char_pointer_type = char_type.pointer()
        buffer_ptr = v['data'].cast(char_pointer_type)

        # read bytes from inferior's memory, because
        # we run the opencv-python module in GDB's own process
        # otherwise, we use memory corss processes
        buf = v['step']['buf']
        bytes_cnt = buf[0] * v['rows']
        inferior = gdb.selected_inferior()
        mem = inferior.read_memory(buffer_ptr, bytes_cnt)

        img = np.frombuffer(mem, dtype='uint8', count=int(bytes_cnt))
        img = img.reshape(rows, cols, channel)

        # cv2.startWindowThread()
        cv2.namedWindow('viewer')
        cv2.imshow('viewer', img)
        cv2.waitKey(0)
        cv2.destroyWindow('viewer')
Beispiel #27
0
def _enable_parse_arg(cmd_name, arg):
    """ Internal worker function to take an argument from
    enable/disable and return a tuple of arguments.

    Arguments:
        cmd_name: Name of the command invoking this function.
        args: The argument as a string.

    Returns:
        A tuple containing the dictionary, and the argument, or just
        the dictionary in the case of "all".
    """

    argv = gdb.string_to_argv(arg);
    argc = len(argv)
    if argc == 0:
        raise gdb.GdbError(cmd_name + " requires an argument")
    if argv[0] == "all":
        if argc > 1:
            raise gdb.GdbError(cmd_name + ": with 'all' " \
                               "you may not specify a filter.")
    elif argc != 2:
            raise gdb.GdbError(cmd_name + " takes exactly two arguments.")

    return argv
Beispiel #28
0
    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        all_ofproto_dpifs_by_name = get_global_variable(
            'all_ofproto_dpifs_by_name')
        if all_ofproto_dpifs_by_name is None:
            return

        all_name = dict()
        max_name_len = 0
        for node in ForEachHMAP(all_ofproto_dpifs_by_name,
                                "struct ofproto_dpif",
                                "all_ofproto_dpifs_by_name_node"):

            all_name[node['up']['name'].string()] = node
            if len(node['up']['name'].string()) > max_name_len:
                max_name_len = len(node['up']['name'].string())

        if len(arg_list) == 0:
            for name in sorted(all_name.iterkeys()):
                print("{}: (struct mac_learning *) {}".
                      format(name.ljust(max_name_len),
                             all_name[name]['ml']))

                self.display_ml_summary(all_name[name]['ml'], 4)
        else:
            if not arg_list[0] in all_name:
                print("ERROR: Given bridge name is not known!")
                return

            ml = all_name[arg_list[0]]['ml']
            self.display_ml_summary(ml, 0, "dbg" in arg_list[1:])
            self.display_ml_entries(ml, 0, "hash" in arg_list[1:],
                                    "dbg" in arg_list[1:])
Beispiel #29
0
	def invoke(self, arg, from_tty):
		args = gdb.string_to_argv(arg)
		if len(args) != 1:
			print 'Usage: rblog <object>'
			return
		
		rblog = gdb.parse_and_eval(args[0])
		num_entries = rblog['num_entries']
		num_arguments = rblog['num_arguments']
		entries = rblog['entries']
		index = rblog['index']
		
		if entries[index]['string']:
			r = range(index, num_entries) + range(index)
		else:
			r = range(index)
		
		for i in r:
			entry = entries[i]
			timestamp = int(entry['timestamp'])
			if not entry['string']:
				break
			string = entry['string'].string()
			arguments = [int(entry['arguments'][i]) for i in range(num_arguments)]
			
			try:
				string = string % tuple(arguments[:string.count('%') - 2 * string.count('%%')])
			except:
				pass
			
			print '%8d  %-80s  %s' % (timestamp, string, ' '.join('%08x' % a for a in arguments))
Beispiel #30
0
 def invoke(self, arg, from_tty):
     arg =  gdb.string_to_argv(arg)
     if len(arg) != 2:
         raise gdb.GdbError("Usage: sol_flow print options <node> <options>")
     type = get_node_type_from_exp(arg[0])
     options = gdb.parse_and_eval(arg[1])
     gdb.write(get_type_options_string(type, options))
Beispiel #31
0
    def complete(self, text, word):
        args = gdb.string_to_argv(text)

        if text.endswith(" "):
            args.append("")

        num_args = len(args)

        comp = []
        if (num_args == 0):
            comp.append("help")
            for p in self.svd_file.peripherals:
                comp.append(p)
        elif (num_args == 1):
            for p in self.file.peripherals():
                if (p.startswith(args[0].upper())):
                    comp.append(p)
        else:
            for r in self.register_list(args[0].upper()):
                if r.upper().startswith(args[1].upper()):
                    comp.append(r)

        return comp
def _enable_parse_arg(cmd_name, arg):
    """ Internal worker function to take an argument from
    enable/disable and return a tuple of arguments.

    Arguments:
        cmd_name: Name of the command invoking this function.
        args: The argument as a string.

    Returns:
        A tuple containing the dictionary, and the argument, or just
        the dictionary in the case of "all".
    """

    argv = gdb.string_to_argv(arg)
    argc = len(argv)
    if argv[0] == "all" and argc > 1:
        raise gdb.GdbError(cmd_name + ": with 'all' " \
                          "you may not specify a filter.")
    else:
        if argv[0] != "all" and argc != 2:
            raise gdb.GdbError(cmd_name + " takes exactly two arguments.")

    return argv
Beispiel #33
0
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
        print(args)
        signed = False
        if len(args) < 2:
            print("Usage: %s <object> <length in elements> [signed]" %
                  (self.name))
            return

    # This is ugly, but so be it.
        source = gdb.parse_and_eval(args[0])
        addr = int(str(source), 0)
        length = int(args[1], 0)
        if len(args) > 2 and args[2] == "signed":
            signed = True
        elem_size = source.dereference().type.sizeof
        print("address = %#x, length = %d, signed = %s, size of each :%d" %
              (addr, length, signed, elem_size))
        q = gdb.selected_inferior().read_memory(addr, length * elem_size)
        fmt = "<%d%s" % (length, make_format_string_numeric(elem_size, signed))
        undone = struct.unpack(fmt, q)
        for qq in undone:
            print("%#x (%d)" % (qq, qq))
Beispiel #34
0
    def invoke(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            print(
                "Error: You need to supply at least one argument. See help hpx thread"
            )
            return

        if argv[0] == "restore":
            state.restore()
            return

        if argv[0][0] == '0' and argv[0][1] == 'x':
            thread_id = gdb.Value(int(argv[0], 16))
        else:
            thread_id = gdb.Value(int(argv[0]))

        thread = HPXThread(thread_id)

        print("Switched to HPX Thread 0x%x" % thread_id)
        print(thread.pc_string)

        state.save_context(thread.context.switch())
Beispiel #35
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)
        global curunit

        if len(argv) == 0:
            if curunit is None:
                print('unit: No Unit set.')
            else:
                gdbprint(curunit)
            return

        if len(argv) > 1:
            print('Usage: unit [Unit*|none]')
            return

        if argv[0] == 'none':
            curunit = None
            return
        else:
            unit_type = T('HPHP::Unit').const().pointer()
            curunit = gdb.parse_and_eval(argv[0]).cast(unit_type)

        gdbprint(curunit)
Beispiel #36
0
    def invoke(self, arg, from_tty):
        try:
            argv = gdb.string_to_argv(arg)
            if len(argv) != 1:
                raise Exception("Invalide parameter")

            pathfile = argv[0]
            gdb.write("Svd Loading {} ".format(pathfile))
            parser = SVDParser.for_xml_file(pathfile)
            device = parser.get_device()
            peripherals = dict((peripheral.name, peripheral)
                               for peripheral in device.peripherals)
            GdbSvdGetCmd(device, peripherals)
            GdbSvdSetCmd(device, peripherals)
            GdbSvdInfoCmd(device, peripherals)

        except Exception as inst:
            gdb.write("\n{}\n".format(inst))
            gdb.execute("help svd")
        except IOError:
            gdb.write("\nFailed to load SVD file\n")
        else:
            gdb.write("Done\n")
Beispiel #37
0
 def invoke(self, arg, from_tty):
     args = gdb.string_to_argv(arg)
     if args[0] == "set" or args[0] == "s":
         newBreak = CounterBreakpoint(args[1])
         self.breakpoints[newBreak.number] = newBreak
         self.show()
     elif args[0] == "clear" or args[0] == "c":
         if (len(args) == 2):
             bid = int(args[1])
             print(bid)
             self.clear(bid)
         elif len(args) == 1 or args[1] == "all":
             self.clear()
     elif args[0] == "show":
         self.show()
     elif args[0] == "stop":
         if (len(args) == 3):
             bid = int(args[1])
             count = int(args[2])
             self.setGoal(bid, count)
         elif (len(args) == 2):
             bid = int(args[1])
             self.setGoal(bid)
Beispiel #38
0
    def invokeHelper(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            print("Malformed arguments; see help")
            return

        hdrPtr = gdb.parse_and_eval('(ElmHdr *) ' + argv[0])
        hdr = hdrPtr.dereference()
        grArgs = gdb.parse_and_eval("grArgs")
        maxAllocFrames = int(grArgs['maxTrackFrames'])
        maxFreeFrames = int(grArgs['maxTrackFreeFrames'])

        if self.isValid(hdr['magic']):
            print("Address %s is a header" % argv[0])
        else:
            hdrPtr = gdb.parse_and_eval('*(ElmHdr **)((char *)' + argv[0] + ' - sizeof(void *))')
            hdr = hdrPtr.dereference()
            if self.isValid(hdr['magic']):
                print("Address %s is a user address" % argv[0])
            else:
                print("Address %s doesn't look valid" % argv[0])
                return

        if hdr['magic'] == MAGIC_INUSE:
            print("Address %s is in-use" % argv[0])
        elif hdr['magic'] == MAGIC_FREE:
            print("Address %s is free" % argv[0])

        print("Header:")
        print(hdr)

        trace = hdr['allocBt']

        print("================ Allocation Trace: ================")
        self.dumpSymTrace(trace, 0, maxAllocFrames)
        print("================ Free Trace: ================")
        self.dumpSymTrace(trace, maxAllocFrames + 1, maxFreeFrames)
    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        all_udpifs = get_global_variable('all_udpifs')
        no_count = "no_count" in arg_list

        if all_udpifs is None:
            return

        udpifs = dict()
        for udpif in ForEachLIST(all_udpifs, "struct udpif", "list_node"):
            udpifs[udpif['dpif']['full_name'].string()] = udpif

            if len(arg_list) == 0 or (len(arg_list) == 1
                                      and arg_list[0] == "no_count"):
                print("(struct udpif *) {}: name = {}, total keys = {}".format(
                    udpif, udpif['dpif']['full_name'].string(),
                    self.count_all_ukeys(udpif)
                    if not no_count else "<not counted!>"))

        if len(arg_list) == 0 or (len(arg_list) == 1
                                  and arg_list[0] == "no_count"):
            return

        if arg_list[0] in udpifs:
            udpif = udpifs[arg_list[0]]
        else:
            try:
                udpif = gdb.parse_and_eval(arg_list[0]).cast(
                    gdb.lookup_type('struct udpif').pointer())
            except Exception:
                udpif = None

        if udpif is None:
            print("Can't find provided udpif address!")
            return

        self.dump_all_ukeys(udpif, 0, "short" in arg_list[1:])
Beispiel #40
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)

        redmagic_info = gdb.execute('info shared redmagic', to_string=True).split('\n')[-2].split()
        redmagic_start = int(redmagic_info[0], 16)
        redmagic_end = int(redmagic_info[1], 16)

        verbose = False

        branches_taken = []

        def get_rip():
            return int(gdb.parse_and_eval('$rip'))

        # so that we can determine where it is resuming the trace
        gdb.execute('break red_asm_resume_eval_block')

        current_rip = get_rip()

        while True:
            last_rip = current_rip
            if not verbose and redmagic_start < last_rip < redmagic_end:
                li = gdb.execute('x/i {}'.format(last_rip), to_string=True)
                if 'red_asm_resume_eval_block' in li:
                    gdb.execute('si', to_string=True)
                else:
                    gdb.execute('n', to_string=True)
                current_rip = get_rip()
            else:
                gdb.execute('si', to_string=True)
                current_rip = get_rip()
                if not (0 < current_rip - last_rip < 15):
                    # then we probably have taken a branch or something
                    li = gdb.execute('x/i {}'.format(last_rip), to_string=True)
                    if verbose or ('__tls_get_addr' not in li and '_dl_addr' not in li):
                        #branches_taken.append(li)
                        gdb.write(li)
Beispiel #41
0
class InfoEpcCommand(gdb.Command):
    """For debugging EPC data structue
    Just calling "info epc" prints address of all epc page.
    To print specific epc page, pass its index as a parameter
    e.g.) info epc 0 """

    epcType = 0

    def __init__(self):
        super(InfoEpcCommand, self).__init__("info epc", gdb.COMMAND_STATUS,
                                             gdb.COMPLETE_NONE)

    def invoke(self, arg, from_tty):
        # EPC symbol check
        try:
            self.epcType = gdb.lookup_type('epc_t')
        except RuntimeError, e:
            print "type epc_t nof found"
            return

        # get args, arg_list[0] indicate index
        arg_list = gdb.string_to_argv(arg)

        # get epc first & end page
        epcBase = gdb.parse_and_eval("EPC_BaseAddr")
        epcEnd = gdb.parse_and_eval("EPC_EndAddr")
        if (epcBase == 0 and epcEnd == 0):
            print "EPC is not allocated yet"
            return

        epcBase += 1

        # print epc info
        if (len(arg_list) == 1):
            self._print_epc(epcBase, arg_list[0])
        else:
            self._print_epc_list(epcBase, epcEnd)
Beispiel #42
0
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)

        try:
            variable = gdb.parse_and_eval(argv[0])
        except gdb.error as e:
            print(e)
            return

        point = variable

        if len(argv) > 3:
            raise gdb.GdbError('Usage: pnext [head] [next] [length]')

        next_p = 'next'
        if len(argv) > 1:
            next_p = argv[1]
            try:
                check = point[next_p].dereference()
            except gdb.error as e:
                print("Oops! ", e)
                return

        count = 50
        if len(argv) > 2:
            try:
                count = int(argv[2])
            except ValueError:
                print("Oops!  That was no valid number", argv[2])
                return

        while point:
            if count == 0:
                break
            print(point.dereference())
            point = point[next_p]
            count -= 1
Beispiel #43
0
    def invoke(arg, from_tty):
        """
        arg is:
        <start_bbcount> <end_bbcount> <bbcount_interval>
        E.g. 0 1000 1
        means sample every basic block from 1 to 1000.
        """
        with udb.time.auto_reverting():
            functions = defaultdict(lambda: 0)

            args = gdb.string_to_argv(arg)

            start_bbcount = int(args[0])
            end_bbcount = int(args[1])
            interval = int(args[2])

            with debugger_utils.temporary_parameter("print address", False):
                for current_bbcount in range(start_bbcount, end_bbcount + 1,
                                             interval):
                    udb.time.goto(current_bbcount)
                    frame = gdb.newest_frame()
                    # Create list of functions in the backtrace
                    trace_functions = []
                    while frame is not None:
                        if frame.name() is not None:
                            trace_functions.append(frame.name())
                        else:
                            # If no symbol for function use pc
                            trace_functions.append(str(frame.pc()))
                        frame = frame.older()
                    # Concatenate functions in backtrace to create key
                    key = "->".join(reversed(trace_functions))
                    functions[key] += 1

        # Now print what we've found...
        for function in functions:
            print("{} {}".format(function, str(functions[function])))
    def invoke(self, arg, from_tty):
        ports = False
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) > 1 or \
           (len(arg_list) == 1 and arg_list[0] != "ports"):
            print("usage: ovs_dump_dp_netdev [ports]")
            return
        elif len(arg_list) == 1:
            ports = True

        dp_netdevs = get_global_variable('dp_netdevs')
        if dp_netdevs is None:
            return

        for dp in ForEachSHASH(dp_netdevs, typeobj=('struct dp_netdev')):

            print("(struct dp_netdev *) {}: name = {}, class = "
                  "(struct dpif_class *) {}".format(dp, dp['name'].string(),
                                                    dp['class']))

            if ports:
                for node in ForEachHMAP(dp['ports'], "struct dp_netdev_port",
                                        "node"):
                    CmdDumpDpNetdevPorts.display_single_port(node, 4)
Beispiel #45
0
    def invokeHelper(self, arg, from_tty):
        argv = gdb.string_to_argv(arg)
        if len(argv) != 0:
            print("Malformed arguments; see help")
            return

        grArgs = gdb.parse_and_eval("grArgs")
        numSlots = int(grArgs['numSlots'])
        maxAllocFrames = int(grArgs['maxTrackFrames'])
        maxFreeFrames = int(grArgs['maxTrackFreeFrames'])
        memSlots = gdb.parse_and_eval("memSlots")

        print("===== START TRACES =====")
        for slotNum in range(0, numSlots):
            memBins = memSlots[slotNum]['memBins']
            numBins = int(gdb.parse_and_eval('sizeof(((MemSlot *)0x0)->memBins)/sizeof(((MemSlot *)0x0)->memBins)[0]'))
            for binNum in range(0, numBins):
                memBin = memBins[binNum]
                hdr = memBin['headInUse']
                while hdr != 0x0:
                    csvTrace = self.getTraceCsv(hdr['allocBt'], 0, maxAllocFrames)
                    elmSize = hdr['usrDataSize']
                    print(str(elmSize) + "," + csvTrace)
                    hdr = hdr['next']
Beispiel #46
0
 def invoke(self, arg, from_tty):
     self.__repeat_count_hack(arg, from_tty)
     args = gdb.string_to_argv(arg)
     size = 16
     if args:
         size = int(args[0])
     typ = gdb.lookup_type("void").pointer()
     #with clippy() as clp:
     fmtdbg = FmtDbg()
     idx = 1 + size * self.repeat_count
     for i in range(idx, idx + size):
         arg_s, arg_v = fmtdbg.fmtstr_arg(i, typ, pad=3)
         line = f"{GREEN}\"%{i:03}$p\"{RESET}: "
         line += f"{BLUE}{arg_s}{RESET}"
         if arg_v.address:
             line += f" (*{hex(arg_v.address)})"
         line += f": {YELLOW}{int(arg_v):#0{typ.sizeof*2+2}x}{RESET}"
         if fmt_get_location_from_symbol(int(arg_v)):
             symb, offset = fmt_get_location_from_symbol(int(arg_v))
             line += f" {PURPLE}<&{symb}"
             if offset:
                 line += f"+{offset}"
             line += f">{RESET}"
         print(line)
Beispiel #47
0
    def complete(self, text, word):
        args = gdb.string_to_argv(text)
        num_args = len(args)
        if text.endswith(" "):
            num_args += 1
        if not text:
            num_args = 1

        # "svd_load <tab>" or "svd_load ST<tab>"
        if num_args == 1:
            prefix = word.lower()
            return [
                vendor for vendor in self.vendors
                if vendor.lower().startswith(prefix)
            ]
        # "svd_load STMicro<tab>" or "svd_load STMicro STM32F1<tab>"
        elif num_args == 2 and args[0] in self.vendors:
            prefix = word.lower()
            filenames = self.vendors[args[0]]
            return [
                fname for fname in filenames
                if fname.lower().startswith(prefix)
            ]
        return gdb.COMPLETE_NONE
Beispiel #48
0
    def complete(self, text, word):
        if not self.device:
            return gdb.COMPLETE_NONE
        args = gdb.string_to_argv(text)

        # Skip over the /x in "svd_show/x"
        if text.startswith("/"):
            options = args[0][1:]
            args = args[1:]
            if text.startswith("/"+options):
                text = text[1+len(options):]
            if word.startswith(options):
                word = ""

        num_args = len(args)
        if text.endswith(" "):
            num_args += 1
        if not text:
            num_args = 1

        if num_args == 1:
            peripheral_names = [peripheral.name.upper() for peripheral in self.device.peripherals]
            if word:
                prefix = word.upper()
                return [name for name in peripheral_names if name.startswith(prefix)]
            else:
                return peripheral_names
        elif num_args == 2 and args[0].upper() in self.peripherals:
            periph_name = args[0].upper()
            periph = self.peripherals[periph_name]
            register_names = [register.name for register in periph.registers]
            if word:
                prefix = word.upper()
                return [name for name in register_names if name.upper().startswith(prefix)]
            return register_names
        return gdb.COMPLETE_NONE
Beispiel #49
0
    def invoke (self, arg, from_tty):
        try:
            if not self.device:
                raise gdb.GdbError("Use svd_load to load an SVD file first")
                return

            args = gdb.string_to_argv(arg)

            # Extract formatting options
            options = ""
            if args and args[0].startswith("/"):
                options = args[0]
                args = args[1:]

            if len(args) >= 1:
                if args[0] not in self.peripherals:
                    raise gdb.GdbError("Invalid peripheral name")
                    return
                peripheral = self.peripherals[args[0]]
                if len(args) == 1:
                    print("%s @ 0x%08x" % (peripheral.name, peripheral.base_address))
                    if peripheral.registers:
                        width = max(len(reg.name) for reg in peripheral.registers) 
                        for register in peripheral.registers:
                            self.dump_register(peripheral, register, width, options)
                elif len(args) == 2:
                    for register in peripheral.registers:
                        if register.name == args[1]:
                            self.dump_register(peripheral, register, 0, options)
                            break
                    else:
                        raise gdb.GdbError("Invalid register name")
            else:
                raise gdb.GdbError("Usage: svd_show[/[x|b]fi] peripheral-name [register-name]")
        except KeyboardInterrupt:
            pass
Beispiel #50
0
class InfoEpcmCommand (gdb.Command):
    """For debugging EPCM data structue
    Calling info epcm prints EPCM address and its contents.
    To designate start and end index, type "info epcm start end".
    e.g.) info epcm 0 3 will print epcm[0]~ epcm[3]. """

    def __init__ (self):
        super (InfoEpcmCommand, self).__init__ ("info epcm",
                                                gdb.COMMAND_STATUS,
                                                gdb.COMPLETE_NONE)

    def invoke (self, arg, from_tty):
	# EPCM symbol check
	try:
	    epcmType = gdb.lookup_type('epcm_entry_t')
	except RuntimeError, e:
	    print "type epcm_entry_t nof found"
	    return 	

	# get args
	arg_list = gdb.string_to_argv(arg)
	if len(arg_list) < 2:
	    start = 0
	    end = numEpcm
	else:
	    start = int(arg_list[0], 10)
	    end = int(arg_list[1], 10)
	    if end > numEpcm:
	    	end = numEpcm
	    if start < 0:
		start = 0

	# get epcm object
	epcmObj = gdb.parse_and_eval("epcm")
	# print epcm info
	self._print_epcm(epcmObj, start, end)
    def invoke(self, args, from_tty):
        argv = gdb.string_to_argv(args)
        if len(argv) == 0:
            raise gdb.GdbError('输入参数数目不对,help print-array 以获得用法')

        self.type_lookup()

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

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

        if not a:
            print("ngx_array_t point empty")
            return

        print("ngx_array_t alloc size: %d" % int(a['nalloc']))
        print("ngx_array_t used size: %d" % int(a['nelts']))
        print("ngx_array_t elts size: %d" % int(a['size']))
        print("ngx_array_t every elts:")

        if len(argv) == 1:
            print("ngx_array_t just first elts pointer: %s" % str(a['elts']))

        elif len(argv) == 2:
            # elt_type = gdb.lookup_type(argv[1])
            # e = gdb.Value(int(a['elts'], 16)).cast(elt_type)
            e = a['elts'].cast(gdb.lookup_type('u_char').point())
            elt_type = argv[1]
            elt_size = int(a['size'])
            for i in xrange(a['nelts']):
                comm = 'p ' + argv[0] + '(' + str(e + i * elt_size) + ')'
                print(comm)
                gdb.execute(comm)
 def invoke(self, arg, from_tty):
     """ Parsing arguments, invoking printing.
     You can print all theeads of current task (no argument to command),
     All threads of current task xnu-threads current
     All user threads - xnu-threads user
     All threads whithin the system - xnu-threads
     All threads of specific task - xnu-threads ${task_ptr}
     """
     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:
         argv = gdb.string_to_argv(arg)
         if len(argv) == 0:
             self.print_all_threads(is_global=True)
         elif len(argv) == 1:
             if argv[0] == "user":
                 self.print_all_threads(user_only=True, is_global=True)
             elif argv[0] == "current":
                 task = sys_info.get_current_task_ptr()
                 self.print_all_threads(task=task)
             else:
                 try:
                     requested_task = int(argv[0], 0)
                     if sys_info.is_valid_ptr(requested_task):
                         if not types.is_task_exist(requested_task):
                             gdb.write(f"\nRequested task {argv[0]} do not exist"
                                       f" in the tasks list of the system!\n\n\n")
                         self.print_all_threads(task=requested_task)
                 except Exception:
                     gdb.write("\nUsage: xnu-threads ${TASK_PTR}\n")
         else:
             gdb.write("\nUsage: xnu-threads ${TASK_PTR}\n")
     except Exception:
         raise gdb.GdbError(traceback.format_exc())
Beispiel #53
0
    def invoke(self, arg, from_tty):
        if self.init == False:
            self.lazy_init()

        argv = gdb.string_to_argv(arg)
        args = None
        try:
            args = self.parser.parse_args(argv)
        except:
            return None

        saved_stdout = None
        if args.o:
            saved_stdout = sys.stdout
            sys.stdout = open(args.o[0], "w+")

        try:
            self.handle_command(args)
        except Exception as e:
            print(f"Exception: {str(e)}")
        finally:
            if saved_stdout:
                sys.stdout.close()
                sys.stdout = saved_stdout
Beispiel #54
0
    def invoke(self, args, from_tty):
        print(repr(args))
        arg_list = gdb.string_to_argv(args)

        chars_only = True

        if len(arg_list) == 2:
            addr_arg = arg_list[0]
            chars_only = True if args[1] == '-c' else False
        else:
            addr_arg = args

        if addr_arg.startswith('0x'):
            addr = int(addr_arg, 16)
        else:
            addr = int(addr_arg)

        # assume that paging will cut in and the user will quit at some point:
        size = 32
        while True:
            hd = hexdump_as_bytes(addr, size, chars_only=chars_only)
            print('%s -> %s %s' %
                  (fmt_addr(addr), fmt_addr(addr + size - 1), hd))
            addr += size
Beispiel #55
0
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)

        frame = "$rbp"
        if len(args) > 0:
            frame = args[0]

        depth = 30
        if len(args) > 1:
            depth = int(args[1])

        for i in range(depth-1, -1, -1):
            ret = gdb.parse_and_eval(f"*(uint64_t*)({frame} + 8)")
            frame = gdb.parse_and_eval(f"*(uint64_t*)({frame})")

            name = ""
            block = gdb.block_for_pc(int(ret))
            if block:
                name = block.function or ""

            print("{:016x} {}".format(int(ret), name))

            if frame == 0 or ret == 0:
                return
Beispiel #56
0
    def invoke(self, args, from_tty):
        self.dont_repeat()
        argv = gdb.string_to_argv(args)
        argc = len(argv)

        if not (0 <= argc <= 2):
            message.error("Invalid number of arguments")
            return None

        if argc == 0:
            print(message.titlify("PWNGEF configuration settings"))
            self.print_settings()
            return None

        if argc == 1:
            prefix = argv[0]
            names = list(
                filter(lambda x: x.startswith(prefix),
                       pwngef.config.__config__.keys()))
            if names:
                if len(names) == 1:
                    print(
                        message.titlify(
                            "PWNGEF configuration setting: {:s}".format(
                                names[0])))
                    self.print_setting(names[0], verbose=True)
                else:
                    print(
                        message.titlify(
                            "PWNGEF configuration settings matching '{:s}'".
                            format(argv[0])))
                    for name in names:
                        self.print_setting(name)
            return None
        self.set_setting(argc, argv)
        return None
Beispiel #57
0
    def invoke(self, argv_str, _from_tty):
        args = gdb.string_to_argv(argv_str)

        if len(args) not in (1, 2):
            print('usage: print-avs-list expr [limit=10]\n'
                  '  expr - an expression that avaluates to a valid AVS_LIST element pointer\n'
                  '  limit - number of elements to display; a value <= 0 means no limit')
            return

        expr = args[0]

        limit = int(args[1]) if len(args) > 1 else 0
        if limit <= 0:
            limit = None

        val = gdb.parse_and_eval(expr)
        if val is None:
            print('cannot evaluate expression: ' + expr)
            return

        if val == 0:
            print('(empty list)')
        else:
            self._print_list(val, limit)
Beispiel #58
0
    def invoke(self, args, from_tty):
        argv = [gdb.parse_and_eval(arg) for arg in gdb.string_to_argv(args)]

        if len(argv) == 0:
            if not self.bcpos:
                print 'hhx: No bytecode specified.'
                return
        elif len(argv) == 1:
            if argv[0] > 0xffffffff:
                self.bcpos = argv[0]
                self.bcoff = 0
                self.count = 1
            else:
                self.count = int(argv[0])
        else:
            self.bcpos = argv[0]
            self.bcoff = 0
            self.count = int(argv[1])

        bctype = gdb.lookup_type('HPHP::Op').const().pointer()
        self.bcpos = self.bcpos.cast(bctype)

        op_names = gdb.parse_and_eval(
            "(char **)*(uint32_t*)('HPHP::opcodeToName(HPHP::Op)' + 10)")

        for i in xrange(0, self.count):
            instr = HHBC.instr_info(self.bcpos)

            idx = as_idx(self.bcpos.dereference())
            out = "[%d] %s" % (self.bcoff, op_names[idx].string())
            for imm in instr['imms']:
                out += ' <' + str(imm) + '>'
            print out

            self.bcpos += instr['len']
            self.bcoff += instr['len']
Beispiel #59
0
    def invoke(self, argument, from_tty):
        self.dont_repeat()

        period = 0.1

        args = gdb.string_to_argv(argument)

        if len(args) > 0:
            try:

                period = int(args[0])
            except ValueError:
                print("Invalid number \"%s\"." % args[0])
                return

        def breaking_continue_handler(event):
            sleep(period)
            os.kill(gdb.selected_inferior().pid, signal.SIGINT)

#        call_chain_frequencies = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

        top = Function("Top", 2)
        sleeps = 0

        threads = {}
        for i in range(0, 200):
            gdb.events.cont.connect(breaking_continue_handler)
            gdb.execute("continue", to_string=True)
            gdb.events.cont.disconnect(breaking_continue_handler)

            for inf in gdb.inferiors():
                inum = inf.num
                for th in inf.threads():
                    thn = th.num
                    th.switch()
                    #              call_chain_frequencies[inum][thn][get_call_chain()] += 1
                    frame = gdb.newest_frame()
                    while (frame.older() != None):
                        frame = frame.older()
#              top.inverse_add_frame(frame);
#              top.add_frame(gdb.newest_frame())
                    if thn not in threads:
                        threads[thn] = Function(str(thn), 2)
                    threads[thn].inverse_add_frame(frame)

            sleeps += 1
            gdb.write(".")
            gdb.flush(gdb.STDOUT)

        print("")
        for thn, function in sorted(threads.items()):
            print("")
            print("Thread: %s" % thn)
            print("")
            function.print_percent("", function.get_samples())


#        top.print_percent("", top.get_samples())

#        print("\nProfiling complete with %d samples." % sleeps)
#        for inum, i_chain_frequencies in sorted(call_chain_frequencies.iteritems()):
#            print ""
#            print "INFERIOR NUM: %s" % inum
#            print ""
#            for thn, t_chain_frequencies in sorted (i_chain_frequencies.iteritems()):
#                print ""
#                print "THREAD NUM: %s" % thn
#                print ""
#
#                for call_chain, frequency in sorted(t_chain_frequencies.iteritems(), key=lambda x: x[1], reverse=True):
#                    print("%d\t%s" % (frequency, '->'.join(str(i) for i in call_chain)))
#
#        for call_chain, frequency in sorted(call_chain_frequencies.iteritems(), key=lambda x: x[1], reverse=True):
#            print("%d\t%s" % (frequency, '->'.join(str(i) for i in call_chain)))

        pid = gdb.selected_inferior().pid
        os.kill(pid,
                signal.SIGSTOP)  # Make sure the process does nothing until
        # it's reattached.
        gdb.execute("detach", to_string=True)
        gdb.execute("attach %d" % pid, to_string=True)
        os.kill(pid, signal.SIGCONT)
        gdb.execute("continue", to_string=True)
Beispiel #60
0
    def invoke(self, argstr, from_tty):
        '''
        Called when this Command is invoked from GDB. Prints classification of
        Inferior to GDB's STDOUT.
        
        Note that sys.stdout is automatically redirected to GDB's STDOUT.
        See GDB Python API documentation for details
        '''

        # Note that OptionParser is configured to work without
        # sys.argv and to minimize the cases where OptionParser
        # calls sys.exit(), which kills the parent GDB process
        op = OptionParser(prog=self._cmdstr,
                          add_help_option=False,
                          description="type 'help exploitable' for "
                          "description. WARNING: typing an invalid "
                          "option string may cause GDB to exit.")
        op.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="print analysis info from the Inferior")
        op.add_option("-p",
                      "--pkl-file",
                      dest="pkl_file",
                      help="pickle exploitability classification object and "
                      "store to PKL_FILE")
        op.add_option("-h",
                      "--help",
                      action="store_true",
                      dest="help",
                      default=False,
                      help="Print this message")
        (opts, args) = op.parse_args(gdb.string_to_argv(argstr))
        if opts.help:
            # Print help manually b/c Default OptionParser help calls sys.exit
            op.print_help()
            return
        self._options = opts

        try:
            target = gdb_wrapper.getTarget()
        except gdb_wrapper.GdbWrapperError as e:
            raise gdb.GdbError(e)

        c = classifier.getClassification(target)
        if self._options.pkl_file:
            path = os.path.expanduser(self._options.pkl_file)
            pickle.dump(c, file(path, "wb"))
            return

        if self._options.verbose:
            print "'exploitable' version %s" % versions.exploitable_version
            print " ".join([str(i) for i in os.uname()])
            print "Signal si_signo: %s Signal si_addr: %s" % \
             (target.si_signo(), target.si_addr())
            print "Nearby code:"
            self.print_disassembly()
            print "Stack trace:"
            print target.backtrace()
            print "Faulting frame: %s" % target.faulting_frame()

        print c