Example #1
0
def createWatch(inf):
    debugMsg('hit createWatch with inf ' + str(inf))
    wdata = ''
    addr = ''
    leng = ''
    lab = ''
    filename = 'inf' + str(inf) + '.watch'
    f = None
    try:
        f = open(filename, 'r')
        try:
            wdata = f.read()
        finally:
            f.close()
    except IOError:
        raise gdb.error('*****Error opening file: ' + filename)
    match = re.match(r"[*]+checkAddr:(\w+)\n[*]+checkLen:(\w+)\n" +
                     "[*]+checkLab:(\w+)\n",
                     wdata)
    if match is not None:
        addr = match.group(1).strip()
        leng = match.group(2).strip()
        lab  = match.group(3).strip()
    else:
        raise gdb.error('*****Error matching re in watch file: ' + filename)
    watches.append(qdWatchpoint(addr, lab, leng, inf))
 def __call__(self, obj, row_idx, col_idx):
     n_rows = obj["n_rows"]
     n_cols = obj["n_cols"]
     if row_idx < 0 or row_idx >= n_rows:
         raise gdb.error(
             "Row index out of bounds -> It must be between 0 and {}".
             format(n_rows - 1))
     if col_idx < 0 or col_idx >= n_cols:
         raise gdb.error(
             "Column index out of bounds -> It must be between 0 and {}".
             format(n_cols - 1))
     return obj["mem"][col_idx * n_rows + row_idx]
    def invoke(self, obj: gdb.Value, type: gdb.Value) -> gdb.Value:
        try:
            type_string = type.string()
        except gdb.error:
            raise gdb.error('the second argument must be literal string')

        try:
            dispatch = self._dispatch[parse_type(obj)]
        except KeyError:
            raise gdb.error(
                'the first argument must be of supported types: interface, literal address, void*'
            )

        return dispatch(obj, type_string)
Example #4
0
def hex_dump(address_str, size=16):
    '''Output memory region in hex.'''

    if size <= 0:
        raise gdb.error('Size must be positive')

    address = gdb_eval(address_str, uint_t)
    start_address = address & ~0xf
    end_address = (address + size + 0xf) & ~0xf

    chars = ''

    for cur_address in range(start_address, end_address):

        if cur_address & 0xf == 0:
            gdb.write('0x%08x: ' % cur_address)
        elif cur_address & 0xf == 0x4 or cur_address & 0xf == 0xc:
            gdb.write(' ')
        elif cur_address & 0xf == 0x8:
            gdb.write('- ')

        if cur_address < int(address) or cur_address >= int(address + size):
            gdb.write('** ')
            chars += ' '
        else:
            byte = int(gdb.Value(cur_address).cast(byteptr_t).dereference())
            gdb.write('%02x ' % byte)
            if byte >= 32 and byte < 128:
                chars += chr(byte)
            else:
                chars += '.'

        if cur_address & 0xf == 0xf:
            gdb.write(' | %s\n' % chars)
            chars = ''
Example #5
0
def tagged_field(tagged_value, field_name, reinterpret=True):
    """
    Look for a field in a tagged record's own and all its inherited fields.

    This is useful because we see tagged records in GDB as a record that
    contains another record (for fields from the parent type) that contains
    another record, etc.

    :param gdb.Value tagged_value: Can be either a tagged record or an access
        to a tagged record.
    :param str field_name: Name of the field to look up.
    :param bool reinterpret: If True, re-interpret `tagged_value` according to
        its dynamic type.
    :rtype: gdb.Value
    """
    tagged_value = (reinterpret_tagged(tagged_value)
                    if reinterpret else auto_deref_tagged(tagged_value))

    if tagged_value.type.code != gdb.TYPE_CODE_STRUCT:
        raise TypeError('Input type is not tagged')

    while True:
        try:
            return tagged_value[field_name]
        except gdb.error:
            pass
        try:
            tagged_value = tagged_value['_parent']
        except gdb.error:
            raise gdb.error('There is no member {}'.format(field_name))
Example #6
0
    def __init__(self, hp):
        super().__init__()
        ahp = hp.split(":")
        host = "0.0.0.0"
        lport = 0
        if (len(ahp) == 1):
            lport = int(ahp[0])
        elif (len(ahp) == 2):
            host = ahp[0]
            lport = int(ahp[1])
        else:
            raise gdb.error("Invalid host:lport/lport argument %s" % hp)
        # open a listen lport, find a way to accept it asynchronously (threading??) and output to all of them
        # host None means 0.0.0.0


#        print("host = '%s'" % host )
#        print("lport = '%s'" % lport )
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, lport))
        sock.listen(1)
        self.sock = sock
        self.host = host
        self.port = lport
        self.enabled = False
        self.targets = []
        self.start()
Example #7
0
    def _vector_item(self, vector, index):
        last = int(vector['size'])
        if index < 1 or last < index:
            raise gdb.error('Out of bounds index')

        array = vector['e'].dereference()
        return array[index]
Example #8
0
File: ssh.py Project: PlasmaHH/vdb
def csum( argv ):
    key = argv[0]
    cs = argv[1]
    if( key.find(":") == -1 ):
        raise gdb.error("ssh csum <key> <csum> : the key parameter must have the form host:file but we found no ':'")
    global csum_cache
    csum_cache[key] = (cs,None)
 def __call__(self, obj, row_idx, col_idx, slice_idx):
     n_rows = obj["n_rows"]
     n_cols = obj["n_cols"]
     n_slices = obj["n_slices"]
     num_elem_per_slice = n_rows * n_cols
     if row_idx < 0 or row_idx >= n_rows:
         raise gdb.error(
             "Row index out of bounds -> It must be between 0 and {}".
             format(n_rows - 1))
     if col_idx < 0 or col_idx >= n_cols:
         raise gdb.error(
             "Column index out of bounds -> It must be between 0 and {}".
             format(n_cols - 1))
     if slice_idx < 0 or slice_idx >= n_slices:
         raise gdb.error(
             "Slice index out of bounds -> It must be between 0 and {}".
             format(n_slices - 1))
     return obj["mem"][slice_idx * num_elem_per_slice + col_idx * n_rows +
                       row_idx]
Example #10
0
    def __init__(self, tty_name):
        super().__init__()
        self.tty = tty_name

        f = self.try_open(tty_name)
        if (f is None):
            f = self.try_open("/dev/" + tty_name)
        if (f is None):
            raise gdb.error(f"Could not open {tty_name} ({fn})")
        self.file = f
Example #11
0
def call_dashboard(argv):
    # type: tmux,port,tty
    # subcommands: list,enable,disable,erase
    if (len(argv) == 0):
        raise gdb.error(cmd_dashboard.__doc__)


#    print("argv = '%s'" % argv )
    if ("tty".startswith(argv[0])):
        if (len(argv) < 3):
            raise gdb.error("dashboard tty, need at least 2 parameters")
        tgt = tty(argv[1])
        add_board(tgt, argv[2:])
    elif ("null".startswith(argv[0])):
        tgt = null()
        add_board(tgt, argv[1:])
    elif ("tmux".startswith(argv[0])):
        if (len(argv) < 3):
            raise gdb.error("dashboard tmux, need at least 2 parameters")
        tgt = tmux(argv[1])
        add_board(tgt, argv[2:])
    elif ("port".startswith(argv[0])):
        if (len(argv) < 3):
            raise gdb.error("dashboard port, need at least 2 parameters")
        tgt = port(argv[1])
        add_board(tgt, argv[2:])
    elif ("delete".startswith(argv[0])):
        del_board(argv[1])
    elif ("show".startswith(argv[0])):
        show_dashboard()
    elif ("enable".startswith(argv[0])):
        trigger_dashboard(argv[1], True)
    elif ("disable".startswith(argv[0])):
        trigger_dashboard(argv[1], False)
    elif ("modify".startswith(argv[0])):
        modify_board(argv[1:])
    elif ("cls".startswith(argv[0])):
        trigger_cls(argv[1], True)
    elif ("nocls".startswith(argv[0])):
        trigger_cls(argv[1], False)
    else:
        print("%s? What do you mean?" % argv[0])
Example #12
0
    def invoke(self, thread, argument, from_tty=False):
        sections = gdb.execute('info target', to_string=True)
        address = None
        for match in self._text_exp.finditer(sections):
            if match.group('section') == '.text':
                address = abs(long(match.group('start'), 16))
                break

        if address is not None:
            gdb.Breakpoint('*0x%x' % address)
        else:
            raise gdb.error('Unable to locate .text section!')
Example #13
0
    def invoke(self, thread, argument, from_tty=False):
        sections = gdb.execute('info target', to_string=True)
        address = None
        for match in self._text_exp.finditer(sections):
            if match.group('section') == '.text':
                address = abs(long(match.group('start'), 16))
                break

        if address is not None:
            gdb.Breakpoint('*0x%x' % address)
        else:
            raise gdb.error('Unable to locate .text section!')
Example #14
0
    def token(self, token_no):
        """
        Retreive the token number "token_no" in this TDH.

        :rtype: Token
        """
        last_token = int(self.value['tokens']['size'])
        if token_no < 1 or last_token < token_no:
            raise gdb.error('Out of bounds token number')

        tokens_array = self.value['tokens']['e'].dereference()
        return Token(self, tokens_array[token_no])
Example #15
0
 def _update(self):
     val = self.val
     arr_type = str(val.type.unqualified().strip_typedefs())
     if re.search('(?:\[\])+', arr_type):
         raise gdb.error("Missing array dimensions. "
                         "All array dimensions must be "
                         "declared as const. ")
     match = self.pattern.search(arr_type)
     bounds = match.group()[1:-1]
     bounds = bounds.split('][')
     bounds = bounds[0]
     self.bounds = [int(bounds)]
     self.val = self.deref(val, [0])
Example #16
0
 def _update(self):
     val = self.val
     arr_type = str(val.type.unqualified().strip_typedefs())
     if re.search('(?:\[\])+',arr_type):
         raise gdb.error("Missing array dimensions. "
                         "All array dimensions must be "
                         "declared as const. ")
     match = self.pattern.search(arr_type)
     bounds = match.group()[1:-1]
     bounds = bounds.split('][')
     bounds = bounds[0]
     self.bounds = [int(bounds)]
     self.val = self.deref(val,[0])
    def __call__(self, obj, slice_idx):
        n_rows = obj["n_rows"]
        n_cols = obj["n_cols"]
        n_slices = obj["n_slices"]
        num_elem_per_slice = n_rows * n_cols

        if slice_idx < 0 or slice_idx >= n_slices:
            raise gdb.error(
                "Slice index out of bounds -> It must be between 0 and {}".
                format(n_slices - 1))

        slice_type = self.get_slice_type(obj)

        return (obj["mem"][slice_idx * num_elem_per_slice]).cast(slice_type)
Example #18
0
    def invoke(self, arg, from_tty):
        if not gdb_running_under_rr():
            raise gdb.error('reverse-callback requires debugging under rr: ' +
                            'https://rr-project.org/')

        # Find the stack frame which extracts the bind state from the task.
        bind_state_frame = find_nearest_frame_matching(
            gdb.selected_frame(), lambda frame: frame.function() and re.match(
                '^base::internal::Invoker<base::internal::BindState<.*>' +
                '::RunOnce\(base::internal::BindStateBase\*\)$',
                frame.function().name))
        if bind_state_frame is None:
            raise Exception(
                'base::internal::Invoker frame not found; are you in a callback?'
            )
        bind_state_frame.select()

        # Disable all existing breakpoints.
        was_enabled = []
        for breakpoint in gdb.breakpoints():
            was_enabled.append(breakpoint.enabled)
            breakpoint.enabled = False

        # Break on the initialization of the BindState.
        storage_address = gdb.parse_and_eval('storage')
        watchpoint = gdb.Breakpoint('*' + str(storage_address),
                                    gdb.BP_WATCHPOINT)

        # Find the construction.
        gdb.execute('reverse-continue')

        # Restore breakpoints
        watchpoint.delete()
        for breakpoint, enabled in zip(gdb.breakpoints(), was_enabled):
            breakpoint.enabled = enabled

        # Find the stack frame which created the BindState.
        def in_bindstate(frame):
            return frame.function() and frame.function().name.startswith(
                'base::internal::BindState<')

        creation_frame = find_nearest_frame_matching(
            find_nearest_frame_matching(gdb.selected_frame(), in_bindstate),
            lambda frame: not in_bindstate(frame))

        # The callback creates the bindstate, step up once more to get the creator
        # of the callback.
        creation_frame.older().select()
Example #19
0
def tagged_field(record_value, field_name):
    """
    Helper to look for a field in a tagged record.

    This is useful because we see tagged records in GDB as a record that
    contains another record (for fields from the parent type) that contains
    another record, etc.
    """
    while True:
        try:
            return record_value[field_name]
        except gdb.error:
            pass
        try:
            record_value = record_value['_parent']
        except gdb.error:
            raise gdb.error('There is no member {}'.format(field_name))
Example #20
0
File: ssh.py Project: PlasmaHH/vdb
def gdbserver( s, argv ):
    print("Searching for port to tunnel over ssh … ",end="")
    s.call("netstat -naput | egrep \"VERBUNDEN|LISTEN|TIME_WAIT\" | awk '{ print $4}'")
    s.fill(0.5)
    ports = s.read()
    ports = ports.splitlines()

    lports = subprocess.check_output(["sh","-c","netstat -npatu | egrep \"VERBUNDEN|LISTEN|TIME_WAIT\" | awk '{print $4}'"])
    lports = lports.decode("utf-8")
    lports = lports.splitlines()


    ports += lports
#    candports = set(range(6000,6020))
    candports = set(valid_ports.elements)

#    print("ports = '%s'" % ports )
    for port in ports:
        try:
            p = int(port.split(":")[-1])
#            print("p = '%s'" % p )
            candports.remove(p)
        except:
            pass
#    print("candports = '%s'" % candports )
    if( len(candports) == 0 ):
        raise gdb.error("No suitable port found among the candidates of %s" % valid_ports.elements )
    gport = candports.pop()
    print(f"using port {gport}")
    gs = ssh_connection(s.host,[ "-L" f"{gport}:localhost:{gport}" ] )
    argv = [ f"localhost:{gport}" ] + argv
#    print("gdbserver " + " ".join(argv))
    gs.call(f"{gdbserver_cmd.value} " + " ".join(argv) )
    gs.fill(0.5)
    r=gs.read()
    print("r = '%s'" % r )
#    print(f"target remote localhost:{gport}")
#    time.sleep(2)
    print("Setting target remote…")
    gdb.execute(f"target remote localhost:{gport}")
#    gdb.execute(f"target extended-remote localhost:{gport}")
    print("Attached to remote process. Use 'detach' to end debugging.")
    return gs
Example #21
0
    def _get_current_language():
        '''
            We have some C files we want to compile. However, this doesn't 
            work if we're getting checkpoints for a fortran benchmark. So, we
            need to retrieve the original language so we can change it to C
            temporarily for our purposes. We promise we'll set it back as soon
            as we're done.
        '''
        import gdb
        lang_raw = gdb.execute('show language', to_string=True)

        lang = lang_raw.split()[-1].split('"')[0]
        if not lang:
            lang = lang_raw.split('"')[1]
        if not lang:
            raise gdb.error('"show language" command returned nothing! Raw: ',
                gdb.execute('show language', to_string=True))
        
        return lang
    def __call__(self, obj):
        """Invoke the xmethod

        Args:
            args: Arguments to the method.  Each element of the tuple is a
                gdb.Value object.  The first element is the 'this' pointer
                value.

        Returns:
            A gdb.Value corresponding to the value returned by the xmethod.
            Returns 'None' if the method does not return anything.
        """
        num_elem = obj['n_elem']
        mem = obj["mem"]
        try:
            max_value = max((mem + i).dereference() for i in range(num_elem))
        except gdb.error:
            raise gdb.error(
                "Error in gdb xmethod implementation for 'max' method")
        return max_value
Example #23
0
    def __init__(self, pane_name):
        p = subprocess.run(
            ["tmux", "list-panes", "-a", "-F", "#{pane_title}{|}#{pane_tty}"],
            encoding="utf-8",
            stdout=subprocess.PIPE)
        #        print("p = '%s'" % p )
        output = p.stdout.splitlines()
        tty = None
        self.pane = pane_name
        for line in output:
            line = line.split("{|}")
            #            print("line = '%s'" % line )
            # or regex?
            #            if( line[0] == pane_name ):
            if (re.match(pane_name, line[0])):
                tty = line[1]
                break
        if (tty is None):
            raise gdb.error("Could not find tmux pane named %s" % pane_name)


#        print("tty = '%s'" % tty )
        super().__init__(tty)
 def __call__(self, obj, index):
     if index < 0 or index >= obj["n_elem"]:
         raise gdb.error(
             "Cannot get element with index {} from {} with {} elements".
             format(index, obj.type.target(), obj['n_elem']))
     return obj["mem"][index]
Example #25
0
def getmod():
    #following code is get from ../getmod.py
    #use the code directly because sys.argv = [''] inside GDB
    def format_file(name):
        tmp = ""
        for c in name:
            if c == "_":
                c = "-"
            tmp += c
        return tmp

    #Check if the target is available
    if str(gdb.selected_thread()) == "None":
        raise gdb.error(
            "Please connect to Linux Kernel before use the script.")

    #Output the help
    print "Use GDB command \"set $mod_search_dir=dir\" to set an directory for search the modules."

    ignore_gtp_ko = gdb.parse_and_eval("$ignore_gtp_ko")
    if ignore_gtp_ko.type.code == gdb.TYPE_CODE_INT:
        ignore_gtp_ko = int(ignore_gtp_ko)
    else:
        ignore_gtp_ko = 1

    #Get the mod_search_dir
    mod_search_dir_list = []
    #Get dir from $mod_search_dir
    tmp_dir = gdb.parse_and_eval("$mod_search_dir")
    if tmp_dir.type.code == gdb.TYPE_CODE_ARRAY:
        tmp_dir = str(tmp_dir)
        tmp_dir = tmp_dir[1:len(tmp_dir)]
        tmp_dir = tmp_dir[0:tmp_dir.index("\"")]
        mod_search_dir_list.append(tmp_dir)
    #Get dir that same with current vmlinux
    tmp_dir = str(gdb.execute("info files", False, True))
    tmp_dir = tmp_dir[tmp_dir.index("Symbols from \"") +
                      len("Symbols from \""):len(tmp_dir)]
    tmp_dir = tmp_dir[0:tmp_dir.index("\"")]
    tmp_dir = tmp_dir[0:tmp_dir.rindex("/")]
    mod_search_dir_list.append(tmp_dir)
    #Get the dir of current Kernel
    tmp_dir = "/lib/modules/" + str(os.uname()[2])
    if os.path.isdir(tmp_dir):
        mod_search_dir_list.append(tmp_dir)
    #Let user choice dir
    mod_search_dir = ""
    while mod_search_dir == "":
        for i in range(0, len(mod_search_dir_list)):
            print str(i) + ". " + mod_search_dir_list[i]
        try:
            s = input('Select a directory for search the modules [0]:')
        except SyntaxError:
            s = 0
        except:
            continue
        if s < 0 or s >= len(mod_search_dir_list):
            continue
        mod_search_dir = mod_search_dir_list[s]

    mod_list_offset = long(
        gdb.parse_and_eval("((size_t) &(((struct module *)0)->list))"))
    mod_list = long(gdb.parse_and_eval("(&modules)"))
    mod_list_current = mod_list

    while 1:
        mod_list_current = long(
            gdb.parse_and_eval("((struct list_head *) " +
                               str(mod_list_current) + ")->next"))

        #check if need break the loop
        if mod_list == mod_list_current:
            break

        mod = mod_list_current - mod_list_offset

        #get mod_name
        mod_name = str(
            gdb.parse_and_eval("((struct module *)" + str(mod) + ")->name"))
        mod_name = mod_name[mod_name.index("\"") + 1:len(mod_name)]
        mod_name = mod_name[0:mod_name.index("\"")]
        if mod_name == "fglrx":
            contiue
        mod_name += ".ko"
        mod_name = format_file(mod_name)

        #get mod_dir_name
        mod_dir_name = ""
        for root, dirs, files in os.walk(mod_search_dir):
            for afile in files:
                tmp_file = format_file(afile)
                if tmp_file == mod_name:
                    mod_dir_name = os.path.join(root, afile)
                    break
            if mod_dir_name != "":
                break

        command = " "

        #Add module_core to command
        command += str(
            gdb.parse_and_eval("((struct module *)" + str(mod) +
                               ")->module_core"))

        #Add each sect_attrs->attrs to command
        #get nsections
        nsections = int(
            gdb.parse_and_eval("((struct module *)" + str(mod) +
                               ")->sect_attrs->nsections"))
        sect_attrs = long(
            gdb.parse_and_eval("(u64)((struct module *)" + str(mod) +
                               ")->sect_attrs"))
        for i in range(0, nsections):
            command += " -s"
            tmp = str(
                gdb.parse_and_eval("((struct module_sect_attrs *)" +
                                   str(sect_attrs) + ")->attrs[" + str(i) +
                                   "].name"))
            tmp = tmp[tmp.index("\"") + 1:len(tmp)]
            tmp = tmp[0:tmp.index("\"")]
            command += " " + tmp
            tmp = str(
                gdb.parse_and_eval("((struct module_sect_attrs *)" +
                                   str(sect_attrs) + ")->attrs[" + str(i) +
                                   "].address"))
            command += " " + tmp

        if mod_dir_name == "":
            print "Cannot find out", mod_name, "from directory."
            print "Please use following command load the symbols from it:"
            print "add-symbol-file some_dir/" + mod_name + command
        else:
            if ignore_gtp_ko and mod_name == "gtp.ko":
                pass
            else:
                #print "add-symbol-file "+mod_dir_name+command
                gdb.execute("add-symbol-file " + mod_dir_name + command, False,
                            False)
Example #26
0
            print("Drop one entry because:")
            for file, lineno, function, text in traceback.extract_tb(
                    sys.exc_info()[2]):
                print file, lineno, function, text
        try:
            gdb.execute("tfind 1", False, True)
        except:
            pass
else:
    while 1:
        try:
            gdb.execute("tfind 0", False, True)
            is_user = False
            pid = long(gdb.parse_and_eval("$current_task_pid"))
            if not pid in task_list:
                raise gdb.error("Cannot find inferior for pid " + str(pid) +
                                ", drop one entry.")
            if trace_user and (not trace_kernel or long(
                    gdb.parse_and_eval("regs->cs & 3")) == 3):
                is_user = True
                ip = long(gdb.parse_and_eval("regs->ip - 1"))
                gdb.execute("inferior " + str(task_list[pid].fid), False, True)
                sym = gdb.execute("info line *" + str(ip), True, True)
            else:
                sym = gdb.execute("info line *(regs->ip - 1)", True, True)
            line = get_line_from_sym(sym)
            if is_user:
                gdb.execute("inferior 1", False, True)
            task_list_add_line(is_user, pid, line)
        except gdb.error, x:
            print("Drop one entry because:")
            for file, lineno, function, text in traceback.extract_tb(
Example #27
0
#Make sure this is connect gdbframe or not, if not, gtpframe_pipe = 1
gtpframe_pipe = 0;
if str(gdb.selected_thread()) == "None":
	gtpframe_pipe = 1
	gdb.execute("target tfile /sys/kernel/debug/gtpframe_pipe");

signal.setitimer(signal.ITIMER_REAL, 1, 1);

keep_running = 1;
while keep_running:
	try:
		tfind_done = 0;
		if gtpframe_pipe:
			tid = tfind_entry(0);
			if tid < 0:
				raise gdb.error("tfind");
		else:
			tid = tfind_entry(-1);
			if tid < 0:
				break;
		tfind_done = 1;

		cpu_id = str(gdb.parse_and_eval("$cpu_id"));
		clock += long(gdb.parse_and_eval("$pc_pe_val_00_"+cpu_id));
		time += 1;

	except gdb.error, x:
		#print("Drop one entry because", x);
		pass;
	except gdb.MemoryError, x:
		print("Drop one entry because", x);
Example #28
0
 def __call__(self, obj, index):
     if index < 0 or index >= obj["n_elem"]:
         raise gdb.error(
             f"Cannot get element with index {index} from {obj.type.target()} with {obj['n_elem']} elements"
         )
     return obj["mem"][index]
Example #29
0
def getmod():
	#following code is get from ../getmod.py
	#use the code directly because sys.argv = [''] inside GDB
	def format_file(name):
		tmp = ""
		for c in name:
			if c == "_":
				c = "-"
			tmp += c
		return tmp

	#Check if the target is available
	if str(gdb.selected_thread()) == "None":
		raise gdb.error("Please connect to Linux Kernel before use the script.")

	#Output the help
	print "Use GDB command \"set $mod_search_dir=dir\" to set an directory for search the modules."

	ignore_gtp_ko = gdb.parse_and_eval("$ignore_gtp_ko")
	if ignore_gtp_ko.type.code == gdb.TYPE_CODE_INT:
		ignore_gtp_ko = int(ignore_gtp_ko)
	else:
		ignore_gtp_ko = 1

	#Get the mod_search_dir
	mod_search_dir_list = []
	#Get dir from $mod_search_dir
	tmp_dir = gdb.parse_and_eval("$mod_search_dir")
	if tmp_dir.type.code == gdb.TYPE_CODE_ARRAY:
		tmp_dir = str(tmp_dir)
		tmp_dir = tmp_dir[1:len(tmp_dir)]
		tmp_dir = tmp_dir[0:tmp_dir.index("\"")]
		mod_search_dir_list.append(tmp_dir)
	#Get dir that same with current vmlinux
	tmp_dir = str(gdb.execute("info files", False, True))
	tmp_dir = tmp_dir[tmp_dir.index("Symbols from \"")+len("Symbols from \""):len(tmp_dir)]
	tmp_dir = tmp_dir[0:tmp_dir.index("\"")]
	tmp_dir = tmp_dir[0:tmp_dir.rindex("/")]
	mod_search_dir_list.append(tmp_dir)
	#Get the dir of current Kernel
	tmp_dir = "/lib/modules/" + str(os.uname()[2])
	if os.path.isdir(tmp_dir):
		mod_search_dir_list.append(tmp_dir)
	#Let user choice dir
	mod_search_dir = ""
	while mod_search_dir == "":
		for i in range(0, len(mod_search_dir_list)):
			print str(i)+". "+mod_search_dir_list[i]
		try:
			s = input('Select a directory for search the modules [0]:')
		except SyntaxError:
			s = 0
		except:
			continue
		if s < 0 or s >= len(mod_search_dir_list):
			continue
		mod_search_dir = mod_search_dir_list[s]

	mod_list_offset = long(gdb.parse_and_eval("((size_t) &(((struct module *)0)->list))"))
	mod_list = long(gdb.parse_and_eval("(&modules)"))
	mod_list_current = mod_list

	while 1:
		mod_list_current = long(gdb.parse_and_eval("((struct list_head *) "+str(mod_list_current)+")->next"))

		#check if need break the loop
		if mod_list == mod_list_current:
			break

		mod = mod_list_current - mod_list_offset

		#get mod_name
		mod_name = str(gdb.parse_and_eval("((struct module *)"+str(mod)+")->name"))
		mod_name = mod_name[mod_name.index("\"")+1:len(mod_name)]
		mod_name = mod_name[0:mod_name.index("\"")]
		if mod_name == "fglrx":
			contiue
		mod_name += ".ko"
		mod_name = format_file(mod_name)

		#get mod_dir_name
		mod_dir_name = ""
		for root, dirs, files in os.walk(mod_search_dir):
			for afile in files:
				tmp_file = format_file(afile)
				if tmp_file == mod_name:
					mod_dir_name = os.path.join(root,afile)
					break
			if mod_dir_name != "":
				break

		command = " "

		#Add module_core to command
		command += str(gdb.parse_and_eval("((struct module *)"+str(mod)+")->module_core"))

		#Add each sect_attrs->attrs to command
		#get nsections
		nsections = int(gdb.parse_and_eval("((struct module *)"+str(mod)+")->sect_attrs->nsections"))
		sect_attrs = long(gdb.parse_and_eval("(u64)((struct module *)"+str(mod)+")->sect_attrs"))
		for i in range(0, nsections):
			command += " -s"
			tmp = str(gdb.parse_and_eval("((struct module_sect_attrs *)"+str(sect_attrs)+")->attrs["+str(i)+"].name"))
			tmp = tmp[tmp.index("\"")+1:len(tmp)]
			tmp = tmp[0:tmp.index("\"")]
			command += " "+tmp
			tmp = str(gdb.parse_and_eval("((struct module_sect_attrs *)"+str(sect_attrs)+")->attrs["+str(i)+"].address"))
			command += " "+tmp

		if mod_dir_name == "":
			print "Cannot find out",mod_name,"from directory."
			print "Please use following command load the symbols from it:"
			print "add-symbol-file some_dir/"+mod_name+command
		else:
			if ignore_gtp_ko and mod_name == "gtp.ko":
				pass
			else:
				#print "add-symbol-file "+mod_dir_name+command
				gdb.execute("add-symbol-file "+mod_dir_name+command, False, False)
Example #30
0
		except gdb.MemoryError, x:
			print("Drop one entry because:")
			for file, lineno, function, text in traceback.extract_tb(sys.exc_info()[2]):
				print file, lineno, function, text
		try:
			gdb.execute("tfind 1", False, True)
		except:
			pass
else:
	while 1:
		try:
			gdb.execute("tfind 0", False, True)
			is_user = False
			pid = long(gdb.parse_and_eval("$current_task_pid"))
			if not pid in task_list:
				raise gdb.error ("Cannot find inferior for pid "+ str(pid) +", drop one entry.")
			if trace_user and (not trace_kernel or long(gdb.parse_and_eval("regs->cs & 3")) == 3):
				is_user = True
				ip = long(gdb.parse_and_eval("regs->ip - 1"))
				gdb.execute("inferior "+str(task_list[pid].fid), False, True)
				sym = gdb.execute("info line *"+str(ip), True, True)
			else:
				sym = gdb.execute("info line *(regs->ip - 1)", True, True)
			line = get_line_from_sym(sym)
			if is_user:
				gdb.execute("inferior 1", False, True)
			task_list_add_line(is_user, pid, line)
		except gdb.error, x:
			print("Drop one entry because:")
			for file, lineno, function, text in traceback.extract_tb(sys.exc_info()[2]):
				print file, lineno, function, text
Example #31
0
#Make sure this is connect gdbframe or not, if not, gtpframe_pipe = 1
gtpframe_pipe = 0
if str(gdb.selected_thread()) == "None":
    gtpframe_pipe = 1
    gdb.execute("target tfile /sys/kernel/debug/gtpframe_pipe")

exit_count = 0
increase_list(1)

while keep_running:
    try:
        tfind_done = 0
        if gtpframe_pipe:
            tid = tfind_entry(0)
            if tid < 0:
                raise gdb.error("tfind")
        else:
            tid = tfind_entry(-1)
            if tid < 0:
                break
        tfind_done = 1

        if tid == schedule_id or tid == do_exit_id:
            cpu_id = int(gdb.parse_and_eval("$cpu_id"))
            if cpu_id >= len(pid_list):
                increase_list(cpu_id + 1 - len(pid_list))
            pid = long(gdb.parse_and_eval("$pc_pid_" + str(cpu_id)))
            clock = long(gdb.parse_and_eval("$pc_begin_" + str(cpu_id)))
            if pid in pid_list[cpu_id]:
                pid_list[cpu_id][pid]["clock"] += clock
                pid_list[cpu_id][pid]["count"] += 1
Example #32
0
def handleEventError(e, f):
    raise gdb.error('*****unhandled event ' + str(e) + ' passed to ' + str(f))
Example #33
0
def seekS(e):
    debugMsg('hit ' + str(inspect.stack()[0][3]) + ' with event: ' + str(e))
    raise gdb.error('seekS not implemented')
Example #34
0
pagination = get_pagination()
gdb.execute("set pagination off", False, False)


def format_file(name):
    tmp = ""
    for c in name:
        if c == "_":
            c = "-"
        tmp += c
    return tmp


#Check if the target is available
if str(gdb.selected_thread()) == "None":
    raise gdb.error("Please connect to Linux Kernel before use the script.")

#Output the help
print "Use GDB command \"set $mod_search_dir=dir\" to set an directory for search the modules."

ignore_gtp_ko = gdb.parse_and_eval("$ignore_gtp_ko")
if ignore_gtp_ko.type.code == gdb.TYPE_CODE_INT:
    ignore_gtp_ko = int(ignore_gtp_ko)
else:
    ignore_gtp_ko = 1

#Get the mod_search_dir
mod_search_dir_list = []
#Get dir from $mod_search_dir
tmp_dir = gdb.parse_and_eval("$mod_search_dir")
if tmp_dir.type.code == gdb.TYPE_CODE_ARRAY:
Example #35
0
def get_mod_dir_name(name, search_dir):
	#get mod_dir_name
	full_name = ""
	for root, dirs, files in os.walk(search_dir):
		for afile in files:
			tmp_file = format_file(afile)
			if tmp_file == name:
				full_name = os.path.join(root,afile)
				break
		if full_name != "":
			break
	return full_name

#Check if the target is available
if str(gdb.selected_thread()) == "None":
	raise gdb.error("Please connect to Linux Kernel before use the script.")

#Output the help
print "Use GDB command \"set $mod_search_dir=dir\" to set an directory for search the modules."

ignore_gtp_ko = gdb.parse_and_eval("$ignore_gtp_ko")
if ignore_gtp_ko.type.code == gdb.TYPE_CODE_INT:
	ignore_gtp_ko = int(ignore_gtp_ko)
else:
	ignore_gtp_ko = 1

#Get the mod_search_dir
mod_search_dir_list = []
#Get dir from $mod_search_dir
tmp_dir = gdb.parse_and_eval("$mod_search_dir")
if tmp_dir.type.code == gdb.TYPE_CODE_ARRAY:
Example #36
0
#Make sure this is connect gdbframe or not, if not, gtpframe_pipe = 1
gtpframe_pipe = 0;
if str(gdb.selected_thread()) == "None":
	gtpframe_pipe = 1
	gdb.execute("target tfile /sys/kernel/debug/gtpframe_pipe");

exit_count = 0;
increase_list(1);

while keep_running:
	try:
		tfind_done = 0;
		if gtpframe_pipe:
			tid = tfind_entry(0);
			if tid < 0:
				raise gdb.error("tfind");
		else:
			tid = tfind_entry(-1);
			if tid < 0:
				break;
		tfind_done = 1;

		if tid == schedule_id or tid == do_exit_id:
			cpu_id = int(gdb.parse_and_eval("$cpu_id"));
			if cpu_id >= len(pid_list):
				increase_list(cpu_id + 1 - len(pid_list));
			pid = long(gdb.parse_and_eval("$pc_pid_"+str(cpu_id)));
			clock = long(gdb.parse_and_eval("$pc_begin_"+str(cpu_id)));
			if pid in pid_list[cpu_id]:
				pid_list[cpu_id][pid]["clock"] += clock;
				pid_list[cpu_id][pid]["count"] += 1;
Example #37
0
#Make sure this is connect gdbframe or not, if not, gtpframe_pipe = 1
gtpframe_pipe = 0
if str(gdb.selected_thread()) == "None":
    gtpframe_pipe = 1
    gdb.execute("target tfile /sys/kernel/debug/gtpframe_pipe")

signal.setitimer(signal.ITIMER_REAL, 1, 1)

keep_running = 1
while keep_running:
    try:
        tfind_done = 0
        if gtpframe_pipe:
            tid = tfind_entry(0)
            if tid < 0:
                raise gdb.error("tfind")
        else:
            tid = tfind_entry(-1)
            if tid < 0:
                break
        tfind_done = 1

        cpu_id = str(gdb.parse_and_eval("$cpu_id"))
        clock += long(gdb.parse_and_eval("$pc_pe_val_00_" + cpu_id))
        time += 1

    except gdb.error, x:
        #print("Drop one entry because", x);
        pass
    except gdb.MemoryError, x:
        print("Drop one entry because", x)