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 import java.io.PrintWriter;
  41 
  42 import com.sun.jdi.Bootstrap;
  43 import com.sun.jdi.Field;
  44 import com.sun.jdi.ReferenceType;
  45 import com.sun.jdi.VirtualMachine;
  46 import com.sun.jdi.connect.Connector;
  47 import com.sun.jdi.connect.IllegalConnectorArgumentsException;
  48 import com.sun.jdi.connect.LaunchingConnector;
  49 import com.sun.jdi.connect.VMStartException;
  50 import com.sun.jdi.event.ClassPrepareEvent;
  51 import com.sun.jdi.event.VMStartEvent;
  52 import com.sun.jdi.event.Event;
  53 import com.sun.jdi.event.EventQueue;
  54 import com.sun.jdi.event.EventSet;
  55 import com.sun.jdi.event.ModificationWatchpointEvent;
  56 import com.sun.jdi.event.VMDeathEvent;
  57 import com.sun.jdi.event.VMDisconnectEvent;
  58 import com.sun.jdi.request.ClassPrepareRequest;
  59 import com.sun.jdi.request.EventRequest;
  60 import com.sun.jdi.request.EventRequestManager;
  61 import com.sun.jdi.request.ModificationWatchpointRequest;
  62 
  63 public class FieldMonitor {
  64 
  65   public static final String CLASS_NAME = "TestPostFieldModification";
  66   public static final String FIELD_NAME = "value";
  67   public static final String ARGUMENTS = "-Xshare:off -XX:+PrintGC";
  68 
  69   public static void main(String[] args)
  70       throws IOException, InterruptedException {
  71     
  72     VirtualMachine vm = launchTarget(CLASS_NAME);
  73     EventQueue eventQueue = vm.eventQueue();
  74     
  75     // make sure the vm is started   
  76     boolean started = false;
  77     while(!started) {
  78       EventSet eventSet = eventQueue.remove();
  79       for (Event event : eventSet) {
  80         if (event instanceof VMStartEvent) {
  81           started = true;
  82         }
  83         if (event instanceof VMDeathEvent
  84             || event instanceof VMDisconnectEvent) {
  85           throw new Error("VM died before it started...:"+event);
  86         }
  87       }
  88     }


  89 
  90     System.out.println("Vm launched");
  91 





  92     // watch for loaded classes
  93     addClassWatch(vm);
  94 
  95     // process events



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