Exemple #1
0
def get_pid():
    inferiors = gdb.inferiors()
    for inf in gdb.inferiors():
        if inf.is_valid():
            return inf.pid

    raise Exception("get_pid(): failed to find program's pid")
Exemple #2
0
 def _check_inferior_state(self):
     if len(gdb.inferiors()) != 1:
         raise GdbWrapperError("Unsupported number of inferiors ({})".format(len(gdb.inferiors())))
     if len(gdb.inferiors()[0].threads()) == 0:
         raise GdbWrapperError("No threads running")
     if not gdb.inferiors()[0].threads()[0].is_stopped:
         raise GdbWrapperError("Inferior's primary thread is not stopped")
Exemple #3
0
def get_inferior():

    try:
        if len(gdb.inferiors()) == 0:
            error("No gdb inferior could be found.")
        else:
            inferior = gdb.inferiors()[0]
            return inferior
    except AttributeError:
        error("This gdb's python support is too old.")
Exemple #4
0
def get_inferior():
    """Get current inferior"""
    try:
        if len(gdb.inferiors()) == 0:
            print ("No gdb inferior could be found.")
            return -1
        else:
            inferior = gdb.inferiors()[0]
            return inferior
    except AttributeError:
        print ("This gdb's python support is too old, please update first.")
        exit()
Exemple #5
0
 def get_inferior(self):
     try:
         if self.inferior is None:
             if len(gdb.inferiors()) == 0:
                 print_error("No gdb inferior could be found.")
                 return -1
             else:
                 self.inferior = gdb.inferiors()[0]
                 return self.inferior
         else:
             return self.inferior
     except AttributeError:
         print_error("This gdb's python support is too old.")
         sys.exit()
    def stop(self):
        # fff = gdb.execute('bt', to_string=True)

        # get the string
        length = int(gdb.parse_and_eval('$ecx'))
        length = socket.ntohl(length)
        print(length)

        registers = ["$edx"]
        # registers = ["$esp", "$ebp", "$esi", "$eax", "$ecx", "$edx", "$ebx", "$edi"]
        for register in registers:
            address = gdb.parse_and_eval(register)
            address = int(address)
            p = struct.pack(">i", address)
            u = struct.unpack("<I", p)
            address = u[0]
            print(address)
            try:
                data = gdb.inferiors()[0].read_memory(address, length)
                print(register, binascii.hexlify(data), length, address)
            except gdb.MemoryError:
                print("FFFFFFFFFFFFFFFFFF")
            except:
                # print("Register %s failed." % register)
                traceback.print_exc()
                return False

        # return False to continue the execution of the program
        return False
    def stop(self):
        registers = ["$edx"]
        for register in registers:
            try:
                length = int(gdb.parse_and_eval('$ecx'))  # IDA Demo 6.6 + GDB FTW!
                p = struct.pack(">i", length)
                length = struct.unpack("<I", p)[0]
                address = gdb.parse_and_eval(register)
                address = int(address)
                p = struct.pack(">i", address)
                u = struct.unpack("<I", p)
                address = u[0]
            except:
                traceback.print_exc()
                return True

            try:
                data = gdb.inferiors()[0].read_memory(address, length)
                # reduce noise by checking for password ("passsword12345"), not strictly required :-)
                if "70617373776f72643132333435" in str(binascii.hexlify(data)):
                    self.trailing_calls = 1
                    print(register, binascii.hexlify(data), length)
                elif self.trailing_calls > 0:
                    print(register, binascii.hexlify(data), length)
                    self.trailing_calls = self.trailing_calls - 1
            except gdb.MemoryError:
                traceback.print_exc()
                return True
            except:
                traceback.print_exc()
                return True

        # return False to continue the execution of the program
        return False
Exemple #8
0
    def create_inferior(self, inferior_id):
        gdb_inferior = None
        try:
            gdb_inferior = (i for i in gdb.inferiors()
                            if i.num == inferior_id).next()
        except StopIteration:
            return None

        cpu = None
        info_inferiors = gdb.execute('info inferiors', False, True)
        info_target = gdb.execute('info target', False, True)
        try:
            matches = self._inferior_expression.findall(info_inferiors)
            inferior = (i for i in matches if int(i[0]) == inferior_id).next()

            inferior_path = os.path.abspath(inferior[2]).strip()
            matches = self._file_expression.findall(info_target)
            try:
                target = (i[1] for i in matches
                          if os.path.abspath(i[0]).strip() ==
                          inferior_path).next()

                architecture = self._target_to_architecture(target)
                cpu = self._cpu_factory.create_cpu(architecture)

            except StopIteration:
                registers = self._registers()
                cpu = GenericCpu(self._cpu_factory, registers)

        except TypeError:
            return None

        return GdbInferior(cpu, gdb_inferior)
    def stop(self):
        registers = ["$edx"]

        for register in registers:
            try:
                length = int(gdb.parse_and_eval('$ecx'))  # IDA Pro + GDB FTW!
                p = struct.pack(">i", length)
                length = struct.unpack("<I", p)[0]
                address = gdb.parse_and_eval(register)
                address = int(address)
                p = struct.pack(">i", address)
                u = struct.unpack("<I", p)
                address = u[0]
            except:
                traceback.print_exc()
                return True

            try:
                data = gdb.inferiors()[0].read_memory(address, length)
                print(register, binascii.hexlify(data), length)
            except gdb.MemoryError:
                traceback.print_exc()
                return True
            except:
                traceback.print_exc()
                return True

        # return False to continue the execution of the program
        return False
Exemple #10
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()
    def invoke(self, arg, from_tty):
        pid = str(gdb.inferiors()[0].pid)
        cmd = "cat /proc/" + pid + "/maps | grep "
        res = subprocess.Popen(cmd + arg,
                               shell=True, stdout=subprocess.PIPE).communicate()[0]
        if (len(res) == 0):
            print '**** Library %s not found. ' % arg
            print '  Do:  cat /proc/%d/maps to see all libs.' % pid
            return

        lib=subprocess.Popen(cmd + arg + " | head -1 | sed -e 's%[^/]*\\(/.*\\)%\\1%'",
                             shell=True, stdout=subprocess.PIPE).communicate()[0].rstrip()

        segAddr=subprocess.Popen(cmd + lib + "| grep r-xp |"\
                                 "sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'",
                                 shell=True, stdout=subprocess.PIPE).communicate()[0]
        segDataAddr=subprocess.Popen(cmd + lib +
                                " | grep rw-p | sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'",
                                 shell=True, stdout=subprocess.PIPE).communicate()[0]

        textOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.text ' | " \
                                    "sed -e 's%^.*text[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                    shell=True, stdout=subprocess.PIPE).communicate()[0]
        dataOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.data ' | "\
                                    "sed -e 's%^.*data[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                    shell=True, stdout=subprocess.PIPE).communicate()[0]
        bssOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.bss ' | "\
                                   "sed -e 's%^.*bss[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                   shell=True, stdout=subprocess.PIPE).communicate()[0]

        gdb.execute("add-symbol-file " + lib + " " + str(long(segAddr, 16) +
                                                         long(textOffset, 16))
                    + " -s .data " + str(long(segDataAddr, 16) + long(dataOffset, 16))
                    + " -s .bss " + str(long(segDataAddr, 16) + long(bssOffset, 16)),
                    True, True) 
Exemple #12
0
  def invoke (self, arg, from_tty):
    thread = gdb.selected_thread()
    if thread == None:
      print 'No thread selected.'
      return

    for thread in gdb.inferiors():
      frame = gdb.newest_frame()
      while frame:
        # if that matches our regexp, select that.
        try:
          match = re.match(arg, frame.name(), flags=re.IGNORECASE)
        except Exception, e:
          print "Error: invalid regex: %s" % str(e)
          return

        if match:
          sal = frame.find_sal()
          print "Found: %s, thread %s, file %s:%s, in function %s" % (frame.name(), thread.num,sal.symtab.filename, sal.line, frame.function())
          frame.select()
          return

        frame = frame.older()
        if not frame:
          return
    def stop(self):
        registers = ["$edx"]

        # reduce noise, not strictly required :-)
        fff = gdb.execute("bt", to_string=True)
        if "0x4013af0f" in fff or "0x644800f4" in fff:
            print("Skipping ...")
            return False

        for register in registers:
            try:
                length = int(gdb.parse_and_eval('$ecx'))  # IDA Pro + GDB FTW!
                p = struct.pack(">i", length)
                length = struct.unpack("<I", p)[0]
                address = gdb.parse_and_eval(register)
                address = int(address)
                p = struct.pack(">i", address)
                u = struct.unpack("<I", p)
                address = u[0]
            except:
                traceback.print_exc()
                return True

            try:
                data = gdb.inferiors()[0].read_memory(address, length)
                print(register, binascii.hexlify(data), length)
            except gdb.MemoryError:
                traceback.print_exc()
                return True
            except:
                traceback.print_exc()
                return True

        # return False to continue the execution of the program
        return False
Exemple #14
0
def pr_cpumask(mask):
    nr_cpu_ids = 1
    if constants.LX_NR_CPUS > 1:
        nr_cpu_ids = gdb.parse_and_eval("nr_cpu_ids")

    inf = gdb.inferiors()[0]
    bits = mask['bits']
    num_bytes = (nr_cpu_ids + 7) / 8
    buf = utils.read_memoryview(inf, bits, num_bytes).tobytes()
    buf = binascii.b2a_hex(buf)

    chunks = []
    i = num_bytes
    while i > 0:
        i -= 1
        start = i * 2
        end = start + 2
        chunks.append(buf[start:end])
        if i != 0 and i % 4 == 0:
            chunks.append(',')

    extra = nr_cpu_ids % 8
    if 0 < extra <= 4:
        chunks[0] = chunks[0][0]  # Cut off the first 0

    return "".join(chunks)
Exemple #15
0
    def invoke(self, arg, from_tty):
        args = arg.split()
        max = 0
        if len(args) >= 1:
            max = int(args[0])
        events = collections.defaultdict(list)
        frequency = float(gdb.selected_frame().read_var("ftracer_frequency"))
        thr_max = 0
        for i in gdb.inferiors():
            for t in i.threads():
                gdb.execute("thread %d" % (t.num,))
                ftracer_len = gdb.selected_frame().read_var("ftracer_size") 
                x = gdb.selected_frame().read_var("ftracer_tbuf")
                for j in range(0, ftracer_len-1):
                    v = x[j]
                    tstamp = int(v["tstamp"])
                    if tstamp:
                        o = (t.num, v["func"], v["arg1"], v["arg2"], v["arg3"], v["rsp"])
                        events[tstamp].append(o)
                        if int(t.num) > thr_max:
                            thr_max = int(t.num)
        print ("%*s %*s %3s %-*s %s" %
                (TSTAMP_WIDTH, "TIME",
                 TSTAMP_WIDTH, "DELTA", "THR",
                 THR_WIDTH * thr_max, "FUNC", "ARGS"))
        prev = 0
        delta = 0
        start = 0
        threads = collections.defaultdict(Thr)
        k = sorted(events.keys())
        if max:
            k = collections.deque(k, max)
        for t in k:
            if prev:
                delta = t - prev
            if start == 0:
                start = t
            for e in events[t]:
                tnum = e[0]
                thr = threads[tnum]
                thr.update(int(e[5]))
		if thr_max >= 8:
			func = "<%d> " % (tnum)
			width = 30
		else:
                	func = " " * (THR_WIDTH * (tnum-1)) 
                       	width = THR_WIDTH * thr_max,
                func += " " * (thr.level() * 2) 
                func += resolve(int(e[1]))
                print "%*.2f %*.2f %3d %-*s %x %x %x" % (
                       TSTAMP_WIDTH,
                       (t - start) / frequency,
                       TSTAMP_WIDTH,
                       delta / frequency,
                       tnum,
		       width,
                       func,
                       int(e[2]), int(e[3]), int(e[4]))
            prev = t
Exemple #16
0
 def selectedInferior():
     try:
         # Does not exist in 7.3.
         return gdb.selected_inferior()
     except:
         pass
     # gdb.Inferior is new in gdb 7.2
     return gdb.inferiors()[0]
Exemple #17
0
  def invoke(self, arg, from_tty):
    args = arg.split(' ')
    argp = 0
    do_print_stack = False
    do_print_full_stack = False
    while len(args[argp])>0 and args[argp][0]=='-':
      S_ = args[argp]
      argp+=1
      if S_=='-help':
        print("threadgrep - Print gdb variables via python\n"
              "\n"
              "Syntax:\n"
              "  threadgrep [-stack] [-fullstack] pattern\n"
              "\n"
              "Options:\n"
              "  -stack      Output stack lines matching the search pattern\n"
              "  -fullstack  Output full stack if the search pattern is matched for a thread")
        return

      if S_=='-stack':
        do_print_stack = True
        continue

      if S_=='-fullstack':
        do_print_full_stack = True
        continue

      print("Unknown option '%s'!"%S_)
      return

    pattern = args[argp]

    # Get list of threads
    threads_string = gdb.execute('info threads',False,True)
    thread_ids = []
    for thread_string in threads_string.split('\n'):
      m = re.match(r'^\*?\s+(\d+).*?\"(.*?)\"',thread_string)
      if m:
        thread_ids += [(int(m.group(1)), m.group(2))]
    thread_ids.sort()

    # Loop over all threads
    thread_names = [i.name for i in gdb.inferiors()[0].threads()]
    for thread_id,thread_name in thread_ids:
      gdb.execute("thread %d"%thread_id, False, True)
      where_string = gdb.execute('where',False,True)
      if re.search(pattern, where_string):
        print(colors.HEADER + "Match in thread #%d (%s)"%(thread_id, thread_name) + colors.ENDC)
        if do_print_stack:
          for where_line in where_string.split("\n"):
            if re.search(pattern,where_line):
              where_line = re.sub('('+pattern+')', colors.BLUE + r"\1" + colors.ENDC,where_line)
              print(where_line)
          print("")
        if do_print_full_stack:
          where_string = re.sub('('+pattern+')', colors.BLUE + r"\1" + colors.ENDC,where_string)
          print(where_string)
    def test_cython_step(self):
        gdb.execute('cy break codefile.spam')

        gdb.execute('run', to_string=True)
        self.lineno_equals('def spam(a=0):')

        gdb.execute('cy step', to_string=True)
        self.lineno_equals('b = c = d = 0')

        self.command = 'cy step'
        self.step([('b', 0)], source_line='b = 1')
        self.step([('b', 1), ('c', 0)], source_line='c = 2')
        self.step([('c', 2)], source_line='int(10)')
        self.step([], source_line='puts("spam")')

        gdb.execute('cont', to_string=True)
        self.assertEqual(len(gdb.inferiors()), 1)
        self.assertEqual(gdb.inferiors()[0].pid, 0)
    def test_cython_step(self):
        gdb.execute("cy break codefile.spam")

        gdb.execute("run", to_string=True)
        self.lineno_equals("def spam(a=0):")

        gdb.execute("cy step", to_string=True)
        self.lineno_equals("b = c = d = 0")

        self.command = "cy step"
        self.step([("b", 0)], source_line="b = 1")
        self.step([("b", 1), ("c", 0)], source_line="c = 2")
        self.step([("c", 2)], source_line="int(10)")
        self.step([], source_line='puts("spam")')

        gdb.execute("cont", to_string=True)
        self.assertEqual(len(gdb.inferiors()), 1)
        self.assertEqual(gdb.inferiors()[0].pid, 0)
Exemple #20
0
 def invoke(self, arg, from_tty):
   e = rv.get_reg_element(arg)
   if e is None:
     print "Unknown register %s" % arg
     return
   addr = rv.get_reg_address(arg)
   buff = gdb.inferiors()[0].read_memory(addr, 4)
   val = struct.unpack("I", buff)[0]
   rv.print_reg(arg, val)
Exemple #21
0
    def _inferior_is_valid(self):
        """Checks if the inferior is still valid"""

        _inferiors = gdb.inferiors()

        for inferior in _inferiors:
            if inferior == self:
                return True

        return False
Exemple #22
0
	def update(self):
		self.thread_dict = dict()
		d = dict()
		for inf in gdb.inferiors():
			for th in inf.threads():
				d[ th.ptid[1] ] = th.num
				debug( "%d -- %d" % ( th.ptid[1],th.num))
				debug("type %s"% type(th.ptid[1]))
		debug( "dic len: %d" %  len(d))
		self.thread_dict = d
    def stop(self):
        # get the string address, from the second arguments of the function
        address = gdb.parse_and_eval('$ecx')

        # get the string
        data = binascii.hexlify(gdb.inferiors()[0].read_memory(address, 64))
        # data = bytearray(gdb.inferiors()[0].read_memory(address, 64))
        print(data)

        # return False to continue the execution of the program
        return False
    def invoke(self, arg, _):
        if not arg:
            arg = DEFAULT_ARG

        addr = gdb.parse_and_eval(arg)

        if addr.type != VOID_P_TYPE:
            gdb.write('Invalid argument: not an address\n', gdb.STDERR)
            return

        infs = gdb.inferiors()

        assert len(infs) == 1

        mem = infs[0].read_memory(addr, STACK_SAMPLE_LENGTH)

        procs = []
        funs = {}

        addr = struct.Struct(ADDR_UNPACK)

        for i in xrange(STACK_SAMPLE_LENGTH / ADDR_SIZE):
            p = addr.unpack(mem[i * ADDR_SIZE:(i + 1) * ADDR_SIZE])[0]

            if p not in funs:
                s = gdb.execute('info symbol %d' % p, to_string=True)
                s = s.strip()

                m = re.match(r'(\w*) \+ \d+ in section', s)
                if m:
                    procs.append(p)
                    funs[p] = m.groups()[0]
            else:
                procs.append(p)

        idx, seq = find_shortest(procs)

        if not seq:
            gdb.write('Unable to find recurring call pattern', gdb.STDERR)
            gdb.flush(gdb.STDERR)
            return

        title = 'Recurring call pattern starting at frame %d' % idx
        gdb.write(title)
        gdb.write('\n')
        gdb.write('=' * len(title))
        gdb.write('\n')
        for c in seq:
            gdb.write('%s @ 0x%x\n' % (funs[c], c))
        gdb.flush(gdb.STDOUT)
Exemple #25
0
    def invoke(self, arg, from_tty):
        # Map a mutex ID to the LWP owning the mutex.
        owner = {}
        # Map an LWP id to a thread object.
        threads = {}
        # Map a mutex ID to a list of thread objects that are waiting
        # for the lock.
        mutexes = {}

        for inf in gdb.inferiors():
            for thr in inf.threads():
                id = thr.ptid[1]
                threads[id] = thr
                with thread_holder(thr):
                    frame = gdb.selected_frame()
                    lock_name = None
                    for n in range(5):
                        if frame is None:
                            break
                        fn_sym = frame.function()
                        if fn_sym is not None and (
                            fn_sym.name == "__pthread_mutex_lock"
                            or fn_sym.name == "__pthread_mutex_lock_full"
                            or fn_sym.name == "pthread_mutex_timedlock"
                        ):
                            m = frame.read_var("mutex")
                            lock_name = long(m)
                            if lock_name not in owner:
                                owner[lock_name] = long(m["__data"]["__owner"])
                                break
                        frame = frame.older()
                    if lock_name not in mutexes:
                        mutexes[lock_name] = []
                    mutexes[lock_name] += [thr]

        global selected_thread

        selected_thread = gdb.selected_thread()

        for id in mutexes.keys():
            if id is None:
                print "Threads not waiting for a lock:"
            else:
                print "Mutex 0x%x:" % id
                print_thread(threads[owner[id]], True)
            for thr in mutexes[id]:
                print_thread(thr, False)
            print
    def stop (self):

        # get the string length, from the return value of the function
        length = gdb.parse_and_eval('$rax')

        # get the string address, from the second arguments of the function
        address = gdb.parse_and_eval('$rsi')

        # get the string
        string = gdb.inferiors()[0].read_memory(address, length)

        # print sniffed data
        print string
        
        # return False to continue the execution of the program
        return False
Exemple #27
0
    def invoke(self, arg, from_tty):
        log_buf_addr = int(str(gdb.parse_and_eval(
            "(void *)'printk.c'::log_buf")).split()[0], 16)
        log_first_idx = int(gdb.parse_and_eval("'printk.c'::log_first_idx"))
        log_next_idx = int(gdb.parse_and_eval("'printk.c'::log_next_idx"))
        log_buf_len = int(gdb.parse_and_eval("'printk.c'::log_buf_len"))

        inf = gdb.inferiors()[0]
        start = log_buf_addr + log_first_idx
        if log_first_idx < log_next_idx:
            log_buf_2nd_half = -1
            length = log_next_idx - log_first_idx
            log_buf = utils.read_memoryview(inf, start, length).tobytes()
        else:
            log_buf_2nd_half = log_buf_len - log_first_idx
            a = utils.read_memoryview(inf, start, log_buf_2nd_half)
            b = utils.read_memoryview(inf, log_buf_addr, log_next_idx)
            log_buf = a.tobytes() + b.tobytes()

        pos = 0
        while pos < log_buf.__len__():
            length = utils.read_u16(log_buf[pos + 8:pos + 10])
            if length == 0:
                if log_buf_2nd_half == -1:
                    gdb.write("Corrupted log buffer!\n")
                    break
                pos = log_buf_2nd_half
                continue

            text_len = utils.read_u16(log_buf[pos + 10:pos + 12])
            text = log_buf[pos + 16:pos + 16 + text_len].decode(
                encoding='utf8', errors='replace')
            time_stamp = utils.read_u64(log_buf[pos:pos + 8])

            for line in text.splitlines():
                msg = u"[{time:12.6f}] {line}\n".format(
                    time=time_stamp / 1000000000.0,
                    line=line)
                # With python2 gdb.write will attempt to convert unicode to
                # ascii and might fail so pass an utf8-encoded str instead.
                if sys.hexversion < 0x03000000:
                    msg = msg.encode(encoding='utf8', errors='replace')
                gdb.write(msg)

            pos += length
Exemple #28
0
 def invoke(self, args, from_tty):
     if args:
         inferiors = gdb.inferiors()
         for inf_id_str in args:
             inf_id = to_int(inf_id_str)
             found = False
             for inf in inferiors:
                 if inf.num == inf_id:
                     self.show(inf.pid)
                     found = True
                     break
             if not found:
                 raise gdb.GdbError("Unknown inferior {}.".format(inf_id))
     else:
         pid = gdb.selected_inferior().pid
         if pid == 0:
             raise gdb.GdbError("No current inferior.")
         self.show(pid)
Exemple #29
0
    def iter_mmap_chunks(self):
        for inf in gdb.inferiors():
            for (start, end) in iter_mmap_heap_chunks(inf.pid):
                # print "Trying 0x%x-0x%x" % (start, end)
                try:
                    chunk = MChunkPtr(gdb.Value(start).cast(MChunkPtr.gdb_type()))
                    # Does this look like the first chunk within a range of
                    # mmap address space?
                    #print ('0x%x' % chunk.as_address() + chunk.chunksize())
                    if (not chunk.has_NON_MAIN_ARENA() and chunk.has_IS_MMAPPED()
                        and chunk.as_address() + chunk.chunksize() <= end):

                        # Iterate upwards until you reach "end" of mmap space:
                        while chunk.as_address() < end and chunk.has_IS_MMAPPED():
                            yield chunk
                            # print '0x%x' % chunk.as_address(), chunk
                            chunk = chunk.next_chunk()
                except RuntimeError:
                    pass
Exemple #30
0
    def invoke(self, arg, from_tty):
        gdb.write("Thread, BQL (iothread_mutex), Replay, Blocked?\n")
        for thread in gdb.inferiors()[0].threads():
            thread.switch()

            iothread = gdb.parse_and_eval("iothread_locked")
            replay = gdb.parse_and_eval("replay_locked")

            frame = gdb.selected_frame()
            if frame.name() == "__lll_lock_wait":
                frame.older().select()
                mutex = gdb.parse_and_eval("mutex")
                owner = gdb.parse_and_eval("mutex->__data.__owner")
                blocked = ("__lll_lock_wait waiting on %s from %d" %
                           (mutex, owner))
            else:
                blocked = "not blocked"

            gdb.write("%d/%d, %s, %s, %s\n" % (thread.num, thread.ptid[1],
                                               iothread, replay, blocked))
    def invoke(self, arg, from_tty):
        if len(arg) == 0:
            filename = "config.txt"
        else:
            filename = arg

        try:
            py_config_ptr = gdb.parse_and_eval("&kernel_config_data")
            py_config_ptr_end = gdb.parse_and_eval("&kernel_config_data_end")
            py_config_size = py_config_ptr_end - py_config_ptr
        except gdb.error as e:
            raise gdb.GdbError("Can't find config, enable CONFIG_IKCONFIG?")

        inf = gdb.inferiors()[0]
        zconfig_buf = utils.read_memoryview(inf, py_config_ptr,
                                            py_config_size).tobytes()

        config_buf = zlib.decompress(zconfig_buf, 16)
        with open(filename, 'wb') as f:
            f.write(config_buf)

        gdb.write("Dumped config to " + filename + "\n")
Exemple #32
0
    def stop(self):
        registers = ["$edx"]
        for register in registers:
            try:
                length = int(
                    gdb.parse_and_eval('$ecx'))  # IDA Demo 6.6 + GDB FTW!
                p = struct.pack(">i", length)
                length = struct.unpack("<I", p)[0]
                address = gdb.parse_and_eval(register)
                address = int(address)
                p = struct.pack(">i", address)
                u = struct.unpack("<I", p)
                address = u[0]
            except:
                traceback.print_exc()
                return True

            try:
                data = gdb.inferiors()[0].read_memory(address, length)
                # reduce noise by checking for password ("passsword12345"), not strictly required :-)
                # if "70617373776f72643132333435" in str(binascii.hexlify(data)):
                # self.trailing_calls = 1
                print(register, binascii.hexlify(data), length)
                out.write("%s %s %s\n" %
                          (register, binascii.hexlify(data), length))
                out.flush()
                # elif self.trailing_calls > 0:
                #    print(register, binascii.hexlify(data), length)
                #    self.trailing_calls = self.trailing_calls - 1
            except gdb.MemoryError:
                traceback.print_exc()
                return True
            except:
                traceback.print_exc()
                return True

        # return False to continue the execution of the program
        return False
    def invoke(self, arg, from_tty):
        print("\nBlocked threads:")
        print("*****************************************************")
        threads = {}
        for process in gdb.inferiors():
            for thread in process.threads():
                trd = Thread()
                trd.threadId = thread.ptid[1]
                thread.switch()
                frame = gdb.selected_frame()
                while frame:
                    frame.select()
                    name = frame.name()
                    if name is None:
                        name = "??"
                    if "pthread_mutex_lock" in name:
                        trd.waitOnThread = int(
                            gdb.execute("print mutex.__data.__owner",
                                        to_string=True).split()[2])
                    trd.frames.append(name)
                    frame = frame.older()
                threads[trd.threadId] = trd

        for (tid, thread) in threads.items():
            if thread.waitOnThread:
                if thread.waitOnThread in threads and threads[
                        thread.waitOnThread].waitOnThread == thread.threadId:
                    if thread.threadId == thread.waitOnThread:
                        print("SELFLOCK -> Thread {0} locked itself".format(
                            thread.threadId))
                    else:
                        print("DEADLOCK -> Thread {0} waits for thread {1}".
                              format(thread.threadId, thread.waitOnThread))
                else:
                    print("BLOCKED  -> Thread {0} is blocked by thread {1}".
                          format(thread.threadId, thread.waitOnThread))

        print("*****************************************************\n")
Exemple #34
0
    def invoke(self, arg, from_tty):
        pid = str(gdb.inferiors()[0].pid)
        cmd = "cat /proc/" + pid + "/maps | grep "
        res = subprocess.Popen(cmd + arg, shell=True,
                               stdout=subprocess.PIPE).communicate()[0]
        if (len(res) == 0):
            print '**** Library %s not found. ' % arg
            print '  Do:  cat /proc/%d/maps to see all libs.' % pid
            return

        lib = subprocess.Popen(
            cmd + arg + " | head -1 | sed -e 's%[^/]*\\(/.*\\)%\\1%'",
            shell=True,
            stdout=subprocess.PIPE).communicate()[0].rstrip()

        segAddr=subprocess.Popen(cmd + lib + "| grep r-xp |"\
                                 "sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'",
                                 shell=True, stdout=subprocess.PIPE).communicate()[0]
        segDataAddr = subprocess.Popen(
            cmd + lib + " | grep rw-p | sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'",
            shell=True,
            stdout=subprocess.PIPE).communicate()[0]

        textOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.text ' | " \
                                    "sed -e 's%^.*text[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                    shell=True, stdout=subprocess.PIPE).communicate()[0]
        dataOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.data ' | "\
                                    "sed -e 's%^.*data[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                    shell=True, stdout=subprocess.PIPE).communicate()[0]
        bssOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.bss ' | "\
                                   "sed -e 's%^.*bss[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'",
                                   shell=True, stdout=subprocess.PIPE).communicate()[0]

        gdb.execute(
            "add-symbol-file " + lib + " " +
            str(long(segAddr, 16) + long(textOffset, 16)) + " -s .data " +
            str(long(segDataAddr, 16) + long(dataOffset, 16)) + " -s .bss " +
            str(long(segDataAddr, 16) + long(bssOffset, 16)), True, True)
Exemple #35
0
    def invoke(self, arg, from_tty):
        log_buf_addr = int(str(gdb.parse_and_eval("log_buf")).split()[0], 16)
        log_first_idx = int(gdb.parse_and_eval("log_first_idx"))
        log_next_idx = int(gdb.parse_and_eval("log_next_idx"))
        log_buf_len = int(gdb.parse_and_eval("log_buf_len"))

        inf = gdb.inferiors()[0]
        start = log_buf_addr + log_first_idx
        if log_first_idx < log_next_idx:
            log_buf_2nd_half = -1
            length = log_next_idx - log_first_idx
            log_buf = inf.read_memory(start, length)
        else:
            log_buf_2nd_half = log_buf_len - log_first_idx
            log_buf = inf.read_memory(start, log_buf_2nd_half) + \
                inf.read_memory(log_buf_addr, log_next_idx)

        pos = 0
        while pos < log_buf.__len__():
            length = utils.read_u16(log_buf[pos + 8:pos + 10])
            if length == 0:
                if log_buf_2nd_half == -1:
                    gdb.write("Corrupted log buffer!\n")
                    break
                pos = log_buf_2nd_half
                continue

            text_len = utils.read_u16(log_buf[pos + 10:pos + 12])
            text = log_buf[pos + 16:pos + 16 + text_len]
            time_stamp = utils.read_u64(log_buf[pos:pos + 8])

            for line in memoryview(text).tobytes().splitlines():
                gdb.write("[{time:12.6f}] {line}\n".format(time=time_stamp /
                                                           1000000000.0,
                                                           line=line))

            pos += length
Exemple #36
0
 def dump_register(self, peripheral, register, name_width=0, options=""):
     if not name_width:
         name_width = len(register.name)
     val = struct.unpack("<L", gdb.inferiors()[0].read_memory(peripheral.base_address + register.address_offset, 4))[0];
     reg_fmt = "{name:<{width}s}"
     if "f" in options:
         reg_fmt += " 0x{offset:04x}"
     if "i" in options:
         reg_fmt += " {value:032b}"
     elif "h" in options:
         reg_fmt += " {value:08x}"
     print(reg_fmt.format(name=register.name,
                          offset=register.address_offset,
                          value=val,
                          width=name_width)),
     if "x" in options:
         field_fmt = "{name}={value:0{hex_width}x}"
         active_field_fmt = "\033[32m{name}={value:0{hex_width}x}\033[0m"
     elif "b" in options:
         field_fmt = "{name}={value:0{bit_width}b}"
         active_field_fmt = "\033[32m{name}={value:0{bit_width}b}\033[0m"
     else:
         field_fmt = "{name}={value:d}"
         active_field_fmt = "\033[32m{name}={value:d}\033[0m"
     for field in register.fields:
         fieldval = (val >> field.bit_offset) & ((1 << field.bit_width) - 1)
         hex_width = (field.bit_width + 3) // 4
         if self.colorize and fieldval > 0:
             fmt = active_field_fmt
         else:
             fmt = field_fmt
         
         print(fmt.format(name=field.name,
                          value=fieldval,
                          bit_width=field.bit_width,
                          hex_width=hex_width)),
     print
    def invoke(self, arg, from_tty):
        print(
            "\n********************************************************************************"
        )
        print("Displaying blocking threads using 'blocked' command")
        threads = {}
        for process in gdb.inferiors():
            for thread in process.threads():
                trd = Thread()
                trd.threadId = thread.ptid[
                    1]  #[1] - threadId; [0] - process pid
                #print ("Thread: {0}".format(threads[-1].threadId))
                thread.switch()
                frame = gdb.selected_frame()
                while frame:
                    frame.select()
                    #print("   {0}".format(frame.name()))
                    if "pthread_mutex_lock" in frame.name():
                        trd.waitOnThread = int(
                            gdb.execute("print mutex.__data.__owner",
                                        to_string=True).split()[2])
                        #print(threads[-1].waitOnThread)
                    trd.frames.append(frame.name())
                    frame = frame.older()
                threads[trd.threadId] = trd

        for (tid, thread) in threads.items():
            if thread.waitOnThread:
                deadlockedText = "" if not threads[
                    thread.
                    waitOnThread].waitOnThread == thread.threadId else "AND DEADLOCKED"
                print("Thread: {0} waits for thread: {1} {2}".format(
                    thread.threadId, thread.waitOnThread, deadlockedText))
        print(
            "********************************************************************************"
        )
Exemple #38
0
    check_cplusplus_object("Derived", object_count)
    check_ref()


#
# Fun starts here
#
core_name = None
try:
    print "[ca_test] ==== Test Against Live Process ===="
    gdb.execute('break last_call')
    gdb.execute('set confirm off')
    gdb.execute('run')
    run_tests()

    print "[ca_test] ==== Test Against Core Dump ===="
    core_name = 'core.' + str(gdb.inferiors()[0].pid)
    gdb.execute('gcore ' + core_name)
    gdb.execute('kill')
    gdb.execute('core ' + core_name)
    run_tests()

    print "[ca_test] Pass"
except Exception as e:
    print("[ca_test] " + e.message)
    print("[ca_test] Test failed")

if core_name and os.path.isfile(core_name):
    os.unlink(core_name)
gdb.execute('quit')
Exemple #39
0
def get_inferiors():
    yield from gdb.inferiors()
Exemple #40
0
 def inferiors():
     return [InferiorProxy(i) for i in gdb.inferiors()]
Exemple #41
0
 def get_val(self):
     addr = self.get_address()
     buff = gdb.inferiors()[0].read_memory(addr, 4)
     return struct.unpack("I", buff)[0]
Exemple #42
0
    # get the current fuzz string (and null terminate it)
    fuzz_string = get_fuzz_email() + '\0'

    # if the fuzz string is too long, we end the loop
    if len(fuzz_string) > 65000:
        break

    # allocate the space for the fuzz string on the heap
    fuzz_string_addr = malloc(len(fuzz_string) + 10)

    # set the register that holds the first argument (amd64 arch) to the address of fuzz_string
    gdb.execute('set $rdi=' + str(fuzz_string_addr))

    # write fuzz_string to that address
    inferior = gdb.inferiors()[0]
    inferior.write_memory(fuzz_string_addr, fuzz_string, len(fuzz_string))

    print 'string len: ' + str(len(fuzz_string))
    gdb.execute("x/s $rdi")

    # continue execution until the end of the function
    gdb.execute('finish')

    # check if the program has crashed
    if gdb_utils.execute_output('info checkpoints')[0] == 'No checkpoints.':
        print ''
        print '#'
        print '# The program has crashed! Stack exhaustion or bug???'
        print '# Now is your turn, have fun! :P'
        print '#'
def info_inferiors():
    all_inferiors = sorted(gdb.inferiors(), key=inf_num)
    for i in gdb.inferiors():
        print("Inferior %d, Connection #%d: %s" %
              (i.num, i.connection_num,
               make_target_connection_string(i.connection)))
Exemple #44
0
 def invoke(self, arg, from_tty):
     pid = str(gdb.inferiors()[0].pid)
     print "cat /proc/" + pid + "/maps"
     print gdb.execute("shell cat /proc/" + pid + "/maps", True, True)
Exemple #45
0
    def invoke(self, arg, from_tty):
        inf = gdb.inferiors()[0]

        # read in prb structure
        prb_addr = int(
            str(gdb.parse_and_eval("(void *)'printk.c'::prb")).split()[0], 16)
        sz = printk_ringbuffer_type.get_type().sizeof
        prb = utils.read_memoryview(inf, prb_addr, sz).tobytes()

        # read in descriptor ring structure
        off = printk_ringbuffer_type.get_type()['desc_ring'].bitpos // 8
        addr = prb_addr + off
        sz = prb_desc_ring_type.get_type().sizeof
        desc_ring = utils.read_memoryview(inf, addr, sz).tobytes()

        # read in descriptor array
        off = prb_desc_ring_type.get_type()['count_bits'].bitpos // 8
        desc_ring_count = 1 << utils.read_u32(desc_ring, off)
        desc_sz = prb_desc_type.get_type().sizeof
        off = prb_desc_ring_type.get_type()['descs'].bitpos // 8
        addr = utils.read_ulong(desc_ring, off)
        descs = utils.read_memoryview(inf, addr,
                                      desc_sz * desc_ring_count).tobytes()

        # read in text data ring structure
        off = printk_ringbuffer_type.get_type()['text_data_ring'].bitpos // 8
        addr = prb_addr + off
        sz = prb_data_ring_type.get_type().sizeof
        text_data_ring = utils.read_memoryview(inf, addr, sz).tobytes()

        # read in text data
        off = prb_data_ring_type.get_type()['size_bits'].bitpos // 8
        text_data_sz = 1 << utils.read_u32(text_data_ring, off)
        off = prb_data_ring_type.get_type()['data'].bitpos // 8
        addr = utils.read_ulong(text_data_ring, off)
        text_data = utils.read_memoryview(inf, addr, text_data_sz).tobytes()

        counter_off = atomic_long_type.get_type()['counter'].bitpos // 8

        sv_off = prb_desc_type.get_type()['state_var'].bitpos // 8

        off = prb_desc_type.get_type()['text_blk_lpos'].bitpos // 8
        begin_off = off + (prb_data_blk_lpos_type.get_type()['begin'].bitpos //
                           8)
        next_off = off + (prb_data_blk_lpos_type.get_type()['next'].bitpos //
                          8)

        off = prb_desc_type.get_type()['info'].bitpos // 8
        ts_off = off + printk_info_type.get_type()['ts_nsec'].bitpos // 8
        len_off = off + printk_info_type.get_type()['text_len'].bitpos // 8

        # definitions from kernel/printk/printk_ringbuffer.h
        desc_sv_bits = utils.get_long_type().sizeof * 8
        desc_committed_mask = 1 << (desc_sv_bits - 1)
        desc_reuse_mask = 1 << (desc_sv_bits - 2)
        desc_flags_mask = desc_committed_mask | desc_reuse_mask
        desc_id_mask = ~desc_flags_mask

        # read in tail and head descriptor ids
        off = prb_desc_ring_type.get_type()['tail_id'].bitpos // 8
        tail_id = utils.read_u64(desc_ring, off + counter_off)
        off = prb_desc_ring_type.get_type()['head_id'].bitpos // 8
        head_id = utils.read_u64(desc_ring, off + counter_off)

        did = tail_id
        while True:
            ind = did % desc_ring_count
            desc_off = desc_sz * ind

            # skip non-committed record
            state = utils.read_u64(
                descs, desc_off + sv_off + counter_off) & desc_flags_mask
            if state != desc_committed_mask:
                if did == head_id:
                    break
                did = (did + 1) & desc_id_mask
                continue

            begin = utils.read_ulong(descs,
                                     desc_off + begin_off) % text_data_sz
            end = utils.read_ulong(descs, desc_off + next_off) % text_data_sz

            # handle data-less record
            if begin & 1 == 1:
                text = ""
            else:
                # handle wrapping data block
                if begin > end:
                    begin = 0

                # skip over descriptor id
                text_start = begin + utils.get_long_type().sizeof

                text_len = utils.read_u16(descs, desc_off + len_off)

                # handle truncated message
                if end - text_start < text_len:
                    text_len = end - text_start

                text = text_data[text_start:text_start + text_len].decode(
                    encoding='utf8', errors='replace')

            time_stamp = utils.read_u64(descs, desc_off + ts_off)

            for line in text.splitlines():
                msg = u"[{time:12.6f}] {line}\n".format(time=time_stamp /
                                                        1000000000.0,
                                                        line=line)
                # With python2 gdb.write will attempt to convert unicode to
                # ascii and might fail so pass an utf8-encoded str instead.
                if sys.hexversion < 0x03000000:
                    msg = msg.encode(encoding='utf8', errors='replace')
                gdb.write(msg)

            if did == head_id:
                break
            did = (did + 1) & desc_id_mask
Exemple #46
0
 def pid(self):
     return gdb.inferiors()[0].pid
Exemple #47
0
 def invoke(self, arg, from_tty):
     pid = str(gdb.inferiors()[0].pid)
     print "ls -l /proc/" + pid + "/fd"
     print gdb.execute("shell ls -l /proc/" + pid + "/fd", True, True)
Exemple #48
0
def GetAttachedProcesses():
    processes = ', '.join(["%d" % (inferior.pid) for inferior in gdb.inferiors() if inferior.pid])
    return '[%s]' % (processes)
Exemple #49
0
def SetTargetProcess(pid):
    match = [i for i in gdb.inferiors() if i.pid == pid]
    if not match:
        raise ValueError('No such process %i' % (pid))
    # Last thread seems to be the main thread, switch to that
    threads = match[0].threads()[-1].switch()
Exemple #50
0
    def show_image(name, flag, width, height, n_channel, line_step,
                   data_address, data_symbol):
        """ Copies the image data to a PIL image and shows it.

        Args:
            width: The image width, in pixels.
            height: The image height, in pixels.
            n_channel: The number of channels in image.
            line_step: The offset to change to pixel (i+1, j) being
                in pixel (i, j), in bytes.
            data_address: The address of image data in memory.
            data_symbol: Python struct module code to the image data type.
        """

        width = int(width)
        height = int(height)
        n_channel = int(n_channel)
        line_step = int(line_step)
        data_address = int(data_address)
        print(data_address)
        infe = gdb.inferiors()

        memory_data = infe[0].read_memory(data_address, line_step * height)

        # Calculate the memory padding to change to the next image line.
        # Either due to memory alignment or a ROI.
        if data_symbol in ('b', 'B'):
            elem_size = 1
        elif data_symbol in ('h', 'H'):
            elem_size = 2
        elif data_symbol in ('i', 'f'):
            elem_size = 4
        elif data_symbol == 'd':
            elem_size = 8
        padding = line_step - width * n_channel * elem_size

        # Format memory data to load into the image.
        image_data = []
        if n_channel == 1:
            mode = 'L'
            fmt = '%d%s%dx' % (width, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        elif n_channel == 3:
            mode = 'RGB'
            fmt = '%d%s%dx' % (width * 3, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        else:
            gdb.write('Only 1 or 3 channels supported\n', gdb.STDERR)
            return

        scale_alpha = 1
        scale_beta = 0
        # Fit the opencv elemente data in the PIL element data
        if data_symbol == 'b':
            image_data = [i + 128 for i in image_data]
        elif data_symbol == 'H':
            image_data = [i >> 8 for i in image_data]
        elif data_symbol == 'h':
            image_data = [(i + 32768) >> 8 for i in image_data]
        elif data_symbol == 'i':
            image_data = [(i + 2147483648) >> 24 for i in image_data]
        elif data_symbol in ('f', 'd'):
            # A float image is discretized in 256 bins for display.
            max_image_data = float(max(image_data))
            min_image_data = float(min(image_data))
            img_range = max_image_data - min_image_data
            print('Image max/min - range: %1.2f / %1.2f - %1.20f' %
                  (max_image_data, min_image_data, img_range))
            if img_range > 0.00000000001:
                scale_beta = min_image_data
                scale_alpha = img_range / 255.0
                image_data = [int(255 * (i - min_image_data) / img_range) \
                              for i in image_data]
            else:
                image_data = [0 for i in image_data]

        dump_data = []
        if n_channel == 3:
            for i in range(0, len(image_data), 3):
                dump_data.append(
                    (image_data[i + 2], image_data[i + 1], image_data[i]))
        if n_channel == 1:
            dump_data = image_data

        # Show image.
        if n_channel == 1:
            img = Image.new(mode, (width, height))
        if n_channel == 3:
            img = Image.new(mode, (width, height), color=(0, 0, 0))

        img.putdata(dump_data)
        img = np.array(img)

        fig = pl.figure()
        fig.canvas.set_window_title(name)
        b = fig.add_subplot(111)

        if n_channel == 1:
            #b.imshow(img, cmap = pl.cm.Greys_r, interpolation='nearest')
            b.imshow(img, cmap='jet', interpolation='nearest')
        elif n_channel == 3:
            b.imshow(img, interpolation='nearest')

        def format_coord(x, y):
            col = int(x + 0.5)
            row = int(y + 0.5)
            if col >= 0 and col < width and row >= 0 and row < height:
                if n_channel == 1:
                    z = float(
                        float(img[row, col]) * scale_alpha) + float(scale_beta)
                    return '(%d, %d), [%1.2f]' % (col, row, z)
                elif n_channel == 3:
                    z0 = img[row, col, 0] * scale_alpha + scale_beta
                    z1 = img[row, col, 1] * scale_alpha + scale_beta
                    z2 = img[row, col, 2] * scale_alpha + scale_beta
                    return '(%d, %d), [%1.2f, %1.2f, %1.2f]' % (col, row, z0,
                                                                z1, z2)
            else:
                return 'x=%d, y=%d' % (col, row)

        b.format_coord = format_coord
        if (flag == 'block'):
            pl.show(block=True)
        else:
            pl.show(block=False)
#!/usr/bin/gdb -P
import sys
import gdb

def on_stop(p):
  (status, value) = p.status
  if status != gdb.EXIT:
    gdb.cli ()
  else:
    sys.exit (value)

gdb.execute("b host.nim:71")
gdb.execute("r")

print(gdb.inferiors())

if len(gdb.inferiors()) > 0:
    c_process = gdb.selected_inferior()

    print(c_process)
    print(c_process.threads())
    print(c_process.pid)
    print(c_process.num)

Exemple #52
0
    def show_image(width, height, n_channel, line_step, data_address, data_symbol):
        """ Copies the image data to a PIL image and shows it.

        Args:
            width: The image width, in pixels.
            height: The image height, in pixels.
            n_channel: The number of channels in image.
            line_step: The offset to change to pixel (i+1, j) being
                in pixel (i, j), in bytes.
            data_address: The address of image data in memory.
            data_symbol: Python struct module code to the image data type.
        """
        width = int(width)
        height = int(height)
        n_channel = int(n_channel)
        line_step = int(line_step)
        data_address = int(data_address)

        infe = gdb.inferiors()
        memory_data = infe[0].read_memory(data_address, line_step * height)

        # Calculate the memory padding to change to the next image line.
        # Either due to memory alignment or a ROI.
        if data_symbol in ('b', 'B'):
            elem_size = 1
        elif data_symbol in ('h', 'H'):
            elem_size = 2
        elif data_symbol in ('i', 'f'):
            elem_size = 4
        elif data_symbol == 'd':
            elem_size = 8
        padding = line_step - width * n_channel * elem_size

        # Format memory data to load into the image.
        image_data = []
        if n_channel == 1:
            mode = 'L'
            fmt = '%d%s%dx' % (width, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        elif n_channel == 3:
            mode = 'RGB'
            fmt = '%d%s%dx' % (width * 3, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        else:
            gdb.write('Only 1 or 3 channels supported\n', gdb.STDERR)
            return

        # Fit the opencv elemente data in the PIL element data
        if data_symbol == 'b':
            image_data = [i+128 for i in image_data]
        elif data_symbol == 'H':
            image_data = [i>>8 for i in image_data]
        elif data_symbol == 'h':
            image_data = [(i+32768)>>8 for i in image_data]
        elif data_symbol == 'i':
            image_data = [(i+2147483648)>>24 for i in image_data]
        elif data_symbol in ('f','d'):
            # A float image is discretized in 256 bins for display.
            max_image_data = max(image_data)
            min_image_data = min(image_data)
            img_range = max_image_data - min_image_data
            if img_range > 0:
                image_data = [int(255 * (i - min_image_data) / img_range) \
                              for i in image_data]
            else:
                image_data = [0 for i in image_data]


        if n_channel == 3:
            # OpenCV stores the channels in BGR mode. Convert to RGB while packing.
            image_data = zip(*[image_data[i::3] for i in [2, 1, 0]])

        # Show image.
        img = Image.new(mode, (width, height))
        img.putdata(image_data)
        img = pl.asarray(img);

        fig = pl.figure()
        b = fig.add_subplot(111)
        if n_channel == 1:
            b.imshow(img, cmap = pl.cm.Greys_r, interpolation='nearest')
        elif n_channel == 3:
            b.imshow(img, interpolation='nearest')

        def format_coord(x, y):
            col = int(x+0.5)
            row = int(y+0.5)
            if col>=0 and col<width and row>=0 and row<height:
                if n_channel == 1:
                    z = img[row,col]
                    return '(%d, %d), [%1.2f]'%(col, row, z)
                elif n_channel == 3:
                    z0 = img[row,col,0]
                    z1 = img[row,col,1]
                    z2 = img[row,col,2]
                    return '(%d, %d), [%1.2f, %1.2f, %1.2f]'%(col, row, z0, z1, z2)
            else:
                return 'x=%d, y=%d'%(col, row)

        b.format_coord = format_coord
        pl.show()
Exemple #53
0
#!/usr/bin/env python3

import os, sys, gdb

if len(gdb.inferiors()) == 1:
    gdb.execute("set env IN_GDB = 1")
    gdb.execute("set auto-load off")

    sys.stdout.write("Are you loading the script [Y]/n ? ")
    sys.stdout.flush()
    ans = sys.stdin.readline()

    if ans[0] != 'n' and ans[0] != 'N':
        gdbfile = os.path.dirname(__file__) + "/pal.gdb"
        gdb.execute("source " + gdbfile)
        sys.stdout.write("script %s loaded\n" % gdbfile)
Exemple #54
0
    def get_vals(width, height, n_channel, line_step, data_address,
                 data_symbol):
        """ Copies the image data to a PIL image and shows it.

            Args:
                width: The image width, in pixels.
                height: The image height, in pixels.
                n_channel: The number of channels in image.
                line_step: The offset to change to pixel (i+1, j) being
                    in pixel (i, j), in bytes.
                data_address: The address of image data in memory.
                data_symbol: Python struct module code to the image data type.
            """
        width = int(width)
        height = int(height)
        n_channel = int(n_channel)
        line_step = int(line_step)
        data_address = int(data_address)

        infe = gdb.inferiors()
        memory_data = infe[0].read_memory(data_address, line_step * height)

        # Calculate the memory padding to change to the next image line.
        # Either due to memory alignment or a ROI.
        if data_symbol in ('b', 'B'):
            elem_size = 1
        elif data_symbol in ('h', 'H'):
            elem_size = 2
        elif data_symbol in ('i', 'f'):
            elem_size = 4
        elif data_symbol == 'd':
            elem_size = 8
        padding = line_step - width * n_channel * elem_size

        # Format memory data to load into the image.
        image_data = []
        if n_channel == 1:
            mode = 'L'
            fmt = '%d%s%dx' % (width, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        elif n_channel == 3:
            mode = 'RGB'
            fmt = '%d%s%dx' % (width * 3, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        else:
            gdb.write('Only 1 or 3 channels supported\n', gdb.STDERR)
            return

        # Fit the opencv elemente data in the PIL element data
        if data_symbol == 'b':
            image_data = [i + 128 for i in image_data]
        elif data_symbol == 'H':
            image_data = [i >> 8 for i in image_data]
        elif data_symbol == 'h':
            image_data = [(i + 32768) >> 8 for i in image_data]
        elif data_symbol == 'i':
            image_data = [(i + 2147483648) >> 24 for i in image_data]

        img = None
        if mode == 'L':
            img = np.reshape(image_data, (height, width))
        elif mode == 'RGB':
            img = np.reshape(image_data, (height, width, 3))
        #gdb.write(str(img))
        return img
Exemple #55
0
 def _read_memory(self, start_address, length):
     start_address = self._pointer_value(start_address)
     inferior = gdb.inferiors()[0]
     memory = inferior.read_memory(start_address, length)
     memory = bytes(memory)
     return memory
Exemple #56
0
 def set_val(self, value):
     addr = self.get_address()
     gdb.inferiors()[0].write_memory(addr, struct.pack("I", value))
Exemple #57
0
    def show_image(width, height, n_channel, line_step, data_address,
                   data_symbol):
        """ Copies the image data to a PIL image and shows it.

        Args:
            width: The image width, in pixels.
            height: The image height, in pixels.
            n_channel: The number of channels in image.
            line_step: The offset to change to pixel (i+1, j) being
                in pixel (i, j), in bytes.
            data_address: The address of image data in memory.
            data_symbol: Python struct module code to the image data type.
        """
        width = int(width)
        height = int(height)
        n_channel = int(n_channel)
        line_step = int(line_step)
        data_address = int(data_address)

        infe = gdb.inferiors()
        memory_data = infe[0].read_memory(data_address, line_step * height)

        # Calculate the memory padding to change to the next image line.
        # Either due to memory alignment or a ROI.
        if data_symbol in ('b', 'B'):
            elem_size = 1
        elif data_symbol in ('h', 'H'):
            elem_size = 2
        elif data_symbol in ('i', 'f'):
            elem_size = 4
        elif data_symbol == 'd':
            elem_size = 8
        padding = line_step - width * n_channel * elem_size

        # Format memory data to load into the image.
        image_data = []
        if n_channel == 1:
            mode = 'L'
            fmt = '%d%s%dx' % (width, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        elif n_channel == 3:
            mode = 'RGB'
            fmt = '%d%s%dx' % (width * 3, data_symbol, padding)
            for line in chunker(memory_data, line_step):
                image_data.extend(struct.unpack(fmt, line))
        else:
            gdb.write('Only 1 or 3 channels supported\n', gdb.STDERR)
            return

        # Fit the opencv elemente data in the PIL element data
        if data_symbol == 'b':
            image_data = [i + 128 for i in image_data]
        elif data_symbol == 'H':
            image_data = [i >> 8 for i in image_data]
        elif data_symbol == 'h':
            image_data = [(i + 32768) >> 8 for i in image_data]
        elif data_symbol == 'i':
            image_data = [(i + 2147483648) >> 24 for i in image_data]
        elif data_symbol in ('f', 'd'):
            # A float image is discretized in 256 bins for display.
            max_image_data = max(image_data)
            min_image_data = min(image_data)
            img_range = max_image_data - min_image_data
            if img_range > 0:
                image_data = [
                    int(255 * (i - min_image_data) / img_range)
                    for i in image_data
                ]
            else:
                image_data = [0 for i in image_data]

        if n_channel == 3:
            # OpenCV stores the channels in BGR mode. Convert to RGB while packing.
            image_data = list(zip(*[image_data[i::3] for i in [2, 1, 0]]))

        # Show image.
        img = Image.new(mode, (width, height))
        img.putdata(image_data)
        img.show()
Exemple #58
0
 def has_target():
     return len(gdb.inferiors()) > 0
Exemple #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)
Exemple #60
0
 def __init__(self):
     super(LoadThis, self).__init__("loadthis", gdb.COMMAND_DATA)
     self.gdb_inf = gdb.inferiors()[0]