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.util.Iterator;
  38 import java.util.List;
  39 import java.util.Map;
  40 
  41 import com.sun.jdi.Bootstrap;
  42 import com.sun.jdi.Field;
  43 import com.sun.jdi.ReferenceType;
  44 import com.sun.jdi.VirtualMachine;
  45 import com.sun.jdi.connect.Connector;
  46 import com.sun.jdi.connect.IllegalConnectorArgumentsException;
  47 import com.sun.jdi.connect.LaunchingConnector;
  48 import com.sun.jdi.connect.VMStartException;
  49 import com.sun.jdi.event.ClassPrepareEvent;
  50 import com.sun.jdi.event.Event;
  51 import com.sun.jdi.event.EventQueue;
  52 import com.sun.jdi.event.EventSet;
  53 import com.sun.jdi.event.ModificationWatchpointEvent;
  54 import com.sun.jdi.event.VMDeathEvent;
  55 import com.sun.jdi.event.VMStartEvent;
  56 import com.sun.jdi.event.VMDisconnectEvent;
  57 import com.sun.jdi.request.ClassPrepareRequest;
  58 import com.sun.jdi.request.EventRequest;
  59 import com.sun.jdi.request.EventRequestManager;
  60 import com.sun.jdi.request.ModificationWatchpointRequest;
  61 
  62 public class FieldMonitor {
  63 
  64   public static final String CLASS_NAME = "TestPostFieldModification";
  65   public static final String FIELD_NAME = "value";
  66   public static final String ARGUMENTS = "-Xshare:off -XX:+PrintGC";
  67 
  68   public static void main(String[] args)
  69       throws IOException, InterruptedException {
  70 
  71     //VirtualMachine vm = launchTarget(sb.toString());
  72     VirtualMachine vm = launchTarget(CLASS_NAME);
  73 
  74     System.out.println("Vm launched");
  75 
  76     // process events
  77     EventQueue eventQueue = vm.eventQueue();
  78     // resume the vm
  79 
  80     Process process = vm.process();
  81 
  82 
  83     // Copy target's output and error to our output and error.
  84     Thread outThread = new StreamRedirectThread("out reader", process.getInputStream());
  85     Thread errThread = new StreamRedirectThread("error reader", process.getErrorStream());
  86 
  87     errThread.start();
  88     outThread.start();
  89 
  90     boolean connected = true;
  91     boolean watched = false;
  92     while (connected) {
  93       EventSet eventSet = eventQueue.remove();
  94       for (Event event : eventSet) {
  95         System.out.println("FieldMonitor-main receives: "+event);
  96         if (event instanceof VMStartEvent) {
  97           addClassWatch(vm);
  98         } else if (event instanceof VMDeathEvent
  99             || event instanceof VMDisconnectEvent) {
 100           // exit
 101           connected = false;
 102         } else if (event instanceof ClassPrepareEvent) {
 103           // watch field on loaded class
 104           System.out.println("ClassPrepareEvent");
 105           ClassPrepareEvent classPrepEvent = (ClassPrepareEvent) event;
 106           ReferenceType refType = classPrepEvent
 107               .referenceType();
 108           addFieldWatch(vm, refType);
 109         } else if (event instanceof ModificationWatchpointEvent) {
 110           watched = true;
 111           System.out.println("sleep for 500 ms");
 112           Thread.sleep(500);
 113           System.out.println("resume...");
 114 
 115           ModificationWatchpointEvent modEvent = (ModificationWatchpointEvent) event;
 116           System.out.println("old="
 117               + modEvent.valueCurrent());
 118           System.out.println("new=" + modEvent.valueToBe());
 119           System.out.println();
 120         }
 121       }
 122       eventSet.resume();
 123     }
 124     // Shutdown begins when event thread terminates
 125     try {
 126         errThread.join(); // Make sure output is forwarded
 127         outThread.join();
 128     } catch (InterruptedException exc) {
 129         // we don't interrupt
 130     }
 131     
 132     if (!watched) {
 133         throw new Error("Did not receive ModificationWatchpointEvent!");
 134     }
 135   }
 136 
 137   /**
 138    * Find a com.sun.jdi.CommandLineLaunch connector
 139    */
 140   static LaunchingConnector findLaunchingConnector() {
 141     List <Connector> connectors = Bootstrap.virtualMachineManager().allConnectors();
 142     Iterator <Connector> iter = connectors.iterator();
 143     while (iter.hasNext()) {
 144       Connector connector = iter.next();
 145       if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
 146         return (LaunchingConnector)connector;
 147       }
 148     }
 149     throw new Error("No launching connector");
 150   }
 151   /**
 152    * Return the launching connector's arguments.
 153    */
 154  static Map <String,Connector.Argument> connectorArguments(LaunchingConnector connector, String mainArgs) {
 155       Map<String,Connector.Argument> arguments = connector.defaultArguments();
 156       for (String key : arguments.keySet()) {
 157         System.out.println(key);
 158       }
 159 
 160       Connector.Argument mainArg = (Connector.Argument)arguments.get("main");
 161       if (mainArg == null) {
 162           throw new Error("Bad launching connector");
 163       }
 164       mainArg.setValue(mainArgs);
 165 
 166       Connector.Argument optionsArg = (Connector.Argument)arguments.get("options");
 167       if (optionsArg == null) {
 168         throw new Error("Bad launching connector");
 169       }
 170       optionsArg.setValue(ARGUMENTS);
 171       return arguments;
 172   }
 173 
 174  static VirtualMachine launchTarget(String mainArgs) {
 175     LaunchingConnector connector = findLaunchingConnector();
 176     Map  arguments = connectorArguments(connector, mainArgs);
 177     try {
 178         return (VirtualMachine) connector.launch(arguments);
 179     } catch (IOException exc) {
 180         throw new Error("Unable to launch target VM: " + exc);
 181     } catch (IllegalConnectorArgumentsException exc) {
 182         throw new Error("Internal error: " + exc);
 183     } catch (VMStartException exc) {
 184         throw new Error("Target VM failed to initialize: " +
 185                         exc.getMessage());
 186     }
 187 }
 188 
 189 
 190   private static void addClassWatch(VirtualMachine vm) {
 191     EventRequestManager erm = vm.eventRequestManager();
 192     ClassPrepareRequest classPrepareRequest = erm
 193         .createClassPrepareRequest();
 194     classPrepareRequest.addClassFilter(CLASS_NAME);
 195     classPrepareRequest.setEnabled(true);
 196   }
 197 
 198 
 199   private static void addFieldWatch(VirtualMachine vm,
 200       ReferenceType refType) {
 201     EventRequestManager erm = vm.eventRequestManager();
 202     Field field = refType.fieldByName(FIELD_NAME);
 203     ModificationWatchpointRequest modificationWatchpointRequest = erm
 204         .createModificationWatchpointRequest(field);
 205     modificationWatchpointRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
 206     modificationWatchpointRequest.setEnabled(true);
 207   }
 208 }
 209 
 210 class StreamRedirectThread extends Thread {
 211 
 212   private final BufferedReader in;
 213 
 214   private static final int BUFFER_SIZE = 2048;
 215 
 216   /**
 217    * Set up for copy.
 218    * @param name  Name of the thread
 219    * @param in    Stream to copy from
 220    * @param out   Stream to copy to
 221    */
 222   StreamRedirectThread(String name, InputStream in) {
 223     super(name);
 224     this.in = new BufferedReader(new InputStreamReader(in));
 225   }
 226 
 227   /**
 228    * Copy.
 229    */
 230   public void run() {
 231     try {
 232       String line;
 233         while ((line = in.readLine ()) != null) {
 234           System.out.println ("testvm: " + line);
 235       }
 236      System.out.flush();
 237     } catch(IOException exc) {
 238       System.err.println("Child I/O Transfer - " + exc);
 239     }
 240   }
 241 }