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
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;
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;
18 import java.util.Vector;
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;
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;
34 public class PHPDBGProxy {
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;
45 private boolean remote;
46 private boolean pathtranslation;
48 private IPath remoteSourcePath;
52 public PHPDBGProxy () {
58 * @param remoteSourcePath
59 * @param pathTranslate
62 public PHPDBGProxy (boolean remote, String remoteSourcePath, boolean pathTranslate, Map paths) {
65 this.remoteSourcePath = new Path (remoteSourcePath);
67 this.pathtranslation = pathTranslate;
73 public void start () {
74 createServerSocket (); // Create a server socket for communicatio with DBG
76 this.startPHPLoop (); //
83 phpLoop.setShouldStop (); // Notify the thread's 'run loop' to stop
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
89 if (!remote) { // If it's not a remote proxy session
91 getDebugTarget ().getProcess ().terminate (); //
92 } catch (DebugException e) {
97 phpLoop.notifyWait ();
100 public void setTerminated () {
102 PHPMainThread.terminate ();
104 catch (DebugException e) {
109 * TODO Is this method called from anywhere?
111 * Returns a already created server socket, or
112 * creates a server socket if none exists, and
113 * returns the newly created one.
115 * @return A server socket
117 protected ServerSocket getServerSocket () throws IOException {
118 if (server == null) { // Do we have already a server socket
119 createServerSocket (); // No, then create one
122 return server; // Return the server socket
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.
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.
134 * @note: The free dbg version doesn't allow to set the appropriate port within php.ini!
138 protected void createServerSocket () {
140 port = SocketUtil.findUnusedLocalPort ("localhost", 10001, 10101); // Get the first free port in the range from 10001 to 10101
143 port = SocketUtil.findUnusedLocalPort ("localhost", 7869, 7869); // Get the first free port in the range from 7869 to 7869
146 if (port == -1) { // Did we get a free port?
147 PHPDebugCorePlugin.log (5, "Cannot find free port!!!!"); // No, output a error message
149 return; // And return
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);
156 } catch (IOException e) {
157 PHPDebugCorePlugin.log (e);
165 public Socket getSocket () throws IOException {
166 return socket; // Return the socket
170 * Set the DBG interface which is linked to this proxy
172 * @paran DBGInt The DGB interface which is linked with this proxy
174 protected void setDBGInterface (PHPDBGInterface DBGInt) {
175 this.DBGInt = DBGInt;
179 * Get the DBG interface which is linked to this proxy
181 * @paran DBGInt The DGB interface which is linked with this proxy
183 public PHPDBGInterface getDBGInterface () {
188 * Give back a buffered input stream for the socket which is
189 * linked with this proxy
191 public BufferedReader getReader () throws IOException {
192 if (reader == null) { // Do we already have a buffered input stream
193 reader = new BufferedReader (new InputStreamReader (this.getSocket ().getInputStream (),
197 return reader; // Return the buffered input stream
203 public BufferedReader getReader (Socket socket) throws IOException {
204 if (socket != null) { // Is a socket provided
205 return new BufferedReader (new InputStreamReader (socket.getInputStream (),
206 "ISO8859_1")); // Then create a buffered input stream
209 return null; // Without a socket we can't create a input stream
215 * @return The output stream for this proxy's socket
217 public OutputStream getOutputStream () throws IOException {
218 return this.getSocket ().getOutputStream ();
224 protected void setBreakPoints () throws IOException, CoreException {
225 IBreakpoint[] breakpoints = DebugPlugin.getDefault ().getBreakpointManager ().getBreakpoints ();
227 for (int i = 0; i < breakpoints.length; i++) {
228 if (breakpoints[i].isEnabled ()) {
229 addBreakpoint (breakpoints[i]);
237 private String MapPath (PHPLineBreakpoint phpLBP) {
245 filename = phpLBP.getMarker().getResource().getProjectRelativePath();
246 filename = remoteSourcePath.append (filename);
248 filename = phpLBP.getMarker().getResource().getLocation();
251 String path = filename.toOSString();
253 if ((pathmap != null) && remote) {
254 java.util.Iterator i = pathmap.keySet().iterator();
256 while (i.hasNext()) {
257 String k = (String) i.next();
258 if (path.startsWith(k)) {
259 path = pathmap.get(k) + path.substring(k.length());
265 if (remoteSourcePath.isEmpty ()) {
266 if ((pathmap != null) && remote) {
267 java.util.Iterator iterator = pathmap.keySet().iterator();
269 while (iterator.hasNext ()) {
270 local = (String) iterator.next (); // Get the local/client side path of the mapping
271 remotePath = new Path ((String) pathmap.get (local)); // Get the remote/server side path of the mapping
272 localPath = new Path (local); // Get the remote/server side path of the mapping
274 if (localPath.isPrefixOf (filename)) { // Starts the remote/server side file path with the remote/server side mapping path
275 // dann prefix abhängen und den remote path davorhägen
276 newpath = filename.removeFirstSegments (localPath.matchingFirstSegments (filename));
277 newpath = remotePath.append (newpath);
278 path = newpath.toString ();
280 if (path.substring (0, 1).equals ("/")) {
281 path = path.replace ('\\', '/');
284 path = path.replace ('/', '\\');
293 if (pathtranslation && remote) {
294 if (remoteSourcePath.toString ().substring (0, 1).equals ("/")) {
295 path = path.replace ('\\', '/');
298 path = path.replace ('/', '\\');
309 public void addBreakpoint (IBreakpoint breakpoint) {
310 if (DBGInt == null) {
317 PHPLineBreakpoint phpLBP;
319 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier()) {
320 phpLBP = (PHPLineBreakpoint) breakpoint;
322 // bpNo= DBGInt.addBreakpoint(phpLBP.getMarker().getResource().getLocation().toOSString(), phpLBP.getLineNumber());
323 if (phpLBP.isConditionEnabled ()) {
324 bpNo = DBGInt.addBreakpoint (MapPath(phpLBP),
325 phpLBP.getLineNumber(),
326 phpLBP.getHitCount(),
327 phpLBP.getCondition ());
330 bpNo = DBGInt.addBreakpoint (MapPath(phpLBP),
331 phpLBP.getLineNumber(),
332 phpLBP.getHitCount(),
336 phpLBP.setDBGBpNo(bpNo);
338 } catch (IOException e) {
339 PHPDebugCorePlugin.log(e);
341 } catch (CoreException e) {
342 PHPDebugCorePlugin.log(e);
350 public void removeBreakpoint (IBreakpoint breakpoint) {
351 if (DBGInt == null) {
356 PHPLineBreakpoint phpLBP;
358 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier ()) {
359 phpLBP = (PHPLineBreakpoint) breakpoint;
361 // bpNo= DBGInt.addBreakpoint(filename.toOSString(), phpLBP.getLineNumber());
363 DBGInt.removeBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber(), phpLBP.getDBGBpNo());
365 } catch (IOException e) {
366 PHPDebugCorePlugin.log (e);
368 } catch (CoreException e) {
369 PHPDebugCorePlugin.log (e);
377 public void phpLoopNotify () {
378 phpLoop.notifyWait ();
384 public void startPHPLoop () {
385 phpLoop = new PHPLoop (); // Create a DBG communication loop object
387 phpLoop.start (); // And start the communication loop
393 public void resume () {
395 DBGInt.continueExecution();
396 phpLoop.notifyWait();
397 } catch (IOException e) {
398 PHPeclipsePlugin.log("Debugging session ended.", e);
406 public void pause () {
408 if (null != DBGInt) {
409 DBGInt.pauseExecution();
412 // TODO Make sure the Suspend action is grayed out
413 // when DBGInt is null
415 } catch (IOException e) {
416 PHPDebugCorePlugin.log (e);
424 protected PHPDebugTarget getDebugTarget() {
429 * Is called by the DebuggerRunner
433 public void setDebugTarget (PHPDebugTarget debugTarget) {
434 this.debugTarget = debugTarget;
435 debugTarget.setPHPDBGProxy(this);
439 * This method is called by a stackframe.
440 * It reads the variables from PHP via DBG
442 * @param frame The stackframe which wants the variables.
443 * @return The list of variables for this stackframe.
445 public Vector readVariables (PHPStackFrame frame) {
447 return DBGInt.getVariables (frame); // Get the variables from DBG interface
448 } catch (IOException ioex) {
449 ioex.printStackTrace ();
450 throw new RuntimeException (ioex.getMessage ());
451 } catch (DebugException ex) {
452 ex.printStackTrace ();
453 throw new RuntimeException (ex.getMessage ());
463 public PHPVariable[] eval (PHPStackFrame frame, String evalString) {
465 return DBGInt.evalBlock (frame, evalString);
466 //return DBGInt.getVariables(frame);
467 } catch (IOException ioex) {
468 ioex.printStackTrace();
469 throw new RuntimeException(ioex.getMessage());
470 } catch (DebugException ex) {
471 ex.printStackTrace();
472 throw new RuntimeException(ex.getMessage());
476 public void readStepOverEnd (PHPStackFrame stackFrame) {
479 phpLoop.notifyWait();
480 } catch (Exception e) {
481 PHPDebugCorePlugin.log(e);
485 public void readStepReturnEnd (PHPStackFrame stackFrame) {
488 phpLoop.notifyWait();
489 } catch (Exception e) {
490 PHPDebugCorePlugin.log(e);
494 public void readStepIntoEnd (PHPStackFrame stackFrame) {
497 phpLoop.notifyWait();
498 } catch (Exception e) {
499 PHPDebugCorePlugin.log(e);
504 * public PHPStackFrame[] readFrames(PHPThread thread) { //try { //this.println("th " + thread.getId() + " ; f "); //return new
505 * FramesReader(getMultiReaderStrategy()).readFrames(thread); return null; //} catch (IOException e) { //
506 * PHPDebugCorePlugin.log(e); // return null; //}
510 public void closeSocket() throws IOException {
511 if (socket != null) {
516 public void closeServerSocket() throws IOException {
517 if (server != null) {
522 public int getPort() {
530 class PHPLoop extends Thread {
531 private boolean shouldStop;
535 this.setName ("PHPDebuggerLoop");
541 public synchronized void setShouldStop () {
542 shouldStop = true; // The run loop should stop
545 // If the loop thread is blocked on the server socket,
546 // forcibly unblock it to avoid leaking the thread,
547 // the socket and the port
548 closeServerSocket ();
549 } catch (IOException x) {
550 // Log this as a warning?
551 PHPDebugCorePlugin.log (x);
558 public synchronized void notifyWait () {
570 long interval = 200; // Wait 200 ms maximum for a DBG response
571 boolean newconnect = false; //
572 Socket newSocket = null;
573 PHPStackFrame[] StackList;
574 PHPDBGInterface newDBGInt;
576 // synchronized (this) {
580 PHPMainThread = new PHPThread (getDebugTarget (), getPort ());
581 PHPMainThread.setName ("Thread [main]");
584 // while ((getDebugTarget() == null) && (timeout < 100)) {
588 // Be sure debug target is set
589 // PHPMainThread.setDebugTarget(getDebugTarget());
591 getDebugTarget ().addThread (PHPMainThread);
593 //System.out.println("Waiting for breakpoints.");
595 while (!shouldStop) { // As long as nobody will stop us
596 newconnect = true; // The first time
599 newSocket = server.accept(); // Waits until DBG want to connect
600 //System.out.println("Accepted! : " + socket.toString());
601 } catch (SocketTimeoutException e) {
602 newconnect = false; // No one wants to connect (connection already done)
603 } catch (IOException e) {
604 PHPDebugCorePlugin.log(e);
608 if (newconnect) { // Is it just after a new connection
609 if (DBGInt == null) { // Do we have a DBG interface?
610 server.setSoTimeout(1); // ???
613 newDBGInt = new PHPDBGInterface (getReader (newSocket), // Create a new interface
614 newSocket.getOutputStream (),
616 newDBGInt.waitResponse (1000); // Wait for the initial DBG response
617 newDBGInt.flushAllPackets (); // Read and process the DBG response
619 // Check version and session ID
620 if ((DBGInt == null) || // If we have no interface
621 (DBGInt.getSID () == newDBGInt.getSID ())) {// or the new session ID is different to the old one
622 DBGInt = newDBGInt; // Set the new interface as current one
627 catch (IOException e) {
628 PHPDebugCorePlugin.log (e);
634 DBGInt.continueExecution (); // Notify DBG that PHP should continue
637 newDBGInt.continueExecution (); // Notify DBG that PHP should continue
642 if (DBGInt.waitResponse (interval)) { // Wait for a DBG response (200 ms)
643 DBGInt.flushAllPackets (); // If we got something, read and process it
645 if (DBGInt.BPUnderHit != 0) { // ???
646 StackList = DBGInt.getStackList (); // Get the stack list from DBGInterface
648 if (StackList.length > 0) { // If there is something in stack list
649 for (i = 0; i < StackList.length; i++) { // For all stack list
650 StackList[i].setThread (PHPMainThread); // Set the PHPTread for all PHPStackFrames
652 if (DBGInt.getModByNo (StackList[i].getModNo ()).equals ("")) {
653 DBGInt.getSourceTree ();
656 StackList[i].setFile (DBGInt.getModByNo (StackList[i].getModNo ()));
659 PHPMainThread.setStackFrames (StackList);
662 PHPMainThread.suspend (); // Fire debug event
664 synchronized (this) {
671 if (PHPMainThread.isTerminated ()) {
674 break; // Go for terminating the thread
677 if (PHPMainThread.isTerminated () ||
678 getDebugTarget ().getProcess ().isTerminated ()) {
681 break; // Go for terminating the thread
685 } catch (Exception ex) {
686 PHPDebugCorePlugin.log (ex);
687 System.out.println (ex);
690 getDebugTarget ().terminate ();
692 closeServerSocket ();
693 } catch (IOException e) {
694 PHPDebugCorePlugin.log (e);
699 //System.out.println("Socket loop finished.");