1 /*
   2  * Copyright 2012 SAP AG.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test FieldMonitor.java
  26  * @bug 7158988
  27  * @key regression
  28  * @summary verify jvm does not crash while debugging
  29  * @run compile TestPostFieldModification.java
  30  * @run main/othervm FieldMonitor
  31  * @author axel.siebenborn@sap.com
  32  */
  33 import java.io.BufferedReader;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.InputStreamReader;
  37 import java.io.OutputStream;
  38 import java.io.OutputStreamWriter;
  39 import java.io.Reader;
  40 import java.io.Writer;
  41 import java.util.Iterator;
  42 import java.util.List;
  43 import java.util.Map;

  44 
  45 import com.sun.jdi.Bootstrap;
  46 import com.sun.jdi.Field;
  47 import com.sun.jdi.ReferenceType;
  48 import com.sun.jdi.VirtualMachine;
  49 import com.sun.jdi.connect.Connector;
  50 import com.sun.jdi.connect.IllegalConnectorArgumentsException;
  51 import com.sun.jdi.connect.LaunchingConnector;
  52 import com.sun.jdi.connect.VMStartException;
  53 import com.sun.jdi.event.ClassPrepareEvent;

  54 import com.sun.jdi.event.Event;
  55 import com.sun.jdi.event.EventQueue;
  56 import com.sun.jdi.event.EventSet;
  57 import com.sun.jdi.event.ModificationWatchpointEvent;
  58 import com.sun.jdi.event.VMDeathEvent;
  59 import com.sun.jdi.event.VMDisconnectEvent;
  60 import com.sun.jdi.request.ClassPrepareRequest;
  61 import com.sun.jdi.request.EventRequest;
  62 import com.sun.jdi.request.EventRequestManager;
  63 import com.sun.jdi.request.ModificationWatchpointRequest;
  64 
  65 public class FieldMonitor {
  66 
  67   public static final String CLASS_NAME = "TestPostFieldModification";
  68   public static final String FIELD_NAME = "value";
  69   public static final String ARGUMENTS = "-Xshare:off -XX:+PrintGC";
  70 
  71   public static void main(String[] args)
  72       throws IOException, InterruptedException {
  73 
  74     StringBuffer sb = new StringBuffer();

  75 
  76     for (int i=0; i < args.length; i++) {
  77         sb.append(' ');
  78         sb.append(args[i]);










  79     }
  80     //VirtualMachine vm = launchTarget(sb.toString());
  81     VirtualMachine vm = launchTarget(CLASS_NAME);
  82 
  83     System.out.println("Vm launched");
  84     // set watch field on already loaded classes
  85     List<ReferenceType> referenceTypes = vm
  86         .classesByName(CLASS_NAME);
  87     for (ReferenceType refType : referenceTypes) {
  88       addFieldWatch(vm, refType);
  89     }
  90     // watch for loaded classes
  91     addClassWatch(vm);
  92 
  93     // process events
  94     EventQueue eventQueue = vm.eventQueue();
  95     // resume the vm
  96 
  97     Process process = vm.process();
  98 
  99 
 100     // Copy target's output and error to our output and error.
 101     Thread outThread = new StreamRedirectThread("out reader", process.getInputStream());
 102     Thread errThread = new StreamRedirectThread("error reader", process.getErrorStream());
 103 

 104     errThread.start();
 105     outThread.start();
 106 
 107 
 108     vm.resume();
 109     boolean connected = true;
 110     while (connected) {
 111       EventSet eventSet = eventQueue.remove();
 112       for (Event event : eventSet) {
 113         if (event instanceof VMDeathEvent
 114             || event instanceof VMDisconnectEvent) {
 115           // exit
 116           connected = false;
 117         } else if (event instanceof ClassPrepareEvent) {
 118           // watch field on loaded class
 119           System.out.println("ClassPrepareEvent");
 120           ClassPrepareEvent classPrepEvent = (ClassPrepareEvent) event;
 121           ReferenceType refType = classPrepEvent
 122               .referenceType();
 123           addFieldWatch(vm, refType);







 124         } else if (event instanceof ModificationWatchpointEvent) {
 125           System.out.println("sleep for 500 ms");
 126           Thread.sleep(500);
 127           System.out.println("resume...");
 128 
 129           ModificationWatchpointEvent modEvent = (ModificationWatchpointEvent) event;
 130           System.out.println("old="
 131               + modEvent.valueCurrent());
 132           System.out.println("new=" + modEvent.valueToBe());
 133           System.out.println();
 134         }
 135       }
 136       eventSet.resume();
 137     }
 138     // Shutdown begins when event thread terminates
 139     try {
 140         errThread.join(); // Make sure output is forwarded
 141         outThread.join();
 142     } catch (InterruptedException exc) {
 143         // we don't interrupt
 144     }
 145   }
 146 
 147   /**
 148    * Find a com.sun.jdi.CommandLineLaunch connector
 149    */
 150   static LaunchingConnector findLaunchingConnector() {
 151     List <Connector> connectors = Bootstrap.virtualMachineManager().allConnectors();
 152     Iterator <Connector> iter = connectors.iterator();
 153     while (iter.hasNext()) {
 154       Connector connector = iter.next();
 155       if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
 156         return (LaunchingConnector)connector;
 157       }
 158     }
 159     throw new Error("No launching connector");
 160   }
 161   /**
 162    * Return the launching connector's arguments.
 163    */
 164  static Map <String,Connector.Argument> connectorArguments(LaunchingConnector connector, String mainArgs) {
 165       Map<String,Connector.Argument> arguments = connector.defaultArguments();
 166       for (String key : arguments.keySet()) {
 167         System.out.println(key);
 168       }
 169 
 170       Connector.Argument mainArg = (Connector.Argument)arguments.get("main");
 171       if (mainArg == null) {
 172           throw new Error("Bad launching connector");
 173       }
 174       mainArg.setValue(mainArgs);
 175 
 176       Connector.Argument optionsArg = (Connector.Argument)arguments.get("options");
 177       if (optionsArg == null) {
 178         throw new Error("Bad launching connector");
 179       }
 180       optionsArg.setValue(ARGUMENTS);
 181       return arguments;
 182   }
 183 
 184  static VirtualMachine launchTarget(String mainArgs) {
 185     LaunchingConnector connector = findLaunchingConnector();
 186     Map  arguments = connectorArguments(connector, mainArgs);
 187     try {
 188         return (VirtualMachine) connector.launch(arguments);
 189     } catch (IOException exc) {
 190         throw new Error("Unable to launch target VM: " + exc);
 191     } catch (IllegalConnectorArgumentsException exc) {
 192         throw new Error("Internal error: " + exc);
 193     } catch (VMStartException exc) {
 194         throw new Error("Target VM failed to initialize: " +
 195                         exc.getMessage());
 196     }
 197 }
 198 
 199 
 200   private static void addClassWatch(VirtualMachine vm) {
 201     EventRequestManager erm = vm.eventRequestManager();
 202     ClassPrepareRequest classPrepareRequest = erm
 203         .createClassPrepareRequest();
 204     classPrepareRequest.addClassFilter(CLASS_NAME);
 205     classPrepareRequest.setEnabled(true);
 206   }
 207 
 208 
 209   private static void addFieldWatch(VirtualMachine vm,
 210       ReferenceType refType) {
 211     EventRequestManager erm = vm.eventRequestManager();
 212     Field field = refType.fieldByName(FIELD_NAME);
 213     ModificationWatchpointRequest modificationWatchpointRequest = erm
 214         .createModificationWatchpointRequest(field);
 215     modificationWatchpointRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
 216     modificationWatchpointRequest.setEnabled(true);
 217   }
 218 }
 219 
 220 class StreamRedirectThread extends Thread {
 221 
 222   private final BufferedReader in;
 223 
 224   private static final int BUFFER_SIZE = 2048;
 225 
 226   /**
 227    * Set up for copy.
 228    * @param name  Name of the thread
 229    * @param in    Stream to copy from
 230    * @param out   Stream to copy to
 231    */
 232   StreamRedirectThread(String name, InputStream in) {
 233     super(name);
 234     this.in = new BufferedReader(new InputStreamReader(in));
 235   }
 236 
 237   /**
 238    * Copy.
 239    */
 240   public void run() {
 241     try {
 242       String line;
 243         while ((line = in.readLine ()) != null) {
 244           System.out.println ("testvm: " + line);
 245       }
 246      System.out.flush();
 247     } catch(IOException exc) {
 248       System.err.println("Child I/O Transfer - " + exc);
 249     }
 250   }
 251 }
--- EOF ---