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 * Give back a buffered input stream for the socket which is
180 * linked with this proxy
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 (),
188 return reader; // Return the buffered input stream
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
200 return null; // Without a socket we can't create a input stream
206 * @return The output stream for this proxy's socket
208 public OutputStream getOutputStream () throws IOException {
209 return this.getSocket ().getOutputStream ();
215 protected void setBreakPoints () throws IOException, CoreException {
216 IBreakpoint[] breakpoints = DebugPlugin.getDefault ().getBreakpointManager ().getBreakpoints ();
218 for (int i = 0; i < breakpoints.length; i++) {
219 if (breakpoints[i].isEnabled ()) {
220 addBreakpoint (breakpoints[i]);
228 private String MapPath (PHPLineBreakpoint phpLBP) {
236 filename = phpLBP.getMarker().getResource().getProjectRelativePath();
237 filename = remoteSourcePath.append (filename);
239 filename = phpLBP.getMarker().getResource().getLocation();
242 String path = filename.toOSString();
244 if ((pathmap != null) && remote) {
245 java.util.Iterator i = pathmap.keySet().iterator();
247 while (i.hasNext()) {
248 String k = (String) i.next();
249 if (path.startsWith(k)) {
250 path = pathmap.get(k) + path.substring(k.length());
256 if (remoteSourcePath.isEmpty ()) {
257 if ((pathmap != null) && remote) {
258 java.util.Iterator iterator = pathmap.keySet().iterator();
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
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 ();
271 if (path.substring (0, 1).equals ("/")) {
272 path = path.replace ('\\', '/');
275 path = path.replace ('/', '\\');
284 if (pathtranslation && remote) {
285 if (remoteSourcePath.toString ().substring (0, 1).equals ("/")) {
286 path = path.replace ('\\', '/');
289 path = path.replace ('/', '\\');
300 public void addBreakpoint (IBreakpoint breakpoint) {
301 if (DBGInt == null) {
308 PHPLineBreakpoint phpLBP;
310 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier()) {
311 phpLBP = (PHPLineBreakpoint) breakpoint;
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 ());
321 bpNo = DBGInt.addBreakpoint (MapPath(phpLBP),
322 phpLBP.getLineNumber(),
323 phpLBP.getHitCount(),
327 phpLBP.setDBGBpNo(bpNo);
329 } catch (IOException e) {
330 PHPDebugCorePlugin.log(e);
332 } catch (CoreException e) {
333 PHPDebugCorePlugin.log(e);
341 public void removeBreakpoint (IBreakpoint breakpoint) {
342 if (DBGInt == null) {
347 PHPLineBreakpoint phpLBP;
349 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier ()) {
350 phpLBP = (PHPLineBreakpoint) breakpoint;
352 // bpNo= DBGInt.addBreakpoint(filename.toOSString(), phpLBP.getLineNumber());
354 DBGInt.removeBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber(), phpLBP.getDBGBpNo());
356 } catch (IOException e) {
357 PHPDebugCorePlugin.log (e);
359 } catch (CoreException e) {
360 PHPDebugCorePlugin.log (e);
368 public void phpLoopNotify () {
369 phpLoop.notifyWait ();
375 public void startPHPLoop () {
376 phpLoop = new PHPLoop (); // Create a DBG communication loop object
378 phpLoop.start (); // And start the communication loop
384 public void resume () {
386 DBGInt.continueExecution();
387 phpLoop.notifyWait();
388 } catch (IOException e) {
389 PHPeclipsePlugin.log("Debugging session ended.", e);
397 public void pause () {
399 if (null != DBGInt) {
400 DBGInt.pauseExecution();
403 // TODO Make sure the Suspend action is grayed out
404 // when DBGInt is null
406 } catch (IOException e) {
407 PHPDebugCorePlugin.log (e);
415 protected PHPDebugTarget getDebugTarget() {
423 public void setDebugTarget (PHPDebugTarget debugTarget) {
424 this.debugTarget = debugTarget;
425 debugTarget.setPHPDBGProxy(this);
429 * This method is called by a stackframe.
430 * It reads the variables from PHP via DBG
432 * @param frame The stackframe which wants the variables.
433 * @return The list of variables for this stackframe.
435 public Vector readVariables (PHPStackFrame frame) {
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 ());
453 public PHPVariable[] eval (PHPStackFrame frame, String evalString) {
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());
466 public void readStepOverEnd (PHPStackFrame stackFrame) {
469 phpLoop.notifyWait();
470 } catch (Exception e) {
471 PHPDebugCorePlugin.log(e);
475 public void readStepReturnEnd (PHPStackFrame stackFrame) {
478 phpLoop.notifyWait();
479 } catch (Exception e) {
480 PHPDebugCorePlugin.log(e);
484 public void readStepIntoEnd (PHPStackFrame stackFrame) {
487 phpLoop.notifyWait();
488 } catch (Exception e) {
489 PHPDebugCorePlugin.log(e);
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; //}
500 public void closeSocket() throws IOException {
501 if (socket != null) {
506 public void closeServerSocket() throws IOException {
507 if (server != null) {
512 public int getPort() {
520 class PHPLoop extends Thread {
521 private boolean shouldStop;
525 this.setName ("PHPDebuggerLoop");
531 public synchronized void setShouldStop () {
532 shouldStop = true; // The run loop should stop
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);
548 public synchronized void notifyWait () {
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;
566 // synchronized (this) {
570 PHPMainThread = new PHPThread (getDebugTarget (), getPort ());
571 PHPMainThread.setName ("Thread [main]");
574 // while ((getDebugTarget() == null) && (timeout < 100)) {
578 // Be sure debug target is set
579 // PHPMainThread.setDebugTarget(getDebugTarget());
581 getDebugTarget ().addThread (PHPMainThread);
583 //System.out.println("Waiting for breakpoints.");
585 while (!shouldStop) { // As long as nobody will stop us
586 newconnect = true; // The first time
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);
598 if (newconnect) { // Is it just after a new connection
599 if (DBGInt == null) { // Do we have a DBG interface?
600 server.setSoTimeout(1); // ???
603 newDBGInt = new PHPDBGInterface (getReader (newSocket), // Create a new interface
604 newSocket.getOutputStream (),
606 newDBGInt.waitResponse (1000); // Wait for the initial DBG response
607 newDBGInt.flushAllPackets (); // Read and process the DBG response
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
617 catch (IOException e) {
618 PHPDebugCorePlugin.log (e);
624 DBGInt.continueExecution (); // Notify DBG that PHP should continue
627 newDBGInt.continueExecution (); // Notify DBG that PHP should continue
632 if (DBGInt.waitResponse (interval)) { // Wait for a DBG response (200 ms)
633 DBGInt.flushAllPackets (); // If we got something, read and process it
635 if (DBGInt.BPUnderHit != 0) { // ???
636 StackList = DBGInt.getStackList (); // Get the stack list from DBGInterface
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
642 if (DBGInt.getModByNo (StackList[i].getModNo ()).equals ("")) {
643 DBGInt.getSourceTree ();
646 StackList[i].setFile (DBGInt.getModByNo (StackList[i].getModNo ()));
649 PHPMainThread.setStackFrames (StackList);
652 PHPMainThread.suspend (); // Fire debug event
654 synchronized (this) {
661 if (PHPMainThread.isTerminated ()) {
664 break; // Go for terminating the thread
667 if (PHPMainThread.isTerminated () ||
668 getDebugTarget ().getProcess ().isTerminated ()) {
671 break; // Go for terminating the thread
675 } catch (Exception ex) {
676 PHPDebugCorePlugin.log (ex);
677 System.out.println (ex);
680 getDebugTarget ().terminate ();
682 closeServerSocket ();
683 } catch (IOException e) {
684 PHPDebugCorePlugin.log (e);
689 //System.out.println("Socket loop finished.");