e09edcbe7276625aa806d42b2cf067b15891823c
[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
213                 if (remote) {
214                         filename = phpLBP.getMarker().getResource().getProjectRelativePath();
215                         filename = remoteSourcePath.append (filename);
216                 } else {
217                         filename = phpLBP.getMarker().getResource().getLocation();
218                 }
219
220                 String path = filename.toOSString();
221
222                 if ((pathmap != null) && remote) {
223                         java.util.Iterator i = pathmap.keySet().iterator();
224
225                         while (i.hasNext()) {
226                                 String k = (String) i.next();
227                                 if (path.startsWith(k)) {
228                                         path = pathmap.get(k) + path.substring(k.length());
229                                         break;
230                                 }
231                         }
232                 }
233
234                 if (pathtranslation && remote) {
235                         if (remoteSourcePath.toString ().substring (0, 1).equals ("/")) {
236                                 path = path.replace ('\\', '/');
237                         }
238                         else {
239                                 path = path.replace ('/', '\\');
240                         }
241                 }
242
243                 return path;
244         }
245
246         /**
247          *
248          */
249         public void addBreakpoint (IBreakpoint breakpoint) {
250                 if (DBGInt == null) {
251                 return;
252                 }
253
254                 int bpNo = 0;
255
256                 try {
257                 PHPLineBreakpoint phpLBP;
258
259                 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier()) {
260                         phpLBP = (PHPLineBreakpoint) breakpoint;
261
262                         //      bpNo= DBGInt.addBreakpoint(phpLBP.getMarker().getResource().getLocation().toOSString(), phpLBP.getLineNumber());
263
264                         bpNo = DBGInt.addBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber());
265                         phpLBP.setDBGBpNo(bpNo);
266                 }
267                 } catch (IOException e) {
268                     PHPDebugCorePlugin.log(e);
269                     stop();
270                 } catch (CoreException e) {
271                 PHPDebugCorePlugin.log(e);
272                 stop();
273                 }
274         }
275
276         /**
277          *
278          */
279         public void removeBreakpoint (IBreakpoint breakpoint) {
280                 if (DBGInt == null) {
281                 return;
282                 }
283
284                 try {
285                 PHPLineBreakpoint phpLBP;
286
287                 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier ()) {
288                         phpLBP = (PHPLineBreakpoint) breakpoint;
289
290                         //      bpNo= DBGInt.addBreakpoint(filename.toOSString(), phpLBP.getLineNumber());
291
292                         DBGInt.removeBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber(), phpLBP.getDBGBpNo());
293                 }
294                 } catch (IOException e) {
295                 PHPDebugCorePlugin.log (e);
296                 stop ();
297                 } catch (CoreException e) {
298                 PHPDebugCorePlugin.log (e);
299                 stop ();
300                 }
301         }
302
303         /**
304          *
305          */
306         public void phpLoopNotify () {
307                 phpLoop.notifyWait ();
308         }
309
310         /**
311          *
312          */
313         public void startPHPLoop () {
314                 phpLoop = new PHPLoop ();                                                                       // Create a DBG communication loop object
315
316                 phpLoop.start ();                                                                                       // And start the communication loop
317         }
318
319         /**
320          *
321          */
322         public void resume () {
323                 try {
324                 DBGInt.continueExecution();
325                 phpLoop.notifyWait();
326                 } catch (IOException e) {
327                 PHPeclipsePlugin.log("Debugging session ended.", e);
328                 stop();
329                 }
330         }
331
332         /**
333          *
334          */
335         public void pause () {
336                 try {
337                 if (null != DBGInt) {
338                                 DBGInt.pauseExecution();
339                         }
340                 else {
341                         // TODO Make sure the Suspend action is grayed out
342                         // when DBGInt is null
343                 }
344                 } catch (IOException e) {
345                 PHPDebugCorePlugin.log (e);
346                 stop ();
347                 }
348         }
349
350         /**
351          *
352          */
353         protected PHPDebugTarget getDebugTarget() {
354                 return debugTarget;
355         }
356
357         /**
358          *
359          * @param debugTarget
360          */
361         public void setDebugTarget (PHPDebugTarget debugTarget) {
362                 this.debugTarget = debugTarget;
363                 debugTarget.setPHPDBGProxy(this);
364         }
365
366         /**
367          * This method is called by a stackframe.
368          * It reads the variables from PHP via DBG
369          *
370          * @param frame The stackframe which wants the variables.
371          * @return      The list of variables for this stackframe.
372          */
373         public Vector readVariables (PHPStackFrame frame) {
374                 try {
375                 return DBGInt.getVariables (frame);                                             // Get the variables from DBG interface
376                 } catch (IOException ioex) {
377                 ioex.printStackTrace ();
378                 throw new RuntimeException (ioex.getMessage ());
379                 } catch (DebugException ex) {
380                     ex.printStackTrace ();
381                     throw new RuntimeException (ex.getMessage ());
382                 }
383         }
384
385         /**
386          *
387          * @param frame
388          * @param evalString
389          * @return
390          */
391         public PHPVariable[] eval (PHPStackFrame frame, String evalString) {
392                 try {
393                 return DBGInt.evalBlock (frame, evalString);
394                 //return DBGInt.getVariables(frame);
395                 } catch (IOException ioex) {
396                 ioex.printStackTrace();
397                 throw new RuntimeException(ioex.getMessage());
398                 } catch (DebugException ex) {
399                 ex.printStackTrace();
400                 throw new RuntimeException(ex.getMessage());
401                 }
402         }
403
404         public void readStepOverEnd (PHPStackFrame stackFrame) {
405                 try {
406                 DBGInt.stepOver();
407                 phpLoop.notifyWait();
408                 } catch (Exception e) {
409                 PHPDebugCorePlugin.log(e);
410                 }
411         }
412
413         public void readStepReturnEnd (PHPStackFrame stackFrame) {
414                 try {
415                 DBGInt.stepOut();
416                     phpLoop.notifyWait();
417                 } catch (Exception e) {
418                 PHPDebugCorePlugin.log(e);
419                 }
420         }
421
422         public void readStepIntoEnd (PHPStackFrame stackFrame) {
423                 try {
424                 DBGInt.stepInto();
425                 phpLoop.notifyWait();
426                 } catch (Exception e) {
427                 PHPDebugCorePlugin.log(e);
428                 }
429         }
430
431         /*
432          * public PHPStackFrame[] readFrames(PHPThread thread) { //try { //this.println("th " + thread.getId() + " ; f "); //return new
433          * FramesReader(getMultiReaderStrategy()).readFrames(thread); return null; //} catch (IOException e) { //
434          * PHPDebugCorePlugin.log(e); // return null; //}
435          *  }
436          */
437
438         public void closeSocket() throws IOException {
439                 if (socket != null) {
440                 socket.close();
441                 }
442         }
443
444         public void closeServerSocket() throws IOException {
445                 if (server != null) {
446                 server.close();
447                 }
448         }
449
450         public int getPort() {
451                 return port;
452         }
453
454         /**
455          *
456          *
457          */
458         class PHPLoop extends Thread {
459                 private boolean shouldStop;
460
461                 public PHPLoop () {
462                 shouldStop = false;
463                 this.setName ("PHPDebuggerLoop");
464                 }
465
466                 /**
467                  *
468                  */
469                 public synchronized void setShouldStop () {
470                         shouldStop = true;                                                                                      // The run loop should stop
471
472                         try {
473                                 // If the loop thread is blocked on the server socket,
474                                 // forcibly unblock it to avoid leaking the thread,
475                                 // the socket and the port
476                                 closeServerSocket ();
477                         } catch (IOException x) {
478                                 // Log this as a warning?
479                                 PHPDebugCorePlugin.log (x);
480                         }
481                 }
482
483                 /**
484                  *
485                  */
486                 public synchronized void notifyWait () {
487                 notify ();
488                 }
489
490                 /**
491                  *
492                  *
493                  */
494                 public void run () {
495                 try {
496                         int                     i;
497                                 int                     timeout;
498                         long                    interval        = 200;                                  // Wait 200 ms maximum for a DBG response
499                         boolean                 newconnect      = false;                                //
500                         Socket                  newSocket       = null;
501                         PHPStackFrame[] StackList;
502                         PHPDBGInterface newDBGInt;
503
504                         //                              synchronized (this) {
505                         //                                      wait();
506                         //                              }
507
508                         PHPMainThread = new PHPThread (getDebugTarget (), getPort ());
509                         PHPMainThread.setName ("Thread [main]");
510                         timeout       = 0;
511
512                         //                              while ((getDebugTarget() == null) && (timeout < 100)) {
513                         //                                      sleep(100);
514                         //                                      timeout++;
515                         //                              }
516                         // Be sure debug target is set
517                         //                              PHPMainThread.setDebugTarget(getDebugTarget());
518
519                                 getDebugTarget ().addThread (PHPMainThread);
520
521                         //System.out.println("Waiting for breakpoints.");
522
523                         while (!shouldStop) {                                                           // As long as nobody will stop us
524                                 newconnect = true;                              // The first time
525
526                                 try {
527                                         newSocket = server.accept();                            // Waits until DBG want to connect
528                                         //System.out.println("Accepted! : " + socket.toString());
529                                 } catch (SocketTimeoutException e) {
530                                         newconnect = false;                                                     // No one wants to connect (connection already done)
531                                 } catch (IOException e) {
532                                         PHPDebugCorePlugin.log(e);
533                                         return;
534                                 }
535
536                                 if (newconnect) {                                                               // Is it just after a new connection
537                                         if (DBGInt == null) {                                           // Do we have a DBG interface?
538                                         server.setSoTimeout(1);                                 // ???
539                                                 }
540
541                                         newDBGInt = new PHPDBGInterface (getReader (newSocket),                 // Create a new interface
542                                                                                                                  newSocket.getOutputStream (),
543                                                                                                                  thisProxy);
544                                         newDBGInt.waitResponse (1000);                          // Wait for the initial DBG response
545                                         newDBGInt.flushAllPackets ();               // Read and process the DBG response
546
547                                         // Check version and session ID
548                                         if ((DBGInt == null) ||                                 // If we have no interface
549                                                 (DBGInt.getSID () == newDBGInt.getSID ())) {// or the new session ID is different to the old one
550                                         DBGInt = newDBGInt;                                                     // Set the new interface as current one
551
552                                         try {
553                                                 closeSocket ();
554                                         }
555                                                         catch (IOException e) {
556                                                 PHPDebugCorePlugin.log (e);
557                                                 shouldStop = true;
558                                         }
559
560                                         socket = newSocket;
561                                         setBreakPoints ();
562                                         DBGInt.continueExecution ();                    // Notify DBG that PHP should continue
563                                         }
564                                                 else {
565                                         newDBGInt.continueExecution ();                         // Notify DBG that PHP should continue
566                                         newSocket.close ();
567                                         }
568                                 }
569
570                                 if (DBGInt.waitResponse (interval)) {                                           // Wait for a DBG response (200 ms)
571                                         DBGInt.flushAllPackets ();                                                              // If we got something, read and process it
572
573                                         if (DBGInt.BPUnderHit != 0) {                                                   // ???
574                                         StackList = DBGInt.getStackList ();                 // Get the stack list from DBGInterface
575
576                                             if (StackList.length > 0) {                         // If there is something in stack list
577                                                 for (i = 0; i < StackList.length; i++) {        // For all stack list
578                                                         StackList[i].setThread (PHPMainThread);     // Set the PHPTread for all PHPStackFrames
579
580                                                         if (DBGInt.getModByNo (StackList[i].getModNo ()).equals ("")) {
581                                                                 DBGInt.getSourceTree ();
582                                                         }
583
584                                                         StackList[i].setFile (DBGInt.getModByNo (StackList[i].getModNo ()));
585                                                 }
586
587                                                 PHPMainThread.setStackFrames (StackList);
588                                         }
589
590                                         PHPMainThread.suspend ();                             // Fire debug event
591
592                                             synchronized (this) {
593                                                 wait ();
594                                         }
595                                         }
596                                 }
597
598                                 if (remote) {
599                                         if (PHPMainThread.isTerminated ()) {
600                                         shouldStop = true;
601
602                                             break;                                                // Go for terminating the thread
603                                         }
604                                 } else {
605                                         if (PHPMainThread.isTerminated () ||
606                                                 getDebugTarget ().getProcess ().isTerminated ()) {
607                                         shouldStop = true;
608
609                                         break;                                                // Go for terminating the thread
610                                         }
611                                 }
612                         }
613                 } catch (Exception ex) {
614                         PHPDebugCorePlugin.log (ex);
615                         System.out.println (ex);
616                 } finally {
617                         try {
618                                 getDebugTarget ().terminate ();
619                                 closeSocket();
620                                 closeServerSocket ();
621                         } catch (IOException e) {
622                                 PHPDebugCorePlugin.log (e);
623
624                                 return;
625                         }
626
627                         //System.out.println("Socket loop finished.");
628                 }
629                 }
630         }
631 }