Reverted this and added a comment.
[mono.git] / mcs / class / Mono.CSharp.Debugger / MonoSymbolFile.cs
1 //
2 // Mono.CSharp.Debugger/MonoSymbolFile.cs
3 //
4 // Author:
5 //   Martin Baulig (martin@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc.  http://www.ximian.com
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Reflection;
33 using System.Collections;
34 using System.Text;
35 using System.Threading;
36 using System.IO;
37         
38 namespace Mono.CompilerServices.SymbolWriter
39 {
40         public class MonoSymbolFileException : Exception
41         {
42                 public MonoSymbolFileException ()
43                         : base ()
44                 { }
45
46                 public MonoSymbolFileException (string message, params object[] args)
47                         : base (String.Format (message, args))
48                 { }
49         }
50
51         internal class MyMemoryStream : Stream
52         {
53                 int length;
54                 int real_length;
55                 int position;
56
57                 int chunk_size = 4096;
58                 ArrayList chunks = new ArrayList ();
59
60                 private struct Chunk {
61                         public readonly int Offset;
62                         public readonly int Length;
63                         public byte[] Buffer;
64
65                         public Chunk (int offset, int length)
66                         {
67                                 this.Offset = offset;
68                                 this.Length = length;
69                                 this.Buffer = new Byte [length];
70                         }
71                 }
72
73                 public override long Position {
74                         get { return position; }
75
76                         set {
77                                 if (value > length)
78                                         throw new ArgumentOutOfRangeException ();
79
80                                 position = (int) value;
81                         }
82                 }
83
84                 public override long Length {
85                         get { return length; }
86                 }
87
88                 public override bool CanRead {
89                         get { return true; }
90                 }
91
92                 public override bool CanWrite {
93                         get { return true; }
94                 }
95
96                 public override bool CanSeek {
97                         get { return true; }
98                 }
99
100                 public override void SetLength (long new_length)
101                 {
102                         if (new_length < length)
103                                 throw new ArgumentException ();
104
105                         while (new_length >= real_length) {
106                                 Chunk new_chunk = new Chunk (real_length, chunk_size);
107                                 chunks.Add (new_chunk);
108                                 real_length += chunk_size;
109                         }
110
111                         length = (int) new_length;
112                 }
113
114                 public override void Flush ()
115                 { }
116
117                 public override long Seek (long offset, SeekOrigin origin)
118                 {
119                         int ref_point;
120
121                         switch (origin) {
122                         case SeekOrigin.Begin:
123                                 ref_point = 0;
124                                 break;
125                         case SeekOrigin.Current:
126                                 ref_point = position;
127                                 break;
128                         case SeekOrigin.End:
129                                 ref_point = length;
130                                 break;
131                         default:
132                                 throw new ArgumentException ("Invalid SeekOrigin");
133                         }
134
135                         if ((ref_point + offset < 0) || (offset > real_length))
136                                 throw new ArgumentOutOfRangeException ();
137
138                         position = ref_point + (int) offset;
139
140                         return position;
141                 }
142
143                 Chunk FindChunk (int offset)
144                 {
145                         return (Chunk) chunks [offset / chunk_size];
146                 }
147
148                 public override int Read (byte[] buffer, int offset, int count)
149                 {
150                         int old_count = count;
151
152                         while (count > 0) {
153                                 Chunk chunk = FindChunk (position);
154                                 int coffset = position - chunk.Offset;
155                                 int rest = chunk.Length - coffset;
156                                 int size = System.Math.Min (count, rest);
157
158                                 Array.Copy (chunk.Buffer, coffset, buffer, offset, size);
159                                 position += size;
160                                 offset += size;
161                                 count -= size;
162                         }
163
164                         return old_count;
165                 }
166
167                 public override void Write (byte[] buffer, int offset, int count)
168                 {
169                         if (position + count > length)
170                                 SetLength (position + count);
171
172                         while (count > 0) {
173                                 Chunk chunk = FindChunk (position);
174                                 int coffset = position - chunk.Offset;
175                                 int rest = chunk.Length - coffset;
176                                 int size = System.Math.Min (count, rest);
177
178                                 Array.Copy (buffer, offset, chunk.Buffer, coffset, size);
179                                 position += size;
180                                 offset += size;
181                                 count -= size;
182                         }
183                 }
184
185                 public byte[] GetContents ()
186                 {
187                         byte[] retval = new byte [length];
188                         position = 0;
189                         Read (retval, 0, length);
190                         return retval;
191                 }
192         }
193
194         internal class MyBinaryWriter : BinaryWriter
195         {
196                 public MyBinaryWriter (Stream stream)
197                         : base (stream)
198                 { }
199
200                 public void WriteLeb128 (int value)
201                 {
202                         base.Write7BitEncodedInt (value);
203                 }
204         }
205
206         internal class MyBinaryReader : BinaryReader
207         {
208                 public MyBinaryReader (Stream stream)
209                         : base (stream)
210                 { }
211
212                 public int ReadLeb128 ()
213                 {
214                         return base.Read7BitEncodedInt ();
215                 }
216         }
217
218         public class MonoDebuggerSupport
219         {
220                 static GetTypeFunc get_type;
221                 static GetMethodTokenFunc get_method_token;
222                 static GetMethodFunc get_method;
223                 static GetLocalTypeFromSignatureFunc local_type_from_sig;
224                 static GetGuidFunc get_guid;
225                 static CheckRuntimeVersionFunc check_runtime_version;
226
227                 delegate Type GetTypeFunc (Assembly assembly, int token);
228                 delegate int GetMethodTokenFunc (Assembly assembly, MethodBase method);
229                 delegate MethodBase GetMethodFunc (Assembly assembly, int token);
230                 delegate Type GetLocalTypeFromSignatureFunc (Assembly assembly, byte[] sig);
231                 delegate Guid GetGuidFunc (Module module);
232                 delegate string CheckRuntimeVersionFunc (string filename);
233
234                 static Delegate create_delegate (Type type, Type delegate_type, string name)
235                 {
236                         MethodInfo mi = type.GetMethod (name, BindingFlags.Static |
237                                                         BindingFlags.NonPublic);
238                         if (mi == null)
239                                 throw new Exception ("Can't find " + name);
240
241                         return Delegate.CreateDelegate (delegate_type, mi);
242                 }
243
244                 static MonoDebuggerSupport ()
245                 {
246                         get_type = (GetTypeFunc) create_delegate (
247                                 typeof (Assembly), typeof (GetTypeFunc),
248                                 "MonoDebugger_GetType");
249
250                         get_method_token = (GetMethodTokenFunc) create_delegate (
251                                 typeof (Assembly), typeof (GetMethodTokenFunc),
252                                 "MonoDebugger_GetMethodToken");
253
254                         get_method = (GetMethodFunc) create_delegate (
255                                 typeof (Assembly), typeof (GetMethodFunc),
256                                 "MonoDebugger_GetMethod");
257
258                         local_type_from_sig = (GetLocalTypeFromSignatureFunc) create_delegate (
259                                 typeof (Assembly), typeof (GetLocalTypeFromSignatureFunc),
260                                 "MonoDebugger_GetLocalTypeFromSignature");
261
262                         get_guid = (GetGuidFunc) create_delegate (
263                                 typeof (Module), typeof (GetGuidFunc), "Mono_GetGuid");
264
265                         check_runtime_version = (CheckRuntimeVersionFunc) create_delegate (
266                                 typeof (Assembly), typeof (CheckRuntimeVersionFunc),
267                                 "MonoDebugger_CheckRuntimeVersion");
268                 }
269
270                 public static Type GetType (Assembly assembly, int token)
271                 {
272                         return get_type (assembly, token);
273                 }
274
275                 public static int GetMethodToken (MethodBase method)
276                 {
277                         return get_method_token (method.ReflectedType.Assembly, method);
278                 }
279
280                 public static MethodBase GetMethod (Assembly assembly, int token)
281                 {
282                         return get_method (assembly, token);
283                 }
284
285                 public static Type GetLocalTypeFromSignature (Assembly assembly, byte[] sig)
286                 {
287                         return local_type_from_sig (assembly, sig);
288                 }
289
290                 public static string CheckRuntimeVersion (string filename)
291                 {
292                         return check_runtime_version (filename);
293                 }
294
295                 public static Guid GetGuid (Module module)
296                 {
297                         return get_guid (module);
298                 }
299         }
300
301         public class MonoSymbolFile : IDisposable
302         {
303                 ArrayList methods = new ArrayList ();
304                 ArrayList sources = new ArrayList ();
305                 Hashtable method_source_hash = new Hashtable ();
306                 Hashtable type_hash = new Hashtable ();
307
308                 OffsetTable ot;
309                 int last_type_index;
310                 int last_method_index;
311                 int last_source_index;
312                 int last_namespace_index;
313
314                 public int NumLineNumbers;
315
316                 public MonoSymbolFile ()
317                 { }
318
319                 internal int AddSource (SourceFileEntry source)
320                 {
321                         sources.Add (source);
322                         return ++last_source_index;
323                 }
324
325                 internal int DefineType (Type type)
326                 {
327                         if (type_hash.Contains (type))
328                                 return (int) type_hash [type];
329
330                         int index = ++last_type_index;
331                         type_hash.Add (type, index);
332                         return index;
333                 }
334
335                 internal void AddMethod (MethodEntry entry)
336                 {
337                         methods.Add (entry);
338                 }
339
340                 internal int GetNextTypeIndex ()
341                 {
342                         return ++last_type_index;
343                 }
344
345                 internal int GetNextMethodIndex ()
346                 {
347                         return ++last_method_index;
348                 }
349
350                 internal int GetNextNamespaceIndex ()
351                 {
352                         return ++last_namespace_index;
353                 }
354
355                 byte [] stringBuffer;
356                 int maxCharsPerRound;
357                 static Encoding enc = Encoding.UTF8;
358                 
359                 internal string ReadString (int offset)
360                 {
361                         int old_pos = (int) reader.BaseStream.Position;
362                         reader.BaseStream.Position = offset;
363
364                         string text = reader.ReadString ();
365
366                         reader.BaseStream.Position = old_pos;
367                         return text;
368                 }
369
370                 void Write (MyBinaryWriter bw, Guid guid)
371                 {
372                         // Magic number and file version.
373                         bw.Write (OffsetTable.Magic);
374                         bw.Write (OffsetTable.Version);
375
376                         bw.Write (guid.ToByteArray ());
377
378                         //
379                         // Offsets of file sections; we must write this after we're done
380                         // writing the whole file, so we just reserve the space for it here.
381                         //
382                         long offset_table_offset = bw.BaseStream.Position;
383                         ot.Write (bw);
384
385                         //
386                         // Write data sections.
387                         //
388                         ot.DataSectionOffset = (int) bw.BaseStream.Position;
389                         foreach (SourceFileEntry source in sources)
390                                 source.WriteData (bw);
391                         ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset;
392
393                         //
394                         // Sort the methods according to their tokens and write
395                         // the method table.
396                         //
397                         methods.Sort ();
398                         ot.MethodTableOffset = (int) bw.BaseStream.Position;
399                         for (int i = 0; i < methods.Count; i++) {
400                                 MethodEntry entry = (MethodEntry) methods [i];
401                                 entry.WriteIndex (bw);
402                         }
403                         ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset;
404
405                         //
406                         // Write source table.
407                         //
408                         ot.SourceTableOffset = (int) bw.BaseStream.Position;
409                         for (int i = 0; i < sources.Count; i++) {
410                                 SourceFileEntry source = (SourceFileEntry) sources [i];
411                                 source.Write (bw);
412                         }
413                         ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset;
414
415                         //
416                         // Fixup offset table.
417                         //
418                         ot.TypeCount = last_type_index;
419                         ot.MethodCount = methods.Count;
420                         ot.SourceCount = sources.Count;
421
422                         //
423                         // Write offset table.
424                         //
425                         ot.TotalFileSize = (int) bw.BaseStream.Position;
426                         bw.Seek ((int) offset_table_offset, SeekOrigin.Begin);
427                         ot.Write (bw);
428                         bw.Seek (0, SeekOrigin.End);
429                 }
430
431                 public byte[] CreateSymbolFile (Guid guid)
432                 {
433                         if (reader != null)
434                                 throw new InvalidOperationException ();
435
436                         using (MyMemoryStream stream = new MyMemoryStream ()) {
437                                 Write (new MyBinaryWriter (stream), guid);
438                                 return stream.GetContents ();
439                         }
440                 }
441
442                 Assembly assembly;
443                 MyBinaryReader reader;
444                 Hashtable method_hash;
445                 Hashtable source_file_hash;
446
447                 Hashtable method_token_hash;
448                 Hashtable source_name_hash;
449
450                 protected MonoSymbolFile (string filename, Assembly assembly)
451                 {
452                         this.assembly = assembly;
453
454                         FileStream stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
455                         reader = new MyBinaryReader (stream);
456
457                         Guid guid;
458
459                         try {
460                                 long magic = reader.ReadInt64 ();
461                                 long version = reader.ReadInt32 ();
462                                 if (magic != OffsetTable.Magic)
463                                         throw new MonoSymbolFileException (
464                                                 "Symbol file `{0}' is not a valid " +
465                                                 "Mono symbol file", filename);
466                                 if (version != OffsetTable.Version)
467                                         throw new MonoSymbolFileException (
468                                                 "Symbol file `{0}' has version {1}, " +
469                                                 "but expected {2}", filename, version,
470                                                 OffsetTable.Version);
471
472                                 guid = new Guid (reader.ReadBytes (16));
473
474                                 ot = new OffsetTable (reader);
475                         } catch {
476                                 throw new MonoSymbolFileException (
477                                         "Cannot read symbol file `{0}'", filename);
478                         }
479
480                         Module[] modules = assembly.GetModules ();
481                         Guid assembly_guid = MonoDebuggerSupport.GetGuid (modules [0]);
482
483                         if (guid != assembly_guid)
484                                 throw new MonoSymbolFileException (
485                                         "Symbol file `{0}' does not match assembly `{1}'",
486                                         filename, assembly.Location);
487
488                         method_hash = new Hashtable ();
489                         source_file_hash = new Hashtable ();
490                 }
491
492                 public static MonoSymbolFile ReadSymbolFile (Assembly assembly)
493                 {
494                         string filename = assembly.Location;
495                         string name = filename + ".mdb";
496
497                         return new MonoSymbolFile (name, assembly);
498                 }
499
500                 public Assembly Assembly {
501                         get { return assembly; }
502                 }
503
504                 public int SourceCount {
505                         get { return ot.SourceCount; }
506                 }
507
508                 public int MethodCount {
509                         get { return ot.MethodCount; }
510                 }
511
512                 public int TypeCount {
513                         get { return ot.TypeCount; }
514                 }
515
516                 public int NamespaceCount {
517                         get { return last_namespace_index; }
518                 }
519
520                 internal int LineNumberCount = 0;
521                 internal int LocalCount = 0;
522                 internal int StringSize = 0;
523
524                 public SourceFileEntry GetSourceFile (int index)
525                 {
526                         if ((index < 1) || (index > ot.SourceCount))
527                                 throw new ArgumentException ();
528                         if (reader == null)
529                                 throw new InvalidOperationException ();
530
531                         SourceFileEntry source = (SourceFileEntry) source_file_hash [index];
532                         if (source != null)
533                                 return source;
534
535                         reader.BaseStream.Position = ot.SourceTableOffset +
536                                 SourceFileEntry.Size * (index - 1);
537                         source = new SourceFileEntry (this, reader);
538                         source_file_hash.Add (index, source);
539                         return source;
540                 }
541
542                 public SourceFileEntry[] Sources {
543                         get {
544                                 if (reader == null)
545                                         throw new InvalidOperationException ();
546
547                                 SourceFileEntry[] retval = new SourceFileEntry [SourceCount];
548                                 for (int i = 0; i < SourceCount; i++)
549                                         retval [i] = GetSourceFile (i + 1);
550                                 return retval;
551                         }
552                 }
553
554                 public MethodIndexEntry GetMethodIndexEntry (int index)
555                 {
556                         int old_pos = (int) reader.BaseStream.Position;
557                         reader.BaseStream.Position = ot.MethodTableOffset +
558                                 MethodIndexEntry.Size * (index - 1);
559                         MethodIndexEntry ie = new MethodIndexEntry (reader);
560                         reader.BaseStream.Position = old_pos;
561                         return ie;
562                 }
563
564                 public MethodEntry GetMethodByToken (int token)
565                 {
566                         if (reader == null)
567                                 throw new InvalidOperationException ();
568
569                         if (method_token_hash == null) {
570                                 method_token_hash = new Hashtable ();
571
572                                 for (int i = 0; i < MethodCount; i++) {
573                                         MethodIndexEntry ie = GetMethodIndexEntry (i + 1);
574
575                                         method_token_hash.Add (ie.Token, i + 1);
576                                 }
577                         }
578
579                         object value = method_token_hash [token];
580                         if (value == null)
581                                 return null;
582
583                         return GetMethod ((int) value);
584                 }
585
586                 public MethodEntry GetMethod (MethodBase method)
587                 {
588                         if (reader == null)
589                                 throw new InvalidOperationException ();
590                         int token = MonoDebuggerSupport.GetMethodToken (method);
591                         return GetMethodByToken (token);
592                 }
593
594                 public MethodEntry GetMethod (int index)
595                 {
596                         if ((index < 1) || (index > ot.MethodCount))
597                                 throw new ArgumentException ();
598                         if (reader == null)
599                                 throw new InvalidOperationException ();
600
601                         MethodEntry entry = (MethodEntry) method_hash [index];
602                         if (entry != null)
603                                 return entry;
604
605                         MethodIndexEntry ie = GetMethodIndexEntry (index);
606                         reader.BaseStream.Position = ie.FileOffset;
607
608                         entry = new MethodEntry (this, reader, index);
609                         method_hash.Add (index, entry);
610                         return entry;
611                 }
612
613                 public MethodEntry[] Methods {
614                         get {
615                                 if (reader == null)
616                                         throw new InvalidOperationException ();
617
618                                 MethodEntry[] retval = new MethodEntry [MethodCount];
619                                 for (int i = 0; i < MethodCount; i++)
620                                         retval [i] = GetMethod (i + 1);
621                                 return retval;
622                         }
623                 }
624
625                 public MethodSourceEntry GetMethodSource (int index)
626                 {
627                         if ((index < 1) || (index > ot.MethodCount))
628                                 throw new ArgumentException ();
629                         if (reader == null)
630                                 throw new InvalidOperationException ();
631
632                         object entry = method_source_hash [index];
633                         if (entry != null)
634                                 return (MethodSourceEntry) entry;
635
636                         MethodEntry method = GetMethod (index);
637                         foreach (MethodSourceEntry source in method.SourceFile.Methods) {
638                                 if (source.Index == index) {
639                                         method_source_hash.Add (index, source);
640                                         return source;
641                                 }
642                         }
643
644                         throw new MonoSymbolFileException ("Internal error.");
645                 }
646
647                 public int FindSource (string file_name)
648                 {
649                         if (reader == null)
650                                 throw new InvalidOperationException ();
651
652                         if (source_name_hash == null) {
653                                 source_name_hash = new Hashtable ();
654
655                                 for (int i = 0; i < ot.SourceCount; i++) {
656                                         SourceFileEntry source = GetSourceFile (i + 1);
657
658                                         source_name_hash.Add (source.FileName, i);
659                                 }
660                         }
661
662                         object value = source_name_hash [file_name];
663                         if (value == null)
664                                 return -1;
665                         return (int) value;
666                 }
667
668                 internal MyBinaryReader BinaryReader {
669                         get {
670                                 if (reader == null)
671                                         throw new InvalidOperationException ();
672
673                                 return reader;
674                         }
675                 }
676
677                 void IDisposable.Dispose ()
678                 {
679                         Dispose (true);
680                 }
681
682                 protected virtual void Dispose (bool disposing)
683                 {
684                         if (disposing) {
685                                 if (reader != null) {
686                                         reader.Close ();
687                                         reader = null;
688                                 }
689                         }
690                 }
691         }
692 }