2009-03-27 Zoltan Varga <vargaz@gmail.com>
[mono.git] / data / gdb / mono-gdb.py
1 #
2 # Author: Zoltan Varga (vargaz@gmail.com)
3 # License: MIT/X11
4 #
5
6 #
7 # This is a mono support mode for a python-enabled gdb:
8 # http://sourceware.org/gdb/wiki/PythonGdb
9 # Usage:
10 # - copy/symlink this file, plus mono-gdbinit to the directory where the mono 
11 #   executable lives.
12 # - run mono under gdb, or attach to a mono process using gdb
13 # - Type 'xdb' in gdb to load/reload the debugging info emitted by the runtime.
14 # - The debug info is emitted to a file called xdb.s in the current working directory.
15 #   When attaching to a mono process, make sure you are in the same directory.
16 #
17
18 import os
19
20 class StringPrinter:
21     "Print a C# string"
22
23     def __init__(self, val):
24         self.val = val
25
26     def to_string(self):
27         if int(self.val.cast (gdb.Type ("guint64"))) == 0:
28             return "null"
29
30         obj = self.val.cast (gdb.Type ("MonoString").pointer ()).dereference ()
31         len = obj ['length']
32         chars = obj ['chars']
33         i = 0
34         res = ['"']
35         while i < len:
36             val = (chars.cast(gdb.Type ("gint64")) + (i * 2)).cast(gdb.Type ("gunichar2").pointer ()).dereference ()
37             if val >= 256:
38                 c = "\u%X" % val
39             else:
40                 c = chr (val)
41             res.append (c)
42             i = i + 1
43         res.append ('"')
44         return ''.join (res)
45
46 def stringify_class_name(ns, name):
47     if ns == "System":
48         if name == "Byte":
49             return "byte"
50         if name == "String":
51             return "string"
52     return "%s.%s" % (ns, name)
53
54 class ArrayPrinter:
55     "Print a C# array"
56
57     def __init__(self, val, class_ns, class_name):
58         self.val = val
59         self.class_ns = class_ns
60         self.class_name = class_name
61
62     def to_string(self):
63         obj = self.val.cast (gdb.Type ("MonoArray").pointer ()).dereference ()
64         length = obj ['max_length']
65         return "%s [%d]" % (stringify_class_name (self.class_ns, self.class_name [0:len(self.class_name) - 2]), int(length))
66         
67 class ObjectPrinter:
68     "Print a C# object"
69
70     def __init__(self, val):
71         self.val = val
72
73     class _iterator:
74         def __init__(self,obj):
75             self.obj = obj
76             self.iter = self.obj.type ().fields ().__iter__ ()
77             pass
78
79         def __iter__(self):
80             return self
81
82         def next(self):
83             field = self.iter.next ()
84             return (field.name, self.obj [field.name])
85
86     def children(self):
87         # FIXME: It would be easier if gdb.Value would support iteration itself
88         # It would also be better if we could return None
89         if int(self.val.cast (gdb.Type ("guint64"))) == 0:
90             return {}.__iter__ ()
91         try:
92             obj = self.val.cast (gdb.Type ("MonoObject").pointer ()).dereference ()
93             class_ns = obj ['vtable'].dereference ()['klass'].dereference ()['name_space'].string ()
94             class_name = obj ['vtable'].dereference ()['klass'].dereference ()['name'].string ()
95             gdb_type = gdb.Type ("struct %s.%s" % (class_ns, class_name))
96             return self._iterator(obj.cast (gdb_type))
97         except:
98             return {}.__iter__ ()
99
100     def to_string(self):
101         if int(self.val.cast (gdb.Type ("guint64"))) == 0:
102             return "null"
103         try:
104             obj = self.val.cast (gdb.Type ("MonoObject").pointer ()).dereference ()
105             class_ns = obj ['vtable'].dereference ()['klass'].dereference ()['name_space'].string ()
106             class_name = obj ['vtable'].dereference ()['klass'].dereference ()['name'].string ()
107             if class_ns == "System" and class_name == "String":
108                 return StringPrinter (self.val).to_string ()
109             if class_name [-2:len(class_name)] == "[]":
110                 return ArrayPrinter (self.val,class_ns,class_name).to_string ()
111             if class_ns != "":
112                 try:
113                     gdb_type = gdb.Type ("struct %s.%s" % (class_ns, class_name))
114                 except:
115                     # Maybe there is no debug info for that type
116                     return "%s.%s" % (class_ns, class_name)
117                 #return obj.cast (gdb_type)
118                 return "%s.%s" % (class_ns, class_name)
119             return class_name
120         except:
121             print sys.exc_info ()[0]
122             print sys.exc_info ()[1]
123             # FIXME: This can happen because we don't have liveness information
124             return self.val.cast (gdb.Type ("guint64"))
125
126 def lookup_pretty_printer(val):
127     if str (val.type ()) == "object":
128         return ObjectPrinter (val)
129     if str (val.type ()) == "string":
130         return StringPrinter (val)
131     return None
132
133 def register_csharp_printers(obj):
134     "Register C# pretty-printers with objfile Obj."
135
136     if obj == None:
137         obj = gdb
138
139     obj.pretty_printers.append (lookup_pretty_printer)
140
141 register_csharp_printers (gdb.current_objfile())
142
143 class MonoSupport(object):
144
145     def __init__(self):
146         self.s_size = 0
147
148     def run_hook(self):
149         if os.access ("xdb.s", os.F_OK):
150             os.remove ("xdb.s")
151         gdb.execute ("set environment MONO_XDEBUG 1")
152         
153     def stop_hook(self):
154         # Called when the program is stopped
155         # Need to recompile+reload the xdb.s file if needed
156         # FIXME: Need to detect half-written files created when the child is
157         # interrupted while executing the xdb.s writing code
158         # FIXME: Handle appdomain unload
159         if os.access ("xdb.s", os.F_OK):
160             new_size = os.stat ("xdb.s").st_size
161             if new_size > self.s_size:
162                 sofile = "xdb.so"
163                 gdb.execute ("shell as -o xdb.o xdb.s && ld -shared -o %s xdb.o" % sofile)
164                 # FIXME: This prints messages which couldn't be turned off
165                 gdb.execute ("add-symbol-file %s 0" % sofile)
166                 self.s_size = new_size
167
168 class RunHook (gdb.Command):
169     def __init__ (self):
170         super (RunHook, self).__init__ ("hook-run", gdb.COMMAND_NONE,
171                                         gdb.COMPLETE_COMMAND, pre_hook_of="run")
172
173     def invoke(self, arg, from_tty):
174         mono_support.run_hook ()
175
176 print "Mono support loaded."
177
178 mono_support = MonoSupport ()
179
180 # This depends on the changes in gdb-python.diff to work
181 #RunHook ()
182
183 # Register our hooks
184 # This currently cannot be done from python code
185
186 exec_file = gdb.current_objfile ().filename
187 # FIXME: Is there a way to detect symbolic links ?
188 if os.stat (exec_file).st_size != os.lstat (exec_file).st_size:
189     exec_file = os.readlink (exec_file)
190 exec_dir = os.path.dirname (exec_file)
191 gdb.execute ("source %s/%s-gdbinit" % (exec_dir, os.path.basename (exec_file)))