FieldMonitor.java 8.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * Copyright 2012 SAP AG.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test FieldMonitor.java
 * @bug 7158988
27
 * @key regression
28
 * @summary verify jvm does not crash while debugging
29 30
 * @run compile TestPostFieldModification.java
 * @run main/othervm FieldMonitor
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 * @author axel.siebenborn@sap.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.sun.jdi.Bootstrap;
import com.sun.jdi.Field;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.LaunchingConnector;
import com.sun.jdi.connect.VMStartException;
import com.sun.jdi.event.ClassPrepareEvent;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.EventQueue;
import com.sun.jdi.event.EventSet;
import com.sun.jdi.event.ModificationWatchpointEvent;
import com.sun.jdi.event.VMDeathEvent;
import com.sun.jdi.event.VMDisconnectEvent;
import com.sun.jdi.request.ClassPrepareRequest;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.ModificationWatchpointRequest;

public class FieldMonitor {

  public static final String CLASS_NAME = "TestPostFieldModification";
  public static final String FIELD_NAME = "value";
  public static final String ARGUMENTS = "-Xshare:off -XX:+PrintGC";

  public static void main(String[] args)
      throws IOException, InterruptedException {

    StringBuffer sb = new StringBuffer();

    for (int i=0; i < args.length; i++) {
        sb.append(' ');
        sb.append(args[i]);
    }
    //VirtualMachine vm = launchTarget(sb.toString());
    VirtualMachine vm = launchTarget(CLASS_NAME);

    System.out.println("Vm launched");
    // set watch field on already loaded classes
    List<ReferenceType> referenceTypes = vm
        .classesByName(CLASS_NAME);
    for (ReferenceType refType : referenceTypes) {
      addFieldWatch(vm, refType);
    }
    // watch for loaded classes
    addClassWatch(vm);

    // process events
    EventQueue eventQueue = vm.eventQueue();
    // resume the vm

    Process process = vm.process();


    // Copy target's output and error to our output and error.
    Thread outThread = new StreamRedirectThread("out reader", process.getInputStream());
    Thread errThread = new StreamRedirectThread("error reader", process.getErrorStream());

    errThread.start();
    outThread.start();


    vm.resume();
    boolean connected = true;
    while (connected) {
      EventSet eventSet = eventQueue.remove();
      for (Event event : eventSet) {
        if (event instanceof VMDeathEvent
            || event instanceof VMDisconnectEvent) {
          // exit
          connected = false;
        } else if (event instanceof ClassPrepareEvent) {
          // watch field on loaded class
          System.out.println("ClassPrepareEvent");
          ClassPrepareEvent classPrepEvent = (ClassPrepareEvent) event;
          ReferenceType refType = classPrepEvent
              .referenceType();
          addFieldWatch(vm, refType);
        } else if (event instanceof ModificationWatchpointEvent) {
          System.out.println("sleep for 500 ms");
          Thread.sleep(500);
          System.out.println("resume...");

          ModificationWatchpointEvent modEvent = (ModificationWatchpointEvent) event;
          System.out.println("old="
              + modEvent.valueCurrent());
          System.out.println("new=" + modEvent.valueToBe());
          System.out.println();
        }
      }
      eventSet.resume();
    }
    // Shutdown begins when event thread terminates
    try {
        errThread.join(); // Make sure output is forwarded
        outThread.join();
    } catch (InterruptedException exc) {
        // we don't interrupt
    }
  }

  /**
   * Find a com.sun.jdi.CommandLineLaunch connector
   */
  static LaunchingConnector findLaunchingConnector() {
    List <Connector> connectors = Bootstrap.virtualMachineManager().allConnectors();
    Iterator <Connector> iter = connectors.iterator();
    while (iter.hasNext()) {
      Connector connector = iter.next();
      if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) {
        return (LaunchingConnector)connector;
      }
    }
    throw new Error("No launching connector");
  }
  /**
   * Return the launching connector's arguments.
   */
 static Map <String,Connector.Argument> connectorArguments(LaunchingConnector connector, String mainArgs) {
      Map<String,Connector.Argument> arguments = connector.defaultArguments();
      for (String key : arguments.keySet()) {
        System.out.println(key);
      }

      Connector.Argument mainArg = (Connector.Argument)arguments.get("main");
      if (mainArg == null) {
          throw new Error("Bad launching connector");
      }
      mainArg.setValue(mainArgs);

      Connector.Argument optionsArg = (Connector.Argument)arguments.get("options");
      if (optionsArg == null) {
        throw new Error("Bad launching connector");
      }
      optionsArg.setValue(ARGUMENTS);
      return arguments;
  }

 static VirtualMachine launchTarget(String mainArgs) {
    LaunchingConnector connector = findLaunchingConnector();
    Map  arguments = connectorArguments(connector, mainArgs);
    try {
        return (VirtualMachine) connector.launch(arguments);
    } catch (IOException exc) {
        throw new Error("Unable to launch target VM: " + exc);
    } catch (IllegalConnectorArgumentsException exc) {
        throw new Error("Internal error: " + exc);
    } catch (VMStartException exc) {
        throw new Error("Target VM failed to initialize: " +
                        exc.getMessage());
    }
}


  private static void addClassWatch(VirtualMachine vm) {
    EventRequestManager erm = vm.eventRequestManager();
    ClassPrepareRequest classPrepareRequest = erm
        .createClassPrepareRequest();
    classPrepareRequest.addClassFilter(CLASS_NAME);
    classPrepareRequest.setEnabled(true);
  }


  private static void addFieldWatch(VirtualMachine vm,
      ReferenceType refType) {
    EventRequestManager erm = vm.eventRequestManager();
    Field field = refType.fieldByName(FIELD_NAME);
    ModificationWatchpointRequest modificationWatchpointRequest = erm
        .createModificationWatchpointRequest(field);
    modificationWatchpointRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
    modificationWatchpointRequest.setEnabled(true);
  }
}

class StreamRedirectThread extends Thread {

  private final BufferedReader in;

  private static final int BUFFER_SIZE = 2048;

  /**
   * Set up for copy.
   * @param name  Name of the thread
   * @param in    Stream to copy from
   * @param out   Stream to copy to
   */
  StreamRedirectThread(String name, InputStream in) {
    super(name);
    this.in = new BufferedReader(new InputStreamReader(in));
  }

  /**
   * Copy.
   */
  public void run() {
    try {
      String line;
        while ((line = in.readLine ()) != null) {
          System.out.println ("testvm: " + line);
      }
     System.out.flush();
    } catch(IOException exc) {
      System.err.println("Child I/O Transfer - " + exc);
    }
  }
}