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 ();
101 * TODO Is this method called from anywhere?
103 * Returns a already created server socket, or
104 * creates a server socket if none exists, and
105 * returns the newly created one.
107 * @return A server socket
109 protected ServerSocket getServerSocket () throws IOException {
110 if (server == null) { // Do we have already a server socket
111 createServerSocket (); // No, then create one
114 return server; // Return the server socket
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?
123 protected void createServerSocket () {
124 port = SocketUtil.findUnusedLocalPort ("localhost", 10001, 10101); // Get the first free port in the range from 10001 to 10101
127 if (port == -1) { // Did we get a free port?
128 PHPDebugCorePlugin.log (5, "Cannot find free port!!!!"); // No, output a error message
130 return; // And return
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);
137 } catch (IOException e) {
139 PHPDebugCorePlugin.log (e);
147 public Socket getSocket () throws IOException {
148 return socket; // Return the socket
152 * Set the DBG interface which is linked to this proxy
154 * @paran DBGInt The DGB interface which is linked with this proxy
156 protected void setDBGInterface (PHPDBGInterface DBGInt) {
157 this.DBGInt = DBGInt;
161 * Give back a buffered input stream for the socket which is
162 * linked with this proxy
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 (),
170 return reader; // Return the buffered input stream
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
182 return null; // Without a socket we can't create a input stream
188 * @return The output stream for this proxy's socket
190 public OutputStream getOutputStream () throws IOException {
191 return this.getSocket ().getOutputStream ();
197 protected void setBreakPoints () throws IOException, CoreException {
198 IBreakpoint[] breakpoints = DebugPlugin.getDefault ().getBreakpointManager ().getBreakpoints ();
200 for (int i = 0; i < breakpoints.length; i++) {
201 if (breakpoints[i].isEnabled ()) {
202 addBreakpoint (breakpoints[i]);
210 private String MapPath (PHPLineBreakpoint phpLBP) {
218 filename = phpLBP.getMarker().getResource().getProjectRelativePath();
219 filename = remoteSourcePath.append (filename);
221 filename = phpLBP.getMarker().getResource().getLocation();
224 String path = filename.toOSString();
226 if ((pathmap != null) && remote) {
227 java.util.Iterator i = pathmap.keySet().iterator();
229 while (i.hasNext()) {
230 String k = (String) i.next();
231 if (path.startsWith(k)) {
232 path = pathmap.get(k) + path.substring(k.length());
238 if (remoteSourcePath.isEmpty ()) {
239 if ((pathmap != null) && remote) {
240 java.util.Iterator iterator = pathmap.keySet().iterator();
242 while (iterator.hasNext ()) {
243 local = (String) iterator.next (); // Get the local/client side path of the mapping
244 remotePath = new Path ((String) pathmap.get (local)); // Get the remote/server side path of the mapping
245 localPath = new Path (local); // Get the remote/server side path of the mapping
247 if (localPath.isPrefixOf (filename)) { // Starts the remote/server side file path with the remote/server side mapping path
248 // dann prefix abhängen und den remote path davorhägen
249 newpath = filename.removeFirstSegments (localPath.matchingFirstSegments (filename));
250 newpath = remotePath.append (newpath);
251 path = newpath.toString ();
253 if (path.substring (0, 1).equals ("/")) {
254 path = path.replace ('\\', '/');
257 path = path.replace ('/', '\\');
266 if (pathtranslation && remote) {
267 if (remoteSourcePath.toString ().substring (0, 1).equals ("/")) {
268 path = path.replace ('\\', '/');
271 path = path.replace ('/', '\\');
282 public void addBreakpoint (IBreakpoint breakpoint) {
283 if (DBGInt == null) {
290 PHPLineBreakpoint phpLBP;
292 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier()) {
293 phpLBP = (PHPLineBreakpoint) breakpoint;
295 // bpNo= DBGInt.addBreakpoint(phpLBP.getMarker().getResource().getLocation().toOSString(), phpLBP.getLineNumber());
297 bpNo = DBGInt.addBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber());
298 phpLBP.setDBGBpNo(bpNo);
300 } catch (IOException e) {
301 PHPDebugCorePlugin.log(e);
303 } catch (CoreException e) {
304 PHPDebugCorePlugin.log(e);
312 public void removeBreakpoint (IBreakpoint breakpoint) {
313 if (DBGInt == null) {
318 PHPLineBreakpoint phpLBP;
320 if (breakpoint.getModelIdentifier() == PHPDebugCorePlugin.getUniqueIdentifier ()) {
321 phpLBP = (PHPLineBreakpoint) breakpoint;
323 // bpNo= DBGInt.addBreakpoint(filename.toOSString(), phpLBP.getLineNumber());
325 DBGInt.removeBreakpoint(MapPath(phpLBP), phpLBP.getLineNumber(), phpLBP.getDBGBpNo());
327 } catch (IOException e) {
328 PHPDebugCorePlugin.log (e);
330 } catch (CoreException e) {
331 PHPDebugCorePlugin.log (e);
339 public void phpLoopNotify () {
340 phpLoop.notifyWait ();
346 public void startPHPLoop () {
347 phpLoop = new PHPLoop (); // Create a DBG communication loop object
349 phpLoop.start (); // And start the communication loop
355 public void resume () {
357 DBGInt.continueExecution();
358 phpLoop.notifyWait();
359 } catch (IOException e) {
360 PHPeclipsePlugin.log("Debugging session ended.", e);
368 public void pause () {
370 if (null != DBGInt) {
371 DBGInt.pauseExecution();
374 // TODO Make sure the Suspend action is grayed out
375 // when DBGInt is null
377 } catch (IOException e) {
378 PHPDebugCorePlugin.log (e);
386 protected PHPDebugTarget getDebugTarget() {
394 public void setDebugTarget (PHPDebugTarget debugTarget) {
395 this.debugTarget = debugTarget;
396 debugTarget.setPHPDBGProxy(this);
400 * This method is called by a stackframe.
401 * It reads the variables from PHP via DBG
403 * @param frame The stackframe which wants the variables.
404 * @return The list of variables for this stackframe.
406 public Vector readVariables (PHPStackFrame frame) {
408 return DBGInt.getVariables (frame); // Get the variables from DBG interface
409 } catch (IOException ioex) {
410 ioex.printStackTrace ();
411 throw new RuntimeException (ioex.getMessage ());
412 } catch (DebugException ex) {
413 ex.printStackTrace ();
414 throw new RuntimeException (ex.getMessage ());
424 public PHPVariable[] eval (PHPStackFrame frame, String evalString) {
426 return DBGInt.evalBlock (frame, evalString);
427 //return DBGInt.getVariables(frame);
428 } catch (IOException ioex) {
429 ioex.printStackTrace();
430 throw new RuntimeException(ioex.getMessage());
431 } catch (DebugException ex) {
432 ex.printStackTrace();
433 throw new RuntimeException(ex.getMessage());
437 public void readStepOverEnd (PHPStackFrame stackFrame) {
440 phpLoop.notifyWait();
441 } catch (Exception e) {
442 PHPDebugCorePlugin.log(e);
446 public void readStepReturnEnd (PHPStackFrame stackFrame) {
449 phpLoop.notifyWait();
450 } catch (Exception e) {
451 PHPDebugCorePlugin.log(e);
455 public void readStepIntoEnd (PHPStackFrame stackFrame) {
458 phpLoop.notifyWait();
459 } catch (Exception e) {
460 PHPDebugCorePlugin.log(e);
465 * public PHPStackFrame[] readFrames(PHPThread thread) { //try { //this.println("th " + thread.getId() + " ; f "); //return new
466 * FramesReader(getMultiReaderStrategy()).readFrames(thread); return null; //} catch (IOException e) { //
467 * PHPDebugCorePlugin.log(e); // return null; //}
471 public void closeSocket() throws IOException {
472 if (socket != null) {
477 public void closeServerSocket() throws IOException {
478 if (server != null) {
483 public int getPort() {
491 class PHPLoop extends Thread {
492 private boolean shouldStop;
496 this.setName ("PHPDebuggerLoop");
502 public synchronized void setShouldStop () {
503 shouldStop = true; // The run loop should stop
506 // If the loop thread is blocked on the server socket,
507 // forcibly unblock it to avoid leaking the thread,
508 // the socket and the port
509 closeServerSocket ();
510 } catch (IOException x) {
511 // Log this as a warning?
512 PHPDebugCorePlugin.log (x);
519 public synchronized void notifyWait () {
531 long interval = 200; // Wait 200 ms maximum for a DBG response
532 boolean newconnect = false; //
533 Socket newSocket = null;
534 PHPStackFrame[] StackList;
535 PHPDBGInterface newDBGInt;
537 // synchronized (this) {
541 PHPMainThread = new PHPThread (getDebugTarget (), getPort ());
542 PHPMainThread.setName ("Thread [main]");
545 // while ((getDebugTarget() == null) && (timeout < 100)) {
549 // Be sure debug target is set
550 // PHPMainThread.setDebugTarget(getDebugTarget());
552 getDebugTarget ().addThread (PHPMainThread);
554 //System.out.println("Waiting for breakpoints.");
556 while (!shouldStop) { // As long as nobody will stop us
557 newconnect = true; // The first time
560 newSocket = server.accept(); // Waits until DBG want to connect
561 //System.out.println("Accepted! : " + socket.toString());
562 } catch (SocketTimeoutException e) {
563 newconnect = false; // No one wants to connect (connection already done)
564 } catch (IOException e) {
565 PHPDebugCorePlugin.log(e);
569 if (newconnect) { // Is it just after a new connection
570 if (DBGInt == null) { // Do we have a DBG interface?
571 server.setSoTimeout(1); // ???
574 newDBGInt = new PHPDBGInterface (getReader (newSocket), // Create a new interface
575 newSocket.getOutputStream (),
577 newDBGInt.waitResponse (1000); // Wait for the initial DBG response
578 newDBGInt.flushAllPackets (); // Read and process the DBG response
580 // Check version and session ID
581 if ((DBGInt == null) || // If we have no interface
582 (DBGInt.getSID () == newDBGInt.getSID ())) {// or the new session ID is different to the old one
583 DBGInt = newDBGInt; // Set the new interface as current one
588 catch (IOException e) {
589 PHPDebugCorePlugin.log (e);
595 DBGInt.continueExecution (); // Notify DBG that PHP should continue
598 newDBGInt.continueExecution (); // Notify DBG that PHP should continue
603 if (DBGInt.waitResponse (interval)) { // Wait for a DBG response (200 ms)
604 DBGInt.flushAllPackets (); // If we got something, read and process it
606 if (DBGInt.BPUnderHit != 0) { // ???
607 StackList = DBGInt.getStackList (); // Get the stack list from DBGInterface
609 if (StackList.length > 0) { // If there is something in stack list
610 for (i = 0; i < StackList.length; i++) { // For all stack list
611 StackList[i].setThread (PHPMainThread); // Set the PHPTread for all PHPStackFrames
613 if (DBGInt.getModByNo (StackList[i].getModNo ()).equals ("")) {
614 DBGInt.getSourceTree ();
617 StackList[i].setFile (DBGInt.getModByNo (StackList[i].getModNo ()));
620 PHPMainThread.setStackFrames (StackList);
623 PHPMainThread.suspend (); // Fire debug event
625 synchronized (this) {
632 if (PHPMainThread.isTerminated ()) {
635 break; // Go for terminating the thread
638 if (PHPMainThread.isTerminated () ||
639 getDebugTarget ().getProcess ().isTerminated ()) {
642 break; // Go for terminating the thread
646 } catch (Exception ex) {
647 PHPDebugCorePlugin.log (ex);
648 System.out.println (ex);
651 getDebugTarget ().terminate ();
653 closeServerSocket ();
654 } catch (IOException e) {
655 PHPDebugCorePlugin.log (e);
660 //System.out.println("Socket loop finished.");