'Simple profiling to count executed instructions in the program
Usage:
MYNAME count [keyword]
default is to count instructions inside the program only
count = 0: run until end of execution
keyword: only display stats for instructions matched it'

def profile(self, *arg):

    (count, keyword) = normalize_argv(arg, 2)
    if (count is None):
        self._missing_argument()
    if (not self._is_running()):
        return
    if ((keyword is None) or (keyword == 'all')):
        keyword = ''
    keyword = keyword.replace('    ', '').split(',')
    peda.save_user_command('hook-stop')
    msg(('Stepping    %s    instructions,    Ctrl-C    to    stop...' % (('%d' % count) if count else 'all')))
    if (count == 0):
        count = (-1)
    stats = {}
    total = 0
    binmap = peda.get_vmmap('binary')
    try:
        while (count != 0):
            pc = peda.getreg('pc')
            if (not peda.is_address(pc)):
                break
            code = peda.get_disasm(pc)
            if (not code):
                break
            if peda.is_address(pc, binmap):
                for k in keyword:
                    if (k in code.split(': DCTB ')[(-1)]):
                        code = code.strip('=>').strip()
                        stats.setdefault(code, 0)
                        stats[code] += 1
                        break
                peda.execute_redirect('stepi', silent=True)
            else:
                peda.execute_redirect('stepi', silent=True)
                peda.execute_redirect('finish', silent=True)
            count -= 1
            total += 1
    except:
        pass
    peda.restore_user_command('hook-stop')
    text = ('Executed    %d    instructions\n' % total)
    text += ('%s    %s\n' % (blue('Run-count', 'bold'), blue('Instruction', 'bold')))
    for (code, count) in sorted(stats.items(), key=(lambda x: x[1]), reverse=True):
        text += ('%8d:    %s\n' % (count, code))
    pager(text)
    return
