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