source: doc/theses/lynn_tran_SE499/SE499-master/utils-gdb.py @ e0116c4e

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since e0116c4e was bd07b15, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

add comments

  • Property mode set to 100644
File size: 22.2 KB
Line 
1#
2# Copyright (C) Lynn Tran, Jiachen Zhang 2018
3#
4# utils-gdb.py --
5#
6# Author           : Lynn Tran
7# Created On       : Mon Oct 1 22:06:09 2018
8# Last Modified By : Peter A. Buhr
9# Last Modified On : Thu Dec 20 22:11:23 2018
10# Update Count     : 5
11#
12
13"""
14To run this extension, the python name has to be as same as one of the loaded library
15Additionally, the file must exist in a folder which is in gdb's safe path
16"""
17import collections
18import gdb
19
20# set these signal handlers with some settings (nostop, noprint, pass)
21gdb.execute('handle SIGALRM nostop noprint pass')
22gdb.execute('handle SIGUSR1 nostop noprint pass')
23
24# GDB types for various structures/types in uC++
25uCluster_ptr_type = gdb.lookup_type('uCluster').pointer()
26uClusterDL_ptr_type = gdb.lookup_type('uClusterDL').pointer()
27uBaseTask_ptr_type = gdb.lookup_type('uBaseTask').pointer()
28uBaseTaskDL_ptr_type = gdb.lookup_type('uBaseTaskDL').pointer()
29int_ptr_type = gdb.lookup_type('int').pointer()
30
31# A named tuple representing information about a stack
32StackInfo = collections.namedtuple('StackInfo', 'sp fp pc')
33
34# A global variable to keep track of stack information as one context switches
35# from one task to another task
36STACK = []
37
38# A global variable to keep all system task name
39SysTask_Name = ["uLocalDebuggerReader", "uLocalDebugger", "uProcessorTask", "uBootTask", "uSystemTask", 
40"uProcessorTask", "uPthread", "uProfiler"]
41
42def get_addr(addr):
43    """
44    NOTE: sketchy solution to retrieve address. There is a better solution...
45    @addr: str of an address that can be in a format 0xfffff <type of the object
46    at this address>
47    Return: str of just the address
48    """
49    str_addr = str(addr)
50    ending_addr_index = str_addr.find('<')
51    if ending_addr_index == -1:
52        return str(addr)
53    return str_addr[:ending_addr_index].strip()
54
55def print_usage(msg):
56    """
57    Print out usage message
58    @msg: str
59    """
60    print('Usage: ' + msg)
61
62def get_argv_list(args):
63    """
64    Split the argument list in string format, where each argument is separated
65    by whitespace delimiter, to a list of arguments like argv
66    @args: str of arguments
67    Return:
68        [] if args is an empty string
69        list if args is not empty
70    """
71    # parse the string format of arguments and return a list of arguments
72    argv = args.split(' ')
73    if len(argv) == 1 and argv[0] == '':
74        return []
75    return argv
76
77def get_cluster_root():
78    """
79    Return: gdb.Value of globalClusters.root (is an address)
80    """
81    cluster_root = gdb.parse_and_eval('uKernelModule::globalClusters.root')
82    if cluster_root.address == 0x0:
83        print('No clusters, program terminated')
84    return cluster_root
85
86def lookup_cluster_by_name(cluster_name):
87    """
88    Look up a cluster given its ID
89    @cluster_name: str
90    Return: gdb.Value
91    """
92    cluster_root = get_cluster_root()
93    if cluster_root.address == 0x0:
94        return cluster_root.address
95
96    # lookup for the task associated with the id
97    cluster = 0x0
98    curr = cluster_root
99    while True:
100        if curr['cluster_']['name'].string() == cluster_name:
101            cluster = curr['cluster_'].address
102            break
103        curr = curr['next'].cast(uClusterDL_ptr_type)
104        if curr == cluster_root:
105            break
106
107    if cluster == 0x0:
108        print("Cannot find a cluster with the name: {}.".format(cluster_name))
109    return cluster
110
111############################ COMMAND IMPLEMENTATION #########################
112
113class Clusters(gdb.Command):
114    """Print out the list of available clusters"""
115    usage_msg = 'cluster'
116    def __init__(self):
117        super(Clusters, self).__init__('clusters', gdb.COMMAND_USER)
118
119    def invoke(self, arg, from_tty):
120        """
121        Iterate through a circular linked list of clusters and print out its
122        name along with address associated to each cluster
123        @arg: str
124        @from_tty: bool
125        """
126        argv = get_argv_list(arg)
127        if len(argv) != 0:
128            print_usage(self.usage_msg)
129            return
130
131        cluster_root = get_cluster_root()
132        if cluster_root.address == 0x0:
133            return
134        curr = cluster_root
135        print('{:>20}{:>18}'.format('Name', 'Address'))
136
137        while True:
138            print('{:>20}{:>18}'.format(curr['cluster_']['name'].string(),
139                                        str(curr['cluster_'].reference_value())[1:]))
140            curr = curr['next'].cast(uClusterDL_ptr_type)
141            if curr == cluster_root:
142                break
143
144class ClusterProcessors(gdb.Command):
145    """Display a list of all info about all available processors on a particular cluster"""
146    usage_msg = 'processors <cluster_name>'
147    def __init__(self):
148        super(ClusterProcessors, self).__init__('processors', gdb.COMMAND_USER)
149
150    def invoke(self, arg, from_tty):
151        """
152        Iterate through a circular linked list of tasks and print out all
153        info about each processor in that cluster
154        @arg: str
155        @from_tty: bool
156        """
157        argv = get_argv_list(arg)
158        if len(argv) > 1:
159            print_usage(self.usage_msg)
160            return
161
162        if len(argv) == 0:
163            cluster_address = lookup_cluster_by_name("userCluster")
164        else:
165            cluster_address = lookup_cluster_by_name(argv[0])
166
167        if cluster_address == 0x0:
168            return
169
170        processor_root = cluster_address.cast(uCluster_ptr_type)['processorsOnCluster']['root']
171        if processor_root.address == 0x0:
172            print('There are no processors for cluster at address: {}'.format(cluster_address))
173            return
174
175        uProcessorDL_ptr_type = gdb.lookup_type('uProcessorDL').pointer()
176        print('{:>18}{:>20}{:>20}{:>20}'.format('Address', 'PID', 'Preemption', 'Spin'))
177        curr = processor_root
178
179        while True:
180            processor = curr['processor_']
181            print('{:>18}{:>20}{:>20}{:>20}'.format(get_addr(processor.address),
182                        str(processor['pid']), str(processor['preemption']),
183                        str(processor['spin'])))
184
185            curr = curr['next'].cast(uProcessorDL_ptr_type)
186            if curr == processor_root:
187                break
188
189class Task(gdb.Command):
190    usage_msg = """
191    task                            : print userCluster tasks, application tasks only
192    task <clusterName>              : print cluster tasks, application tasks only
193    task all                        : print all clusters, all tasks
194    task <id>                       : context switch to task id on userCluster
195    task 0x<address>                : context switch to task on any cluster
196    task <id> <clusterName>         : context switch to task on specified cluster
197    """
198    def __init__(self):
199        # The first parameter of the line below is the name of the command. You
200        # can call it 'uc++ task'
201        super(Task, self).__init__('task', gdb.COMMAND_USER)
202
203    ############################ AUXILIARY FUNCTIONS #########################
204
205    def print_tasks_by_cluster_all(self, cluster_address):
206        """
207        Display a list of all info about all available tasks on a particular cluster
208        @cluster_address: gdb.Value
209        """
210        cluster_address = cluster_address.cast(uCluster_ptr_type)
211        task_root = cluster_address['tasksOnCluster']['root']
212
213        if task_root.address == 0x0:
214            print('There are no tasks for cluster at address: {}'.format(cluster_address))
215            return
216
217        print('{:>4}{:>20}{:>18}{:>25}'.format('ID', 'Task Name', 'Address', 'State'))
218        curr = task_root
219        task_id = 0
220        systask_id = -1
221
222        btstr = gdb.execute('bt', to_string = True)
223        break_addr = btstr.splitlines()[0].split('this=',1)[1].split(',')[0].split(')')[0]
224
225        while True:
226            global SysTask_Name
227            if (curr['task_']['name'].string() in SysTask_Name):
228                if str(curr['task_'].reference_value())[1:] == break_addr:
229                    print(
230                            ('{:>4}{:>20}{:>18}{:>25}'.format('* '+str(systask_id), curr['task_']['name'].string(),
231                            str(curr['task_'].reference_value())[1:],
232                            str(curr['task_']['state']))
233                        )
234                    )
235                else:
236                    print(
237                            ('{:>4}{:>20}{:>18}{:>25}'.format(systask_id, curr['task_']['name'].string(),
238                            str(curr['task_'].reference_value())[1:],
239                            str(curr['task_']['state']))
240                        )
241                    )
242                systask_id -= 1
243            else:
244                if str(curr['task_'].reference_value())[1:] == break_addr:
245                    print('{:>4}{:>20}{:>18}{:>25}'.format('* '+str(task_id), curr['task_']['name'].string(),
246                                                           str(curr['task_'].reference_value())[1:],
247                                                           str(curr['task_']['state']))
248                    )
249                else:
250                    print('{:>4}{:>20}{:>18}{:>25}'.format(task_id, curr['task_']['name'].string(),
251                                                           str(curr['task_'].reference_value())[1:],
252                                                           str(curr['task_']['state']))
253                    )
254                task_id += 1
255
256            curr = curr['next'].cast(uBaseTaskDL_ptr_type)
257            if curr == task_root:
258                break
259
260    def print_tasks_by_cluster_address_all(self, cluster_address):
261        """
262        Display a list of all info about all available tasks on a particular cluster
263        @cluster_address: str
264        """
265        # Iterate through a circular linked list of tasks and print out its
266        # name along with address associated to each cluster
267
268        # convert hex string to hex number
269        try:
270            hex_addr = int(cluster_address, 16)
271        except:
272            print_usage(self.usage_msg)
273            return
274
275        cluster_address = gdb.Value(hex_addr)
276        self.print_tasks_by_cluster_all(cluster_address)
277
278    def print_tasks_by_cluster_address(self, cluster_address):
279        """
280        Display a list of limited info about all available tasks on a particular cluster
281        @cluster_address: str
282        """
283        # Iterate through a circular linked list of tasks and print out its
284        # name along with address associated to each cluster
285
286        # convert hex string to hex number
287        try:
288            hex_addr = int(cluster_address, 16)
289        except:
290            print_usage(self.usage_msg)
291            return
292
293        cluster_address = gdb.Value(hex_addr).cast(uCluster_ptr_type)
294        task_root = cluster_address['tasksOnCluster']['root']
295
296        if task_root.address == 0x0:
297            print('There are no tasks for cluster at address: {}'.format(cluster_address))
298            return
299
300        print('{:>4}{:>20}{:>18}{:>25}'.format('ID', 'Task Name', 'Address', 'State'))
301        curr = task_root
302        task_id = 0
303        btstr = gdb.execute('bt', to_string = True)
304        break_addr = btstr.splitlines()[0].split('this=',1)[1].split(',')[0].split(')')[0]
305
306        while True:
307            global SysTask_Name
308            if (curr['task_']['name'].string() not in SysTask_Name):
309                if str(curr['task_'].reference_value())[1:] == break_addr:           
310                    print(
311                        ('{:>4}{:>20}{:>18}{:>25}'.format('* '+str(task_id), curr['task_']['name'].string(),
312                        str(curr['task_'].reference_value())[1:],
313                        str(curr['task_']['state']))
314                    )
315                )
316                else:
317                    print('{:>4}{:>20}{:>18}{:>25}'.format(task_id, curr['task_']['name'].string(),
318                                                           str(curr['task_'].reference_value())[1:],
319                                                           str(curr['task_']['state']))
320                    )
321
322                curr = curr['next'].cast(uBaseTaskDL_ptr_type)
323                task_id += 1
324                if curr == task_root:
325                    break
326            else:
327                curr = curr['next'].cast(uBaseTaskDL_ptr_type)
328                if curr == task_root:
329                    break
330
331    ############################ COMMAND FUNCTIONS #########################
332
333    def print_user_tasks(self):
334        """Iterate only userCluster, print only tasks and main""" 
335
336        cluster_address = lookup_cluster_by_name("userCluster")
337        if cluster_address == 0x0:
338            return
339
340        self.print_tasks_by_cluster_address(str(cluster_address))
341
342
343    def print_all_tasks(self):
344        """Iterate through each cluster, iterate through all tasks and  print out info about all the tasks
345        in those clusters"""
346        cluster_root = get_cluster_root()
347        if cluster_root.address == 0x0:
348            return
349
350        curr = cluster_root
351        print('{:>20}{:>18}'.format('Cluster Name', 'Address'))
352
353        while True:
354            addr = str(curr['cluster_'].reference_value())[1:]
355            print('{:>20}{:>18}'.format(curr['cluster_']['name'].string(), addr))
356
357            self.print_tasks_by_cluster_address_all(addr)
358            curr = curr['next'].cast(uClusterDL_ptr_type)
359            if curr == cluster_root:
360                break
361
362    def pushtask_by_address(self, task_address):
363        """Change to a new task by switching to a different stack and manually
364        adjusting sp, fp and pc
365        @task_address: str
366            2 supported format:
367                in hex format
368                    <hex_address>: literal hexadecimal address
369                    Ex: 0xffffff
370                in name of the pointer to the task
371                    "task_name": pointer of the variable name of the cluster
372                        Ex: T* s -> task_name = s
373            Return: gdb.value of the cluster's address
374        """
375        # Task address has a format "task_address", which implies that it is the
376        # name of the variable, and it needs to be evaluated
377        if task_address.startswith('"') and task_address.endswith('"'):
378            task = gdb.parse_and_eval(task_address.replace('"', ''))
379        else:
380        # Task address format does not include the quotation marks, which implies
381        # that it is a hex address
382            # convert hex string to hex number
383            try:
384                hex_addr = int(task_address, 16)
385            except:
386                print_usage(self.usage_msg)
387                return
388            task_address = gdb.Value(hex_addr)
389            task = task_address.cast(uBaseTask_ptr_type)
390
391        uContext_t_ptr_type = gdb.lookup_type('UPP::uMachContext::uContext_t').pointer()
392
393        task_state = task['state']
394        if task_state == gdb.parse_and_eval('uBaseTask::Terminate'):
395            print('Cannot switch to a terminated thread')
396            return
397        task_context = task['context'].cast(uContext_t_ptr_type)
398
399        # lookup for sp,fp and uSwitch
400        xsp = task_context['SP'] + 48
401        xfp = task_context['FP']
402        if not gdb.lookup_symbol('uSwitch'):
403            print('uSwitch symbol is unavailable')
404            return
405
406        # convert string so we can strip out the address
407        xpc = get_addr(gdb.parse_and_eval('uSwitch').address + 28)
408        # must be at frame 0 to set pc register
409        gdb.execute('select-frame 0')
410
411        # push sp, fp, pc into a global stack
412        global STACK
413        sp = gdb.parse_and_eval('$sp')
414        fp = gdb.parse_and_eval('$fp')
415        pc = gdb.parse_and_eval('$pc')
416        stack_info = StackInfo(sp = sp, fp = fp, pc = pc)
417        STACK.append(stack_info)
418
419        # update registers for new task
420        gdb.execute('set $rsp={}'.format(xsp))
421        gdb.execute('set $rbp={}'.format(xfp))
422        gdb.execute('set $pc={}'.format(xpc))
423
424    def pushtask_by_id(self, task_id, cluster_name):
425        """
426        @cluster_name: str
427        @task_id: str
428        """
429        try:
430            task_id = int(task_id)
431        except:
432            print_usage(self.usage_msg)
433            return
434
435        # retrieve the address associated with the cluster name
436        cluster_address = lookup_cluster_by_name(cluster_name)
437        if cluster_address == 0x0:
438            return
439
440        task_root = cluster_address.cast(uCluster_ptr_type)['tasksOnCluster']['root']
441        if task_root.address == 0x0:
442            print('There are no tasks on this cluster')
443            return
444
445        user_id = 0
446        task_addr = None
447        systask_id = -1 # system search id starts with negative
448
449        # lookup for the task associated with the id
450        global SysTask_Name
451        if (task_id >= 0 and cluster_name == "systemCluster"):
452            print('internal error: systemCluster does not have ID >= 0')
453            return
454        #id is a system task
455        elif task_id < 0:
456            curr = task_root
457            rootflag = False
458            while (curr['task_']['name'].string() not in SysTask_Name):
459                curr = curr['next'].cast(uBaseTaskDL_ptr_type)
460                if curr == task_root:
461                    rootflag = True
462                    break
463            if rootflag == False:
464                if task_id == systask_id:
465                    task_addr = str(curr['task_'].address)
466                else:
467                    while True:
468                        curr = curr['next'].cast(uBaseTaskDL_ptr_type)
469
470                        if (curr['task_']['name'].string() in SysTask_Name):
471                            systask_id -= 1
472                            if curr == task_root:
473                                break
474                            if task_id == systask_id:
475                                task_addr = str(curr['task_'].address)
476                                break
477
478                        if curr == task_root:
479                            break
480        #id is a user task
481        else:
482            curr = task_root
483            rootflag = False
484            while (curr['task_']['name'].string() in SysTask_Name):
485                curr = curr['next'].cast(uBaseTaskDL_ptr_type)
486                if curr == task_root:
487                    rootflag = True
488                    break
489            if rootflag == False:
490                if task_id == user_id:
491                    task_addr = str(curr['task_'].address)
492                else:
493                    while True:
494                        curr = curr['next'].cast(uBaseTaskDL_ptr_type)
495
496                        if (curr['task_']['name'].string() not in SysTask_Name):
497                            user_id += 1
498                            if curr == task_root:
499                                break
500                            if task_id == user_id:
501                                task_addr = str(curr['task_'].address)
502                                break
503
504                        if curr == task_root:
505                            break
506
507        if not task_addr:
508            print("Cannot find task ID: {}. Only have {} tasks".format(task_id,user_id))
509        else:
510            self.pushtask_by_address(task_addr)
511
512    def print_tasks_by_cluster_name(self, cluster_name):
513        """
514        Print out all the tasks available in the specified cluster
515        @cluster_name: str
516        """
517        cluster_address = lookup_cluster_by_name(cluster_name)
518        if cluster_address == 0x0:
519            return
520
521        self.print_tasks_by_cluster_all(cluster_address)
522
523    def invoke(self, arg, from_tty):
524        """
525        @arg: str
526        @from_tty: bool
527        """
528        argv = get_argv_list(arg)
529        if len(argv) == 0:
530            # print tasks
531            self.print_user_tasks() # only tasks and main
532        elif len(argv) == 1:
533            # push task
534            if argv[0].isdigit():
535                self.pushtask_by_id(argv[0], "userCluster") # by id, userCluster
536            elif argv[0].startswith('0x') or argv[0].startswith('0X'):
537                self.pushtask_by_address(argv[0]) # by address, any cluster
538            # print tasks
539            elif argv[0] == 'all':
540                self.print_all_tasks() # all tasks, all clusters
541            else:
542                self.print_tasks_by_cluster_name(argv[0]) # all tasks, specified cluster
543        elif len(argv) == 2:
544            # push task
545            self.pushtask_by_id(argv[0], argv[1]) # by id, specified cluster
546        else:
547            print('parse error')
548            print_usage(self.usage_msg)
549
550class PrevTask(gdb.Command):
551    """Switch back to previous task on the stack"""
552    usage_msg = 'prevtask <task_address>'
553
554    def __init__(self):
555        super(PrevTask, self).__init__('prevtask', gdb.COMMAND_USER)
556
557    def invoke(self, arg, from_tty):
558        """
559        @arg: str
560        @from_tty: bool
561        """
562        global STACK
563        if len(STACK) != 0:
564            # must be at frame 0 to set pc register
565            gdb.execute('select-frame 0')
566
567            # pop stack
568            stack_info = STACK.pop()
569            pc = get_addr(stack_info.pc)
570            sp = stack_info.sp
571            fp = stack_info.fp
572
573            # pop sp, fp, pc from global stack
574            gdb.execute('set $pc = {}'.format(pc))
575            gdb.execute('set $rbp = {}'.format(fp))
576            gdb.execute('set $sp = {}'.format(sp))
577
578            # must be at C++ frame to access C++ vars
579            gdb.execute('frame 1')
580        else:
581            print('empty stack')
582
583class ResetOriginFrame(gdb.Command):
584    """Reset to the origin frame prior to continue execution again"""
585    usage_msg = 'resetOriginFrame'
586    def __init__(self):
587        super(ResetOriginFrame, self).__init__('reset', gdb.COMMAND_USER)
588
589    def invoke(self, arg, from_tty):
590        """
591        @arg: str
592        @from_tty: bool
593        """
594        global STACK
595        if len(STACK) != 0:
596            stack_info = STACK.pop(0)
597            STACK.clear()
598            pc = get_addr(stack_info.pc)
599            sp = stack_info.sp
600            fp = stack_info.fp
601
602            # pop sp, fp, pc from global stack
603            gdb.execute('set $pc = {}'.format(pc))
604            gdb.execute('set $rbp = {}'.format(fp))
605            gdb.execute('set $sp = {}'.format(sp))
606
607            # must be at C++ frame to access C++ vars
608            gdb.execute('frame 1')
609        #else:
610            #print('reset: empty stack') #probably does not have to print msg
611
612Clusters()
613ClusterProcessors()
614PrevTask()
615ResetOriginFrame()
616Task()
617
618# Local Variables: #
619# mode: Python #
620# End: #
Note: See TracBrowser for help on using the repository browser.