2009-04-05 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             try:
85                 if str(self.obj [field.name].type ()) == "object":
86                     # Avoid recursion
87                     return (field.name, self.obj [field.name].cast (gdb.Type ("void").pointer ()))
88                 else:
89                     return (field.name, self.obj [field.name])
90             except:
91                 # Superclass
92                 return (field.name, self.obj.cast (gdb.Type ("struct %s" % (field.name))))
93
94     def children(self):
95         # FIXME: It would be easier if gdb.Value would support iteration itself
96         # It would also be better if we could return None
97         if int(self.val.cast (gdb.Type ("guint64"))) == 0:
98             return {}.__iter__ ()
99         try:
100             obj = self.val.cast (gdb.Type ("MonoObject").pointer ()).dereference ()
101             class_ns = obj ['vtable'].dereference ()['klass'].dereference ()['name_space'].string ()
102             class_name = obj ['vtable'].dereference ()['klass'].dereference ()['name'].string ()
103             gdb_type = gdb.Type ("struct %s.%s" % (class_ns, class_name))
104             return self._iterator(obj.cast (gdb_type))
105         except:
106             return {}.__iter__ ()
107
108     def to_string(self):
109         if int(self.val.cast (gdb.Type ("guint64"))) == 0:
110             return "null"
111         try:
112             obj = self.val.cast (gdb.Type ("MonoObject").pointer ()).dereference ()
113             class_ns = obj ['vtable'].dereference ()['klass'].dereference ()['name_space'].string ()
114             class_name = obj ['vtable'].dereference ()['klass'].dereference ()['name'].string ()
115             if class_ns == "System" and class_name == "String":
116                 return StringPrinter (self.val).to_string ()
117             if class_name [-2:len(class_name)] == "[]":
118                 return ArrayPrinter (self.val,class_ns,class_name).to_string ()
119             if class_ns != "":
120                 try:
121                     gdb_type = gdb.Type ("struct %s.%s" % (class_ns, class_name))
122                 except:
123                     # Maybe there is no debug info for that type
124                     return "%s.%s" % (class_ns, class_name)
125                 #return obj.cast (gdb_type)
126                 return "%s.%s" % (class_ns, class_name)
127             return class_name
128         except:
129             print sys.exc_info ()[0]
130             print sys.exc_info ()[1]
131             # FIXME: This can happen because we don't have liveness information
132             return self.val.cast (gdb.Type ("guint64"))
133
134 def lookup_pretty_printer(val):
135     if str (val.type ()) == "object":
136         return ObjectPrinter (val)
137     if str (val.type ()) == "string":
138         return StringPrinter (val)
139     return None
140
141 def register_csharp_printers(obj):
142     "Register C# pretty-printers with objfile Obj."
143
144     if obj == None:
145         obj = gdb
146
147     obj.pretty_printers.append (lookup_pretty_printer)
148
149 register_csharp_printers (gdb.current_objfile())
150
151 class MonoSupport(object):
152
153     def __init__(self):
154         self.s_size = 0
155
156     def run_hook(self):
157         if os.access ("xdb.s", os.F_OK):
158             os.remove ("xdb.s")
159         gdb.execute ("set environment MONO_XDEBUG 1")
160         
161     def stop_hook(self):
162         # Called when the program is stopped
163         # Need to recompile+reload the xdb.s file if needed
164         # FIXME: Need to detect half-written files created when the child is
165         # interrupted while executing the xdb.s writing code
166         # FIXME: Handle appdomain unload
167         if os.access ("xdb.s", os.F_OK):
168             new_size = os.stat ("xdb.s").st_size
169             if new_size > self.s_size:
170                 sofile = "xdb.so"
171                 gdb.execute ("shell as -o xdb.o xdb.s && ld -shared -o %s xdb.o" % sofile)
172                 # FIXME: This prints messages which couldn't be turned off
173                 gdb.execute ("add-symbol-file %s 0" % sofile)
174                 self.s_size = new_size
175
176 class RunHook (gdb.Command):
177     def __init__ (self):
178         super (RunHook, self).__init__ ("hook-run", gdb.COMMAND_NONE,
179                                         gdb.COMPLETE_COMMAND, pre_hook_of="run")
180
181     def invoke(self, arg, from_tty):
182         mono_support.run_hook ()
183
184 print "Mono support loaded."
185
186 mono_support = MonoSupport ()
187
188 # This depends on the changes in gdb-python.diff to work
189 #RunHook ()
190
191 # Register our hooks
192 # This currently cannot be done from python code
193
194 exec_file = gdb.current_objfile ().filename
195 # FIXME: Is there a way to detect symbolic links ?
196 if os.stat (exec_file).st_size != os.lstat (exec_file).st_size:
197     exec_file = os.readlink (exec_file)
198 exec_dir = os.path.dirname (exec_file)
199 gdb.execute ("source %s/%s-gdbinit" % (exec_dir, os.path.basename (exec_file)))