Merge pull request #1325 from madrang/CryptoToolsCtorCheck
[mono.git] / mcs / tools / csharp / repl.cs
1 //
2 // repl.cs: Support for using the compiler in interactive mode (read-eval-print loop)
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@gnome.org)
6 //
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 //
9 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
11 // Copyright 2011-2013 Xamarin Inc
12 //
13 //
14 // TODO:
15 //   Do not print results in Evaluate, do that elsewhere in preparation for Eval refactoring.
16 //   Driver.PartialReset should not reset the coretypes, nor the optional types, to avoid
17 //      computing that on every call.
18 //
19 using System;
20 using System.IO;
21 using System.Text;
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Threading;
27 using System.Net;
28 using System.Net.Sockets;
29 using System.Collections.Generic;
30
31 using Mono.CSharp;
32
33 namespace Mono {
34
35         public class Driver {
36                 public static string StartupEvalExpression;
37                 static int? attach;
38                 static string target_host;
39                 static int target_port;
40                 static string agent;
41                 
42                 static int Main (string [] args)
43                 {
44                         var cmd = new CommandLineParser (Console.Out);
45                         cmd.UnknownOptionHandler += HandleExtraArguments;
46
47                         // Enable unsafe code by default
48                         var settings = new CompilerSettings () {
49                                 Unsafe = true
50                         };
51
52                         if (!cmd.ParseArguments (settings, args))
53                                 return 1;
54
55                         var startup_files = new string [settings.SourceFiles.Count];
56                         int i = 0;
57                         foreach (var source in settings.SourceFiles)
58                                 startup_files [i++] = source.FullPathName;
59                         settings.SourceFiles.Clear ();
60
61                         TextWriter agent_stderr = null;
62                         ReportPrinter printer;
63                         if (agent != null) {
64                                 agent_stderr = new StringWriter ();
65                                 printer = new StreamReportPrinter (agent_stderr);
66                         } else {
67                                 printer = new ConsoleReportPrinter ();
68                         }
69
70                         var eval = new Evaluator (new CompilerContext (settings, printer));
71
72                         eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
73                         eval.DescribeTypeExpressions = true;
74                         eval.WaitOnTask = true;
75
76                         CSharpShell shell;
77 #if !ON_DOTNET
78                         if (attach.HasValue) {
79                                 shell = new ClientCSharpShell_v1 (eval, attach.Value);
80                         } else if (agent != null) {
81                                 new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
82                                 return 0;
83                         } else
84 #endif
85                         if (target_host != null) 
86                                 shell = new ClientCSharpShell  (eval, target_host, target_port);
87                         else 
88                                 shell = new CSharpShell (eval);
89
90                         return shell.Run (startup_files);
91                 }
92
93                 static int HandleExtraArguments (string [] args, int pos)
94                 {
95                         switch (args [pos]) {
96                         case "-e":
97                                 if (pos + 1 < args.Length) {
98                                         StartupEvalExpression = args[pos + 1];
99                                         return pos + 1;
100                                 }
101                                 break;
102                         case "--attach":
103                                 if (pos + 1 < args.Length) {
104                                         attach = Int32.Parse (args[1]);
105                                         return pos + 1;
106                                 }
107                                 break;
108                         default:
109                                 if (args [pos].StartsWith ("--server=")){
110                                         var hostport = args [pos].Substring (9);
111                                         int p = hostport.IndexOf (':');
112                                         if (p == -1){
113                                                 target_host = hostport;
114                                                 target_port = 10000;
115                                         } else {
116                                                 target_host = hostport.Substring (0,p);
117                                                 if (!int.TryParse (hostport.Substring (p), out target_port)){
118                                                         Console.Error.WriteLine ("Usage is: --server[=host[:port]");
119                                                         Environment.Exit (1);
120                                                 }
121                                         }
122                                         return pos + 1;
123                                 }
124                                 if (args [pos].StartsWith ("--client")){
125                                         target_host = "localhost";
126                                         target_port = 10000;
127                                         return pos + 1;
128                                 }
129                                 if (args [pos].StartsWith ("--agent:")) {
130                                         agent = args[pos];
131                                         return pos + 1;
132                                 } else {
133                                         return -1;
134                                 }
135                         }
136                         return -1;
137                 }
138                 
139         }
140
141         public class InteractiveBaseShell : InteractiveBase {
142                 static bool tab_at_start_completes;
143                 
144                 static InteractiveBaseShell ()
145                 {
146                         tab_at_start_completes = false;
147                 }
148
149                 internal static Mono.Terminal.LineEditor Editor;
150                 
151                 public static bool TabAtStartCompletes {
152                         get {
153                                 return tab_at_start_completes;
154                         }
155
156                         set {
157                                 tab_at_start_completes = value;
158                                 if (Editor != null)
159                                         Editor.TabAtStartCompletes = value;
160                         }
161                 }
162
163                 public static new string help {
164                         get {
165                                 return InteractiveBase.help +
166                                         "  TabAtStartCompletes      - Whether tab will complete even on empty lines\n";
167                         }
168                 }
169         }
170         
171         public class CSharpShell {
172                 static bool isatty = true, is_unix = false;
173                 protected string [] startup_files;
174                 
175                 Mono.Terminal.LineEditor editor;
176                 bool dumb;
177                 readonly Evaluator evaluator;
178
179                 public CSharpShell (Evaluator evaluator)
180                 {
181                         this.evaluator = evaluator;
182                 }
183
184                 protected virtual void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
185                 {
186                         // Do not about our program
187                         a.Cancel = true;
188
189                         evaluator.Interrupt ();
190                 }
191                 
192                 void SetupConsole ()
193                 {
194                         if (is_unix){
195                                 string term = Environment.GetEnvironmentVariable ("TERM");
196                                 dumb = term == "dumb" || term == null || isatty == false;
197                         } else
198                                 dumb = false;
199                         
200                         editor = new Mono.Terminal.LineEditor ("csharp", 300);
201                         InteractiveBaseShell.Editor = editor;
202
203                         editor.AutoCompleteEvent += delegate (string s, int pos){
204                                 string prefix = null;
205
206                                 string complete = s.Substring (0, pos);
207                                 
208                                 string [] completions = evaluator.GetCompletions (complete, out prefix);
209                                 
210                                 return new Mono.Terminal.LineEditor.Completion (prefix, completions);
211                         };
212                         
213 #if false
214                         //
215                         // This is a sample of how completions sould be implemented.
216                         //
217                         editor.AutoCompleteEvent += delegate (string s, int pos){
218
219                                 // Single match: "Substring": Sub-string
220                                 if (s.EndsWith ("Sub")){
221                                         return new string [] { "string" };
222                                 }
223
224                                 // Multiple matches: "ToString" and "ToLower"
225                                 if (s.EndsWith ("T")){
226                                         return new string [] { "ToString", "ToLower" };
227                                 }
228                                 return null;
229                         };
230 #endif
231                         
232                         Console.CancelKeyPress += ConsoleInterrupt;
233                 }
234
235                 string GetLine (bool primary)
236                 {
237                         string prompt = primary ? InteractiveBase.Prompt : InteractiveBase.ContinuationPrompt;
238
239                         if (dumb){
240                                 if (isatty)
241                                         Console.Write (prompt);
242
243                                 return Console.ReadLine ();
244                         } else {
245                                 return editor.Edit (prompt, "");
246                         }
247                 }
248
249                 delegate string ReadLiner (bool primary);
250
251                 void InitializeUsing ()
252                 {
253                         Evaluate ("using System; using System.Linq; using System.Collections.Generic; using System.Collections;");
254                 }
255
256                 void InitTerminal (bool show_banner)
257                 {
258                         int p = (int) Environment.OSVersion.Platform;
259                         is_unix = (p == 4) || (p == 128);
260
261                         isatty = !Console.IsInputRedirected && !Console.IsOutputRedirected;
262
263                         // Work around, since Console is not accounting for
264                         // cursor position when writing to Stderr.  It also
265                         // has the undesirable side effect of making
266                         // errors plain, with no coloring.
267 //                      Report.Stderr = Console.Out;
268                         SetupConsole ();
269
270                         if (isatty && show_banner)
271                                 Console.WriteLine ("Mono C# Shell, type \"help;\" for help\n\nEnter statements below.");
272
273                 }
274
275                 void ExecuteSources (IEnumerable<string> sources, bool ignore_errors)
276                 {
277                         foreach (string file in sources){
278                                 try {
279                                         try {
280                                                 bool first = true;
281                         
282                                                 using (System.IO.StreamReader r = System.IO.File.OpenText (file)){
283                                                         ReadEvalPrintLoopWith (p => {
284                                                                 var line = r.ReadLine ();
285                                                                 if (first){
286                                                                         if (line.StartsWith ("#!"))
287                                                                                 line = r.ReadLine ();
288                                                                         first = false;
289                                                                 }
290                                                                 return line;
291                                                         });
292                                                 }
293                                         } catch (FileNotFoundException){
294                                                 Console.Error.WriteLine ("cs2001: Source file `{0}' not found", file);
295                                                 return;
296                                         }
297                                 } catch {
298                                         if (!ignore_errors)
299                                                 throw;
300                                 }
301                         }
302                 }
303                 
304                 protected virtual void LoadStartupFiles ()
305                 {
306                         string dir = Path.Combine (
307                                 Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
308                                 "csharp");
309                         if (!Directory.Exists (dir))
310                                 return;
311
312                         List<string> sources = new List<string> ();
313                         List<string> libraries = new List<string> ();
314                         
315                         foreach (string file in System.IO.Directory.GetFiles (dir)){
316                                 string l = file.ToLower ();
317                                 
318                                 if (l.EndsWith (".cs"))
319                                         sources.Add (file);
320                                 else if (l.EndsWith (".dll"))
321                                         libraries.Add (file);
322                         }
323
324                         foreach (string file in libraries)
325                                 evaluator.LoadAssembly (file);
326
327                         ExecuteSources (sources, true);
328                 }
329
330                 void ReadEvalPrintLoopWith (ReadLiner readline)
331                 {
332                         string expr = null;
333                         while (!InteractiveBase.QuitRequested){
334                                 string input = readline (expr == null);
335                                 if (input == null)
336                                         return;
337
338                                 if (input == "")
339                                         continue;
340
341                                 expr = expr == null ? input : expr + "\n" + input;
342                                 
343                                 expr = Evaluate (expr);
344                         }
345                 }
346
347                 public int ReadEvalPrintLoop ()
348                 {
349                         if (startup_files != null && startup_files.Length == 0)
350                                 InitTerminal (startup_files.Length == 0 && Driver.StartupEvalExpression == null);
351
352                         InitializeUsing ();
353
354                         LoadStartupFiles ();
355
356                         if (startup_files != null && startup_files.Length != 0) {
357                                 ExecuteSources (startup_files, false);
358                         } else {
359                                 if (Driver.StartupEvalExpression != null){
360                                         ReadEvalPrintLoopWith (p => {
361                                                 var ret = Driver.StartupEvalExpression;
362                                                 Driver.StartupEvalExpression = null;
363                                                 return ret;
364                                                 });
365                                 } else {
366                                         ReadEvalPrintLoopWith (GetLine);
367                                 }
368                                 
369                                 editor.SaveHistory ();
370                         }
371
372                         Console.CancelKeyPress -= ConsoleInterrupt;
373                         
374                         return 0;
375                 }
376
377                 protected virtual string Evaluate (string input)
378                 {
379                         bool result_set;
380                         object result;
381
382                         try {
383                                 input = evaluator.Evaluate (input, out result, out result_set);
384
385                                 if (result_set){
386                                         PrettyPrint (Console.Out, result);
387                                         Console.WriteLine ();
388                                 }
389                         } catch (Exception e){
390                                 Console.WriteLine (e);
391                                 return null;
392                         }
393                         
394                         return input;
395                 }
396
397                 static void p (TextWriter output, string s)
398                 {
399                         output.Write (s);
400                 }
401
402                 static string EscapeString (string s)
403                 {
404                         return s.Replace ("\"", "\\\"");
405                 }
406                 
407                 static void EscapeChar (TextWriter output, char c)
408                 {
409                         if (c == '\''){
410                                 output.Write ("'\\''");
411                                 return;
412                         }
413                         if (c > 32){
414                                 output.Write ("'{0}'", c);
415                                 return;
416                         }
417                         switch (c){
418                         case '\a':
419                                 output.Write ("'\\a'");
420                                 break;
421
422                         case '\b':
423                                 output.Write ("'\\b'");
424                                 break;
425                                 
426                         case '\n':
427                                 output.Write ("'\\n'");
428                                 break;
429                                 
430                         case '\v':
431                                 output.Write ("'\\v'");
432                                 break;
433                                 
434                         case '\r':
435                                 output.Write ("'\\r'");
436                                 break;
437                                 
438                         case '\f':
439                                 output.Write ("'\\f'");
440                                 break;
441                                 
442                         case '\t':
443                                 output.Write ("'\\t");
444                                 break;
445
446                         default:
447                                 output.Write ("'\\x{0:x}", (int) c);
448                                 break;
449                         }
450                 }
451
452                 // Some types (System.Json.JsonPrimitive) implement
453                 // IEnumerator and yet, throw an exception when we
454                 // try to use them, helper function to check for that
455                 // condition
456                 static internal bool WorksAsEnumerable (object obj)
457                 {
458                         IEnumerable enumerable = obj as IEnumerable;
459                         if (enumerable != null){
460                                 try {
461                                         enumerable.GetEnumerator ();
462                                         return true;
463                                 } catch {
464                                         // nothing, we return false below
465                                 }
466                         }
467                         return false;
468                 }
469                 
470                 internal static void PrettyPrint (TextWriter output, object result)
471                 {
472                         if (result == null){
473                                 p (output, "null");
474                                 return;
475                         }
476                         
477                         if (result is Array){
478                                 Array a = (Array) result;
479                                 
480                                 p (output, "{ ");
481                                 int top = a.GetUpperBound (0);
482                                 for (int i = a.GetLowerBound (0); i <= top; i++){
483                                         PrettyPrint (output, a.GetValue (i));
484                                         if (i != top)
485                                                 p (output, ", ");
486                                 }
487                                 p (output, " }");
488                         } else if (result is bool){
489                                 if ((bool) result)
490                                         p (output, "true");
491                                 else
492                                         p (output, "false");
493                         } else if (result is string){
494                                 p (output, String.Format ("\"{0}\"", EscapeString ((string)result)));
495                         } else if (result is IDictionary){
496                                 IDictionary dict = (IDictionary) result;
497                                 int top = dict.Count, count = 0;
498                                 
499                                 p (output, "{");
500                                 foreach (DictionaryEntry entry in dict){
501                                         count++;
502                                         p (output, "{ ");
503                                         PrettyPrint (output, entry.Key);
504                                         p (output, ", ");
505                                         PrettyPrint (output, entry.Value);
506                                         if (count != top)
507                                                 p (output, " }, ");
508                                         else
509                                                 p (output, " }");
510                                 }
511                                 p (output, "}");
512                         } else if (WorksAsEnumerable (result)) {
513                                 int i = 0;
514                                 p (output, "{ ");
515                                 foreach (object item in (IEnumerable) result) {
516                                         if (i++ != 0)
517                                                 p (output, ", ");
518
519                                         PrettyPrint (output, item);
520                                 }
521                                 p (output, " }");
522                         } else if (result is char) {
523                                 EscapeChar (output, (char) result);
524                         } else {
525                                 p (output, result.ToString ());
526                         }
527                 }
528
529                 public virtual int Run (string [] startup_files)
530                 {
531                         this.startup_files = startup_files;
532                         return ReadEvalPrintLoop ();
533                 }
534                 
535         }
536
537         //
538         // Stream helper extension methods
539         //
540         public static class StreamHelper {
541                 static DataConverter converter = DataConverter.LittleEndian;
542                 
543                 static void GetBuffer (this Stream stream, byte [] b)
544                 {
545                         int n, offset = 0;
546                         int len = b.Length;
547
548                         do {
549                                 n = stream.Read (b, offset, len);
550                                 if (n == 0)
551                                         throw new IOException ("End reached");
552
553                                 offset += n;
554                                 len -= n;
555                         } while (len > 0);
556                 }
557
558                 public static int GetInt (this Stream stream)
559                 {
560                         byte [] b = new byte [4];
561                         stream.GetBuffer (b);
562                         return converter.GetInt32 (b, 0);
563                 }
564
565                 public static string GetString (this Stream stream)
566                 {
567                         int len = stream.GetInt ();
568                         if (len == 0)
569                                 return "";
570
571                         byte [] b = new byte [len];
572                         stream.GetBuffer (b);
573
574                         return Encoding.UTF8.GetString (b);
575                 }
576
577                 public static void WriteInt (this Stream stream, int n)
578                 {
579                         byte [] bytes = converter.GetBytes (n);
580                         stream.Write (bytes, 0, bytes.Length);
581                 }
582         
583                 public static void WriteString (this Stream stream, string s)
584                 {
585                         stream.WriteInt (s.Length);
586                         byte [] bytes = Encoding.UTF8.GetBytes (s);
587                         stream.Write (bytes, 0, bytes.Length);
588                 }
589         }
590         
591         public enum AgentStatus : byte {
592                 // Received partial input, complete
593                 PARTIAL_INPUT  = 1,
594         
595                 // The result was set, expect the string with the result
596                 RESULT_SET     = 2,
597         
598                 // No result was set, complete
599                 RESULT_NOT_SET = 3,
600         
601                 // Errors and warnings string follows
602                 ERROR          = 4,
603
604                 // Stdout
605                 STDOUT         = 5,
606         }
607
608         class ClientCSharpShell : CSharpShell {
609                 string target_host;
610                 int target_port;
611                 
612                 public ClientCSharpShell (Evaluator evaluator, string target_host, int target_port) : base (evaluator)
613                 {
614                         this.target_port = target_port;
615                         this.target_host = target_host;
616                 }
617
618                 T ConnectServer<T> (Func<NetworkStream,T> callback, Action<Exception> error)
619                 {
620                         try {
621                                 var client = new TcpClient (target_host, target_port);
622                                 var ns = client.GetStream ();
623                                 T ret = callback (ns);
624                                 ns.Flush ();
625                                 ns.Close ();
626                                 client.Close ();
627                                 return ret;
628                         } catch (Exception e){
629                                 error (e);
630                                 return default(T);
631                         }
632                 }
633                 
634                 protected override string Evaluate (string input)
635                 {
636                         return ConnectServer<string> ((ns)=> {
637                                 try {
638                                         ns.WriteString ("EVALTXT");
639                                         ns.WriteString (input);
640
641                                         while (true) {
642                                                 AgentStatus s = (AgentStatus) ns.ReadByte ();
643                                         
644                                                 switch (s){
645                                                 case AgentStatus.PARTIAL_INPUT:
646                                                         return input;
647                                                 
648                                                 case AgentStatus.ERROR:
649                                                         string err = ns.GetString ();
650                                                         Console.Error.WriteLine (err);
651                                                         break;
652
653                                                 case AgentStatus.STDOUT:
654                                                         string stdout = ns.GetString ();
655                                                         Console.WriteLine (stdout);
656                                                         break;
657                                                 
658                                                 case AgentStatus.RESULT_NOT_SET:
659                                                         return null;
660                                                 
661                                                 case AgentStatus.RESULT_SET:
662                                                         string res = ns.GetString ();
663                                                         Console.WriteLine (res);
664                                                         return null;
665                                                 }
666                                         }
667                                 } catch (Exception e){
668                                         Console.Error.WriteLine ("Error evaluating expression, exception: {0}", e);
669                                 }
670                                 return null;
671                         }, (e) => {
672                                 Console.Error.WriteLine ("Error communicating with server {0}", e);
673                         });
674                 }
675                 
676                 public override int Run (string [] startup_files)
677                 {
678                         // The difference is that we do not call Evaluator.Init, that is done on the target
679                         this.startup_files = startup_files;
680                         return ReadEvalPrintLoop ();
681                 }
682         
683                 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
684                 {
685                         ConnectServer<int> ((ns)=> {
686                                 ns.WriteString ("INTERRUPT");
687                                 return 0;
688                         }, (e) => { });
689                 }
690                         
691         }
692
693 #if !ON_DOTNET
694         //
695         // A shell connected to a CSharpAgent running in a remote process.
696         //  - maybe add 'class_name' and 'method_name' arguments to LoadAgent.
697         //  - Support Gtk and Winforms main loops if detected, this should
698         //    probably be done as a separate agent in a separate place.
699         //
700         class ClientCSharpShell_v1 : CSharpShell {
701                 NetworkStream ns, interrupt_stream;
702                 
703                 public ClientCSharpShell_v1 (Evaluator evaluator, int pid)
704                         : base (evaluator)
705                 {
706                         // Create a server socket we listen on whose address is passed to the agent
707                         TcpListener listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
708                         listener.Start ();
709                         TcpListener interrupt_listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
710                         interrupt_listener.Start ();
711         
712                         string agent_assembly = typeof (ClientCSharpShell).Assembly.Location;
713                         string agent_arg = String.Format ("--agent:{0}:{1}" ,
714                                                           ((IPEndPoint)listener.Server.LocalEndPoint).Port,
715                                                           ((IPEndPoint)interrupt_listener.Server.LocalEndPoint).Port);
716         
717                         var vm = new Attach.VirtualMachine (pid);
718                         vm.Attach (agent_assembly, agent_arg);
719         
720                         /* Wait for the client to connect */
721                         TcpClient client = listener.AcceptTcpClient ();
722                         ns = client.GetStream ();
723                         TcpClient interrupt_client = interrupt_listener.AcceptTcpClient ();
724                         interrupt_stream = interrupt_client.GetStream ();
725         
726                         Console.WriteLine ("Connected.");
727                 }
728
729                 //
730                 // A remote version of Evaluate
731                 //
732                 protected override string Evaluate (string input)
733                 {
734                         ns.WriteString (input);
735                         while (true) {
736                                 AgentStatus s = (AgentStatus) ns.ReadByte ();
737         
738                                 switch (s){
739                                 case AgentStatus.PARTIAL_INPUT:
740                                         return input;
741         
742                                 case AgentStatus.ERROR:
743                                         string err = ns.GetString ();
744                                         Console.Error.WriteLine (err);
745                                         break;
746         
747                                 case AgentStatus.RESULT_NOT_SET:
748                                         return null;
749         
750                                 case AgentStatus.RESULT_SET:
751                                         string res = ns.GetString ();
752                                         Console.WriteLine (res);
753                                         return null;
754                                 }
755                         }
756                 }
757                 
758                 public override int Run (string [] startup_files)
759                 {
760                         // The difference is that we do not call Evaluator.Init, that is done on the target
761                         this.startup_files = startup_files;
762                         return ReadEvalPrintLoop ();
763                 }
764         
765                 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
766                 {
767                         // Do not about our program
768                         a.Cancel = true;
769         
770                         interrupt_stream.WriteByte (0);
771                         int c = interrupt_stream.ReadByte ();
772                         if (c != -1)
773                                 Console.WriteLine ("Execution interrupted");
774                 }
775                         
776         }
777
778         //
779         // This is the agent loaded into the target process when using --attach.
780         //
781         class CSharpAgent
782         {
783                 NetworkStream interrupt_stream;
784                 readonly Evaluator evaluator;
785                 TextWriter stderr;
786                 
787                 public CSharpAgent (Evaluator evaluator, String arg, TextWriter stderr)
788                 {
789                         this.evaluator = evaluator;
790                         this.stderr = stderr;
791                         new Thread (new ParameterizedThreadStart (Run)).Start (arg);
792                 }
793
794                 public void InterruptListener ()
795                 {
796                         while (true){
797                                 int b = interrupt_stream.ReadByte();
798                                 if (b == -1)
799                                         return;
800                                 evaluator.Interrupt ();
801                                 interrupt_stream.WriteByte (0);
802                         }
803                 }
804                 
805                 public void Run (object o)
806                 {
807                         string arg = (string)o;
808                         string ports = arg.Substring (8);
809                         int sp = ports.IndexOf (':');
810                         int port = Int32.Parse (ports.Substring (0, sp));
811                         int interrupt_port = Int32.Parse (ports.Substring (sp+1));
812         
813                         Console.WriteLine ("csharp-agent: started, connecting to localhost:" + port);
814         
815                         TcpClient client = new TcpClient ("127.0.0.1", port);
816                         TcpClient interrupt_client = new TcpClient ("127.0.0.1", interrupt_port);
817                         Console.WriteLine ("csharp-agent: connected.");
818         
819                         NetworkStream s = client.GetStream ();
820                         interrupt_stream = interrupt_client.GetStream ();
821                         new Thread (InterruptListener).Start ();
822
823                         try {
824                                 // Add all assemblies loaded later
825                                 AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
826         
827                                 // Add all currently loaded assemblies
828                                 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
829                                         // Some assemblies seem to be already loaded, and loading them again causes 'defined multiple times' errors
830                                         if (a.GetName ().Name != "mscorlib" && a.GetName ().Name != "System.Core" && a.GetName ().Name != "System")
831                                                 evaluator.ReferenceAssembly (a);
832                                 }
833         
834                                 RunRepl (s);
835                         } finally {
836                                 AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoaded;
837                                 client.Close ();
838                                 interrupt_client.Close ();
839                                 Console.WriteLine ("csharp-agent: disconnected.");                      
840                         }
841                 }
842         
843                 void AssemblyLoaded (object sender, AssemblyLoadEventArgs e)
844                 {
845                         evaluator.ReferenceAssembly (e.LoadedAssembly);
846                 }
847         
848                 public void RunRepl (NetworkStream s)
849                 {
850                         string input = null;
851
852                         while (!InteractiveBase.QuitRequested) {
853                                 try {
854                                         string error_string;
855                                         StringWriter error_output = (StringWriter)stderr;
856
857                                         string line = s.GetString ();
858         
859                                         bool result_set;
860                                         object result;
861         
862                                         if (input == null)
863                                                 input = line;
864                                         else
865                                                 input = input + "\n" + line;
866         
867                                         try {
868                                                 input = evaluator.Evaluate (input, out result, out result_set);
869                                         } catch (Exception e) {
870                                                 s.WriteByte ((byte) AgentStatus.ERROR);
871                                                 s.WriteString (e.ToString ());
872                                                 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
873                                                 continue;
874                                         }
875                                         
876                                         if (input != null){
877                                                 s.WriteByte ((byte) AgentStatus.PARTIAL_INPUT);
878                                                 continue;
879                                         }
880         
881                                         // Send warnings and errors back
882                                         error_string = error_output.ToString ();
883                                         if (error_string.Length != 0){
884                                                 s.WriteByte ((byte) AgentStatus.ERROR);
885                                                 s.WriteString (error_output.ToString ());
886                                                 error_output.GetStringBuilder ().Clear ();
887                                         }
888         
889                                         if (result_set){
890                                                 s.WriteByte ((byte) AgentStatus.RESULT_SET);
891                                                 StringWriter sr = new StringWriter ();
892                                                 CSharpShell.PrettyPrint (sr, result);
893                                                 s.WriteString (sr.ToString ());
894                                         } else {
895                                                 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
896                                         }
897                                 } catch (IOException) {
898                                         break;
899                                 } catch (Exception e){
900                                         Console.WriteLine (e);
901                                 }
902                         }
903                 }
904         }
905
906         public class UnixUtils {
907                 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
908                 extern static int _isatty (int fd);
909                         
910                 public static bool isatty (int fd)
911                 {
912                         try {
913                                 return _isatty (fd) == 1;
914                         } catch {
915                                 return false;
916                         }
917                 }
918         }
919 #endif
920 }
921         
922 namespace Mono.Management
923 {
924         interface IVirtualMachine {
925                 void LoadAgent (string filename, string args);
926         }
927 }
928