e93a7f1deb0a7cbf9490a9720b7814b08b36b37f
[phpeclipse.git] / net.sourceforge.phpeclipse.debug.core / src / net / sourceforge / phpdt / internal / debug / core / PHPDBGProxy.java
1 /***********************************************************************************************************************************
2  * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made
3  * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at
4  * http://www.eclipse.org/legal/cpl-v10.html
5  *
6  * Contributors: IBM Corporation - Initial implementation Vicente Fernando - www.alfersoft.com.ar Christian Perkonig - remote debug
7  **********************************************************************************************************************************/
8 package net.sourceforge.phpdt.internal.debug.core;
9
10 import java.io.BufferedReader;
11 import java.io.IOException;
12 import java.io.InputStreamReader;
13 import java.io.OutputStream;
14 import java.net.ServerSocket;
15 import java.net.Socket;
16 import java.net.SocketTimeoutException;
17 import java.util.Map;
18 import java.util.Vector;
19
20 import net.sourceforge.phpdt.internal.debug.core.breakpoints.PHPLineBreakpoint;
21 import net.sourceforge.phpdt.internal.debug.core.model.PHPDebugTarget;
22 import net.sourceforge.phpdt.internal.debug.core.model.PHPStackFrame;
23 import net.sourceforge.phpdt.internal.debug.core.model.PHPThread;
24 import net.sourceforge.phpdt.internal.debug.core.model.PHPVariable;
25 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
26
27 import org.eclipse.core.runtime.CoreException;
28 import org.eclipse.core.runtime.IPath;
29 import org.eclipse.core.runtime.Path;
30 import org.eclipse.debug.core.DebugException;
31 import org.eclipse.debug.core.DebugPlugin;
32 import org.eclipse.debug.core.model.IBreakpoint;
33
34 public class PHPDBGProxy {
35
36         private ServerSocket            server          = null;
37         private BufferedReader          reader          = null;
38         private PHPDBGInterface         DBGInt          = null;         // The DBG interface which is linked with the proxy
39         private PHPDebugTarget          debugTarget = null;
40         private PHPDBGProxy             thisProxy       = null;
41         private PHPLoop                         phpLoop;
42         private PHPThread                       PHPMainThread;
43         private Socket                          socket;
44         private int                             port;
45         private boolean                         remote;
46         private boolean                         pathtranslation;
47         private Map                             pathmap;
48         private IPath                           remoteSourcePath;
49
50         /**
51          */
52         public PHPDBGProxy () {
53           thisProxy = this;
54         }
55
56         /**
57          * @param remote
58          * @param remoteSourcePath
59          * @param pathTranslate
60          * @param paths
61          */
62         public PHPDBGProxy (boolean remote, String remoteSourcePath, boolean pathTranslate, Map paths) {
63                 thisProxy             = this;
64                 this.remote               = remote;
65                 this.remoteSourcePath = new Path (remoteSourcePath);
66                 this.pathmap          = paths;
67                 this.pathtranslation  = pathTranslate;
68         }
69
70         /**
71          *
72          */
73         public void start () {
74                 createServerSocket ();                                      // Create a server socket for communicatio with DBG
75
76                 this.startPHPLoop ();                                                                           //
77         }
78
79         /**
80          *
81          */
82         public void stop () {
83                 phpLoop.setShouldStop ();                                   // Notify the thread's 'run loop' to stop
84
85                 if (DBGInt != null) {                                       // If we have a DBG interface linked with this proxy
86                 DBGInt.setShouldStop ();                                //  Notify the DBG interface to stop the waiting for response
87                 }
88
89                 if (!remote) {                                              // If it's not a remote proxy session
90                 try {
91                         getDebugTarget ().getProcess ().terminate ();       //
92                 } catch (DebugException e) {
93                         e.printStackTrace ();
94                 }
95                 }
96
97                 phpLoop.notifyWait ();
98         }
99
100         /**
101          * TODO Is this method called from anywhere?
102          *
103          * Returns a already created server socket, or
104          * creates a server socket if none exists, and
105          * returns the newly created one.
106          *
107          * @return A server socket
108          */
109         protected ServerSocket getServerSocket () throws IOException {
110                 if (server == null) {                                                                           // Do we have already a server socket
111                 createServerSocket ();                                                                  //  No, then create one
112                 }
113
114                 return server;                                                                                          // Return the server socket
115         }
116
117         /**
118          *
119          * TODO The example for setting up DBG within PHP.ini shows ports from 10000 to 10016 ???
120          * if my interpretation is correct.
121          * How can we find the correct DBG port?
122          */
123         protected void createServerSocket () {
124                 port = SocketUtil.findUnusedLocalPort ("localhost", 10001, 10101);      // Get the first free port in the range from 10001 to 10101
125
126 //          port = 10001;
127                 if (port == -1) {                                                   // Did we get a free port?
128                 PHPDebugCorePlugin.log (5, "Cannot find free port!!!!");        //  No, output a error message
129
130                 return;                                                         //  And return
131                 }
132                 try {
133                 if (server == null) {                                           // If there is no server socket yet
134                         server = new ServerSocket (port);                           //  create a server socket for the free port
135                         //System.out.println("ServerSocket on port: " + port);
136                 }
137                 } catch (IOException e) {
138                 // IO Error
139                 PHPDebugCorePlugin.log (e);
140                 stop ();
141                 }
142         }
143
144         /**
145          *
146          */
147         public Socket getSocket () throws IOException {
148                 return socket;                                                          // Return the socket
149         }
150
151         /**
152          * Set the DBG interface which is linked to this proxy
153          *
154          * @paran DBGInt The DGB interface which is linked with this proxy
155          */
156         protected void setDBGInterface (PHPDBGInterface DBGInt) {
157                 this.DBGInt = DBGInt;
158         }
159
160         /**
161          * Give back a buffered input stream for the socket which is
162          * linked with this proxy
163          */
164         public BufferedReader getReader () throws IOException {
165                 if (reader == null) {                                               // Do we already have a buffered input stream
166                 reader = new BufferedReader (new InputStreamReader (this.getSocket ().getInputStream (),
167                                                                         "ISO8859_1"));
168                 }
169
170           return reader;                                                      // Return the buffered input stream
171         }
172
173         /**
174          *
175          */
176         public BufferedReader getReader (Socket socket) throws IOException {
177                 if (socket != null) {                                                                                           // Is a socket provided
178                 return new BufferedReader (new InputStreamReader (socket.getInputStream (),
179                                                                                                   "ISO8859_1"));  // Then create a buffered input stream
180                 }
181                 else {
182                 return null;                                                      // Without a socket we can't create a input stream
183                 }
184         }
185
186         /**
187          *
188          * @return The output stream for this proxy's socket
189          */
190         public OutputStream getOutputStream () throws IOException {
191                 return this.getSocket ().getOutputStream ();
192         }
193
194         /**
195          *
196          */
197         protected void setBreakPoints () throws IOException, CoreException {
198                 IBreakpoint[] breakpoints = DebugPlugin.getDefault ().getBreakpointManager ().getBreakpoints ();
199
200                 for (int i = 0; i < breakpoints.length; i++) {
201                         if (breakpoints[i].isEnabled ()) {
202                                 addBreakpoint (breakpoints[i]);
203                         }
204                 }
205         }
206
207         /**
208          *
209          */
210         private String MapPath (PHPLineBreakpoint phpLBP) {
211                 IPath    filename;
212                 IPath    remotePath;
213                 IPath    newpath;
214                 IPath    localPath;
215                 String   local;
216
217                 if (remote) {
218                         filename = phpLBP.getMarker().getResource().getProjectRelativePath();
219                         filename = remoteSourcePath.append (filename);
220                 } else {
221                         filename = phpLBP.getMarker().getResource().getLocation();
222                 }
223
224                 String path = filename.toOSString();
225
226                 if ((pathmap != null) && remote) {
227                         java.util.Iterator i = pathmap.keySet().iterator();
228
229                         while (i.hasNext()) {
230                                 String k = (String) i.next();
231                                 if (path.startsWith(k)) {
232                                         path = pathmap.get(k) + path.substring(k.length());
233                                         break;
234                                 }
235                         }
236                 }
237
238                 if (remoteSourcePath.isEmpty ()) {
239                         if ((pathmap != null) && remote) {
240                                 java.util.Iterator iterator = pathmap.keySet().iterator();
241
242                                 while (iterator.hasNext ()) {
243                                         local      = (String) iterator.next ();                 // Get the local/client side path of the mapping
244                                         remotePath = new Path ((String) pathmap.get (local));   // Get the remote/server side path of the mapping
245                                         localPath  = new Path (local);                          // Get the remote/server side path of the mapping
246
247                                         if (localPath.isPrefixOf (filename)) {                  // Starts the remote/server side file path with the remote/server side mapping path
248                                                                                                                                                         // dann prefix abhängen und den remote path davorhägen
249                                                 newpath = filename.removeFirstSegments (localPath.matchingFirstSegments (filename));
250                                                 newpath = remotePath.append (newpath);
251                                                 path    = newpath.toString ();
252
253                                                 if (path.substring (0, 1).equals ("/")) {
254                                                         path = path.replace ('\\', '/');
255                                                 }
256                                                 else {
257                                                         path = path.replace ('/', '\\');
258                                                 }
259
260                                                 return path;
261                                         }
262                                 }
263                         }
264                 }
265                 else {
266                         if (pathtranslation && remote) {
267                                 if (remoteSourcePath.toString ().substring (0, 1).equals ("/")) {
268                                         path = path.replace ('\\', '/');
269                                 }
270                                 else {
271                                         path = path.replace ('/', '\\');
272                                 }
273                         }
274                 }
275
276                 return path;
277         }
278
279         /**
280          *
281          */
282         public void addBreakpoint (IBreakpoint breakpoint) {
283                 if (DBGInt == null) {
284                 return;
285                 }
286
287                 int bpNo = 0;
288
289                 try {
290                 PHPLineBreakpoint phpLBP;
291
292                 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier()) {
293                         phpLBP = (PHPLineBreakpoint) breakpoint;
294
295                         //      bpNo= DBGInt.addBreakpoint(phpLBP.getMarker().getResource().getLocation().toOSString(), phpLBP.getLineNumber());
296
297                         bpNo = DBGInt.addBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber());
298                         phpLBP.setDBGBpNo(bpNo);
299                 }
300                 } catch (IOException e) {
301                     PHPDebugCorePlugin.log(e);
302                     stop();
303                 } catch (CoreException e) {
304                 PHPDebugCorePlugin.log(e);
305                 stop();
306                 }
307         }
308
309         /**
310          *
311          */
312         public void removeBreakpoint (IBreakpoint breakpoint) {
313                 if (DBGInt == null) {
314                 return;
315                 }
316
317                 try {
318                 PHPLineBreakpoint phpLBP;
319
320                 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier ()) {
321                         phpLBP = (PHPLineBreakpoint) breakpoint;
322
323                         //      bpNo= DBGInt.addBreakpoint(filename.toOSString(), phpLBP.getLineNumber());
324
325                         DBGInt.removeBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber(), phpLBP.getDBGBpNo());
326                 }
327                 } catch (IOException e) {
328                 PHPDebugCorePlugin.log (e);
329                 stop ();
330                 } catch (CoreException e) {
331                 PHPDebugCorePlugin.log (e);
332                 stop ();
333                 }
334         }
335
336         /**
337          *
338          */
339         public void phpLoopNotify () {
340                 phpLoop.notifyWait ();
341         }
342
343         /**
344          *
345          */
346         public void startPHPLoop () {
347                 phpLoop = new PHPLoop ();                                                                       // Create a DBG communication loop object
348
349                 phpLoop.start ();                                                                                       // And start the communication loop
350         }
351
352         /**
353          *
354          */
355         public void resume () {
356                 try {
357                 DBGInt.continueExecution();
358                 phpLoop.notifyWait();
359                 } catch (IOException e) {
360                 PHPeclipsePlugin.log("Debugging session ended.", e);
361                 stop();
362                 }
363         }
364
365         /**
366          *
367          */
368         public void pause () {
369                 try {
370                 if (null != DBGInt) {
371                                 DBGInt.pauseExecution();
372                         }
373                 else {
374                         // TODO Make sure the Suspend action is grayed out
375                         // when DBGInt is null
376                 }
377                 } catch (IOException e) {
378                 PHPDebugCorePlugin.log (e);
379                 stop ();
380                 }
381         }
382
383         /**
384          *
385          */
386         protected PHPDebugTarget getDebugTarget() {
387                 return debugTarget;
388         }
389
390         /**
391          *
392          * @param debugTarget
393          */
394         public void setDebugTarget (PHPDebugTarget debugTarget) {
395                 this.debugTarget = debugTarget;
396                 debugTarget.setPHPDBGProxy(this);
397         }
398
399         /**
400          * This method is called by a stackframe.
401          * It reads the variables from PHP via DBG
402          *
403          * @param frame The stackframe which wants the variables.
404          * @return      The list of variables for this stackframe.
405          */
406         public Vector readVariables (PHPStackFrame frame) {
407                 try {
408                 return DBGInt.getVariables (frame);                                             // Get the variables from DBG interface
409                 } catch (IOException ioex) {
410                 ioex.printStackTrace ();
411                 throw new RuntimeException (ioex.getMessage ());
412                 } catch (DebugException ex) {
413                     ex.printStackTrace ();
414                     throw new RuntimeException (ex.getMessage ());
415                 }
416         }
417
418         /**
419          *
420          * @param frame
421          * @param evalString
422          * @return
423          */
424         public PHPVariable[] eval (PHPStackFrame frame, String evalString) {
425                 try {
426                 return DBGInt.evalBlock (frame, evalString);
427                 //return DBGInt.getVariables(frame);
428                 } catch (IOException ioex) {
429                 ioex.printStackTrace();
430                 throw new RuntimeException(ioex.getMessage());
431                 } catch (DebugException ex) {
432                 ex.printStackTrace();
433                 throw new RuntimeException(ex.getMessage());
434                 }
435         }
436
437         public void readStepOverEnd (PHPStackFrame stackFrame) {
438                 try {
439                 DBGInt.stepOver();
440                 phpLoop.notifyWait();
441                 } catch (Exception e) {
442                 PHPDebugCorePlugin.log(e);
443                 }
444         }
445
446         public void readStepReturnEnd (PHPStackFrame stackFrame) {
447                 try {
448                 DBGInt.stepOut();
449                     phpLoop.notifyWait();
450                 } catch (Exception e) {
451                 PHPDebugCorePlugin.log(e);
452                 }
453         }
454
455         public void readStepIntoEnd (PHPStackFrame stackFrame) {
456                 try {
457                 DBGInt.stepInto();
458                 phpLoop.notifyWait();
459                 } catch (Exception e) {
460                 PHPDebugCorePlugin.log(e);
461                 }
462         }
463
464         /*
465          * public PHPStackFrame[] readFrames(PHPThread thread) { //try { //this.println("th " + thread.getId() + " ; f "); //return new
466          * FramesReader(getMultiReaderStrategy()).readFrames(thread); return null; //} catch (IOException e) { //
467          * PHPDebugCorePlugin.log(e); // return null; //}
468          *  }
469          */
470
471         public void closeSocket() throws IOException {
472                 if (socket != null) {
473                 socket.close();
474                 }
475         }
476
477         public void closeServerSocket() throws IOException {
478                 if (server != null) {
479                 server.close();
480                 }
481         }
482
483         public int getPort() {
484                 return port;
485         }
486
487         /**
488          *
489          *
490          */
491         class PHPLoop extends Thread {
492                 private boolean shouldStop;
493
494                 public PHPLoop () {
495                 shouldStop = false;
496                 this.setName ("PHPDebuggerLoop");
497                 }
498
499                 /**
500                  *
501                  */
502                 public synchronized void setShouldStop () {
503                         shouldStop = true;                                                                                      // The run loop should stop
504
505                         try {
506                                 // If the loop thread is blocked on the server socket,
507                                 // forcibly unblock it to avoid leaking the thread,
508                                 // the socket and the port
509                                 closeServerSocket ();
510                         } catch (IOException x) {
511                                 // Log this as a warning?
512                                 PHPDebugCorePlugin.log (x);
513                         }
514                 }
515
516                 /**
517                  *
518                  */
519                 public synchronized void notifyWait () {
520                 notify ();
521                 }
522
523                 /**
524                  *
525                  *
526                  */
527                 public void run () {
528                 try {
529                         int                     i;
530                                 int                     timeout;
531                         long                    interval        = 200;                                  // Wait 200 ms maximum for a DBG response
532                         boolean                 newconnect      = false;                                //
533                         Socket                  newSocket       = null;
534                         PHPStackFrame[] StackList;
535                         PHPDBGInterface newDBGInt;
536
537                         //                              synchronized (this) {
538                         //                                      wait();
539                         //                              }
540
541                         PHPMainThread = new PHPThread (getDebugTarget (), getPort ());
542                         PHPMainThread.setName ("Thread [main]");
543                         timeout       = 0;
544
545                         //                              while ((getDebugTarget() == null) && (timeout < 100)) {
546                         //                                      sleep(100);
547                         //                                      timeout++;
548                         //                              }
549                         // Be sure debug target is set
550                         //                              PHPMainThread.setDebugTarget(getDebugTarget());
551
552                                 getDebugTarget ().addThread (PHPMainThread);
553
554                         //System.out.println("Waiting for breakpoints.");
555
556                         while (!shouldStop) {                                                           // As long as nobody will stop us
557                                 newconnect = true;                              // The first time
558
559                                 try {
560                                         newSocket = server.accept();                            // Waits until DBG want to connect
561                                         //System.out.println("Accepted! : " + socket.toString());
562                                 } catch (SocketTimeoutException e) {
563                                         newconnect = false;                                                     // No one wants to connect (connection already done)
564                                 } catch (IOException e) {
565                                         PHPDebugCorePlugin.log(e);
566                                         return;
567                                 }
568
569                                 if (newconnect) {                                                               // Is it just after a new connection
570                                         if (DBGInt == null) {                                           // Do we have a DBG interface?
571                                         server.setSoTimeout(1);                                 // ???
572                                                 }
573
574                                         newDBGInt = new PHPDBGInterface (getReader (newSocket),                 // Create a new interface
575                                                                                                                  newSocket.getOutputStream (),
576                                                                                                                  thisProxy);
577                                         newDBGInt.waitResponse (1000);                          // Wait for the initial DBG response
578                                         newDBGInt.flushAllPackets ();               // Read and process the DBG response
579
580                                         // Check version and session ID
581                                         if ((DBGInt == null) ||                                 // If we have no interface
582                                                 (DBGInt.getSID () == newDBGInt.getSID ())) {// or the new session ID is different to the old one
583                                         DBGInt = newDBGInt;                                                     // Set the new interface as current one
584
585                                         try {
586                                                 closeSocket ();
587                                         }
588                                                         catch (IOException e) {
589                                                 PHPDebugCorePlugin.log (e);
590                                                 shouldStop = true;
591                                         }
592
593                                         socket = newSocket;
594                                         setBreakPoints ();
595                                         DBGInt.continueExecution ();                    // Notify DBG that PHP should continue
596                                         }
597                                                 else {
598                                         newDBGInt.continueExecution ();                         // Notify DBG that PHP should continue
599                                         newSocket.close ();
600                                         }
601                                 }
602
603                                 if (DBGInt.waitResponse (interval)) {                                           // Wait for a DBG response (200 ms)
604                                         DBGInt.flushAllPackets ();                                                              // If we got something, read and process it
605
606                                         if (DBGInt.BPUnderHit != 0) {                                                   // ???
607                                         StackList = DBGInt.getStackList ();                 // Get the stack list from DBGInterface
608
609                                             if (StackList.length > 0) {                         // If there is something in stack list
610                                                 for (i = 0; i < StackList.length; i++) {        // For all stack list
611                                                         StackList[i].setThread (PHPMainThread);     // Set the PHPTread for all PHPStackFrames
612
613                                                         if (DBGInt.getModByNo (StackList[i].getModNo ()).equals ("")) {
614                                                                 DBGInt.getSourceTree ();
615                                                         }
616
617                                                         StackList[i].setFile (DBGInt.getModByNo (StackList[i].getModNo ()));
618                                                 }
619
620                                                 PHPMainThread.setStackFrames (StackList);
621                                         }
622
623                                         PHPMainThread.suspend ();                             // Fire debug event
624
625                                             synchronized (this) {
626                                                 wait ();
627                                         }
628                                         }
629                                 }
630
631                                 if (remote) {
632                                         if (PHPMainThread.isTerminated ()) {
633                                         shouldStop = true;
634
635                                             break;                                                // Go for terminating the thread
636                                         }
637                                 } else {
638                                         if (PHPMainThread.isTerminated () ||
639                                                 getDebugTarget ().getProcess ().isTerminated ()) {
640                                         shouldStop = true;
641
642                                         break;                                                // Go for terminating the thread
643                                         }
644                                 }
645                         }
646                 } catch (Exception ex) {
647                         PHPDebugCorePlugin.log (ex);
648                         System.out.println (ex);
649                 } finally {
650                         try {
651                                 getDebugTarget ().terminate ();
652                                 closeSocket();
653                                 closeServerSocket ();
654                         } catch (IOException e) {
655                                 PHPDebugCorePlugin.log (e);
656
657                                 return;
658                         }
659
660                         //System.out.println("Socket loop finished.");
661                 }
662                 }
663         }
664 }