예제 #1
0
  public static void main(String[] args) {
    String outputDirectory = System.getProperty("outputDirectory");

    Instrumentation instrumentation = new Instrumentation();
    instrumentation.setOutputDirectory(outputDirectory);
    instrumentation.instrument();
  }
예제 #2
0
  public static void premain(String args, Instrumentation inst) throws Exception {
    try {
      String[] agentArgs;
      if (args == null) agentArgs = new String[] {""};
      else agentArgs = args.split(",");
      if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0];
      BaseClassTransformer rct = null;
      rct = new BaseClassTransformer();
      if (agentArgs[0].equals("instrumenting")) {
        initVMClasses = new HashSet<String>();
        for (Class<?> c : inst.getAllLoadedClasses()) {
          ((Set<String>) initVMClasses).add(c.getName());
        }
      }
      if (!agentArgs[0].equals("instrumenting")) {

        inst.addTransformer(rct);
        Tracer.setLocals(new CounterThreadLocal());
        Tracer.overrideAll(true);
        for (Class<?> c : inst.getAllLoadedClasses()) {
          try {
            if (c.isInterface()) continue;
            if (c.isArray()) continue;
            byte[] bytes = rct.getBytes(c.getName());
            if (bytes == null) {
              continue;
            }
            inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)});
          } catch (Throwable e) {
            synchronized (System.err) {
              System.err.println("" + c + " failed...");
              e.printStackTrace();
            }
          }
        }
        Runtime.getRuntime()
            .addShutdownHook(
                new Thread() {
                  public void run() {
                    Tracer.mark();
                    try {
                      PrintStream ps = new PrintStream("bailout.txt");
                      ps.println("Bailouts: " + Tracer.getBailoutCount());
                      ps.close();
                    } catch (Exception e) {
                    }
                    Tracer.unmark();
                  }
                });
        if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #3
0
 private void runTicks(Instrumentation instrumentation) throws InterruptedException {
   int n = 0;
   while (n++ < 120) {
     instrumentation.record("TICK");
     Thread.sleep(4);
   }
 }
 @ThreadedBefore
 public void before() {
   SimpleClass instance = new SimpleClass();
   recorder = new MethodRecorder<SimpleClass>(SimpleClass.class);
   control = recorder.getControl();
   ic = Instrumentation.getClassInstrumentation(SimpleClass.class);
 }
예제 #5
0
  public void testItemClick() throws Exception {
    ds.writeNote("Note 1", "test");
    start();
    Instrumentation.ActivityMonitor monitor =
        instrumentation.addMonitor(Editor.class.getName(), null, false);

    notes.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            listView.performItemClick(listView, 0, 0);
          }
        });

    instrumentation.waitForIdleSync();
    Activity editor = instrumentation.waitForMonitorWithTimeout(monitor, 3 * 1000);
    notes.finishActivity(1);
    assertNotNull("Editor not started in 3 sec.", editor);
  }
예제 #6
0
  private E2<DummyLogger, DummyRemoteInstrumentationLogger> setupLoggers(
      final String levelsConfig) {
    // Red of Instrumentation.configure ()
    Logging.clearLoggers();

    final DummyRemoteInstrumentationLogger remoteLogger =
        new DummyRemoteInstrumentationLogger("fewi", getTempPath("log-remote.txt"));

    final List<ConsoleStringLogger> slaves =
        OUTPUT_TO_CONSOLE ? Arrays.asList(new ConsoleStringLogger()) : null;
    final DummyLogger localLogger =
        new DummyLogger(levelsConfig, slaves, getTempPath("log-local.txt"));
    Logging.addLogger(localLogger);

    Instrumentation.addInstrumentationListener(new InstrumentionStringLogger(localLogger));

    Instrumentation.addInstrumentationListener(remoteLogger);
    Logging.addLogger(remoteLogger);

    return E2.of(localLogger, remoteLogger);
  }
  /**
   * Creates an intrument functions compiler pass.
   *
   * @param compiler The JSCompiler
   * @param functionNames Assigned function identifiers.
   * @param templateFilename Template filename; for use during error reporting only.
   * @param appNameStr String to pass to appNameSetter.
   * @param readable Instrumentation template protobuf text.
   */
  InstrumentFunctions(
      AbstractCompiler compiler,
      FunctionNames functionNames,
      String templateFilename,
      String appNameStr,
      Readable readable) {
    this.compiler = compiler;
    this.functionNames = functionNames;
    this.templateFilename = templateFilename;
    this.appNameStr = appNameStr;

    Instrumentation.Builder builder = Instrumentation.newBuilder();
    try {
      TextFormat.merge(readable, builder);
    } catch (IOException e) {
      compiler.report(
          JSError.make(
              RhinoErrorReporter.PARSE_ERROR,
              "Error reading instrumentation template protobuf at " + templateFilename));
      this.initCodeSource = "";
      this.definedFunctionName = "";
      this.reportFunctionName = "";
      this.reportFunctionExitName = "";
      this.appNameSetter = "";
      this.declarationsToRemove = Lists.newArrayList();
      return;
    }

    Instrumentation template = builder.build();

    StringBuilder initCodeSourceBuilder = new StringBuilder();
    for (String line : template.getInitList()) {
      initCodeSourceBuilder.append(line).append("\n");
    }
    this.initCodeSource = initCodeSourceBuilder.toString();

    this.definedFunctionName = template.getReportDefined();
    this.reportFunctionName = template.getReportCall();
    this.reportFunctionExitName = template.getReportExit();
    this.appNameSetter = template.getAppNameSetter();

    this.declarationsToRemove = ImmutableList.copyOf(template.getDeclarationToRemoveList());
  }
  /**
   * Creates an instrument functions compiler pass.
   *
   * @param compiler The JSCompiler
   * @param functionNames Assigned function identifiers.
   * @param template Instrumentation template; for use during error reporting only.
   * @param appNameStr String to pass to appNameSetter.
   */
  InstrumentFunctions(
      AbstractCompiler compiler,
      FunctionNames functionNames,
      Instrumentation template,
      String appNameStr) {
    this.compiler = compiler;
    this.functionNames = functionNames;
    this.appNameStr = appNameStr;

    StringBuilder initCodeSourceBuilder = new StringBuilder();
    for (String line : template.getInitList()) {
      initCodeSourceBuilder.append(line).append("\n");
    }
    this.initCodeSource = initCodeSourceBuilder.toString();

    this.definedFunctionName = template.getReportDefined();
    this.reportFunctionName = template.getReportCall();
    this.reportFunctionExitName = template.getReportExit();
    this.appNameSetter = template.getAppNameSetter();

    this.declarationsToRemove = ImmutableList.copyOf(template.getDeclarationToRemoveList());
  }
예제 #9
0
  @Test
  public void testInstrumentation() {
    try (IScope scope = new ExecutionScope()) {
      Instrumentation.setPolicyAsyncInstrumentation(false); // execute actions synchronously

      final E2<DummyLogger, DummyRemoteInstrumentationLogger> loggers = setupLoggers("fewi");
      final DummyLogger localLogger = loggers.getE0();
      final DummyRemoteInstrumentationLogger remoteLogger = loggers.getE1();

      if (true) {
        Instrumentation.publishExecutionSummary();
        checkInstrumentationListener(remoteLogger, 1, 0, 0, 0);
        checkLogger(localLogger, 0, 0, 0, 1, 0, 0);
        checkLogger(remoteLogger, 0, 0, 0, 0, 0, 0);
      }

      if (true) {
        final String name = "timelyOperation";
        Instrumentation.execute(
            name,
            200,
            () -> {
              HcUtil.pause(10);
            },
            name);

        Instrumentation.publishExecutionSummary();
        checkInstrumentationListener(remoteLogger, 2, 0, 0, 0);
        checkLogger(localLogger, 0, 0, 0, 2, 0, 0);
        checkLogger(remoteLogger, 0, 0, 0, 0, 0, 0);
      }

      if (true) {
        final String name = "slowOperation";
        Instrumentation.execute(
            name,
            10,
            () -> {
              HcUtil.pause(100);
            },
            name);

        Instrumentation.publishExecutionSummary();
        checkInstrumentationListener(remoteLogger, 3, 1, 1, 0);
        checkLogger(localLogger, 0, 0, 2, 3, 0, 0);
        checkLogger(remoteLogger, 0, 0, 0, 0, 0, 0);
      }

      if (true) {
        try {
          final String name = "failedTimelyOperation";
          Instrumentation.execute(
              name,
              200,
              () -> {
                HcUtil.pause(10);
                ThreadContext.assertFaultNotNull(null);
              },
              name);
        } catch (final Exception e) {
        }

        Instrumentation.publishExecutionSummary();
        checkInstrumentationListener(remoteLogger, 4, 1, 1, 1);
        checkLogger(localLogger, 2, 0, 2, 4, 0, 0);
        checkLogger(remoteLogger, 1, 0, 0, 0, 0, 0);
      }

      if (true) {
        try {
          final String name = "failedTimelyOperationException";
          Instrumentation.execute(
              name,
              200,
              () -> {
                HcUtil.pause(10);
                throw new RuntimeException("Ooops");
              },
              name);
        } catch (final Exception e) {
        }

        Instrumentation.publishExecutionSummary();
        checkInstrumentationListener(remoteLogger, 5, 1, 1, 2);
        checkLogger(localLogger, 4, 0, 2, 5, 0, 0);
        checkLogger(remoteLogger, 2, 0, 0, 0, 0, 0);
      }
    }
  }
 @Override
 public void init() {
   leakTracing.init();
   instrumentation.init();
 }
  /**
   * INTERNAL predeploy (with deploy) is one of the two steps required in deployment of entities
   * This method will prepare to call predeploy, call it and finally register the transformer
   * returned to be used for weaving.
   */
  protected boolean callPredeploy(
      SEPersistenceUnitInfo persistenceUnitInfo,
      Map m,
      PersistenceInitializationActivator persistenceActivator) {
    ClassLoader tempLoader = null;
    // we will only attempt to deploy when TopLink is specified as the provider or the provider is
    // unspecified
    String providerClassName = persistenceUnitInfo.getPersistenceProviderClassName();
    if (persistenceActivator.isPersistenceProviderSupported(providerClassName)) {
      EntityManagerSetupImpl emSetupImpl =
          EntityManagerFactoryProvider.getEntityManagerSetupImpl(
              persistenceUnitInfo.getPersistenceUnitRootUrl()
                  + persistenceUnitInfo.getPersistenceUnitName());

      // if we already have an EntityManagerSetupImpl this PU has already been processed.  Use the
      // existing one
      if (emSetupImpl != null && !emSetupImpl.isUndeployed()) {
        return false;
      }
      Set tempLoaderSet =
          PersistenceUnitProcessor.buildClassSet(
              persistenceUnitInfo, Thread.currentThread().getContextClassLoader());

      Map mergedProperties =
          EntityManagerFactoryProvider.mergeMaps(m, persistenceUnitInfo.getProperties());

      String weaving =
          EntityManagerFactoryProvider.getConfigPropertyAsString(
              TopLinkProperties.WEAVING, mergedProperties, null);
      // Bug#4452468  When globalInstrumentation is null, there is no weaving
      if (globalInstrumentation == null) {
        if (weaving == null) {
          mergedProperties.put(TopLinkProperties.WEAVING, "false");
          weaving = "false";
        } else if (weaving.equalsIgnoreCase("true")) {
          throw new PersistenceException(EntityManagerSetupException.wrongWeavingPropertyValue());
        }
      }

      // Bug#2741: If weaving disabled then use regular loader, not a temp one
      if (weaving != null
          && (weaving.equalsIgnoreCase("false") || weaving.equalsIgnoreCase("static"))) {
        shouldCreateInternalLoader = false;
      }
      // Create the temp loader that will not cache classes for entities in our persistence unit
      tempLoader = createTempLoader(tempLoaderSet);
      persistenceUnitInfo.setNewTempClassLoader(tempLoader);
      persistenceUnitInfo.setClassLoader(getMainLoader());
      if (emSetupImpl == null) {
        emSetupImpl = new EntityManagerSetupImpl();
        EntityManagerFactoryProvider.addEntityManagerSetupImpl(
            persistenceUnitInfo.getPersistenceUnitRootUrl()
                + persistenceUnitInfo.getPersistenceUnitName(),
            emSetupImpl);
      }
      // Make the callback
      AbstractSessionLog.getLog()
          .log(
              SessionLog.FINER,
              "cmp_init_invoke_predeploy",
              persistenceUnitInfo.getPersistenceUnitName());

      // A call to predeploy will partially build the session we will use
      final ClassTransformer transformer =
          emSetupImpl.predeploy(persistenceUnitInfo, mergedProperties);

      // If we got a transformer then register it
      if ((transformer != null) && (globalInstrumentation != null)) {
        AbstractSessionLog.getLog()
            .log(
                SessionLog.FINER,
                "cmp_init_register_transformer",
                persistenceUnitInfo.getPersistenceUnitName());
        globalInstrumentation.addTransformer(
            new ClassFileTransformer() {
              // adapt ClassTransformer to ClassFileTransformer interface
              public byte[] transform(
                  ClassLoader loader,
                  String className,
                  Class<?> classBeingRedefined,
                  ProtectionDomain protectionDomain,
                  byte[] classfileBuffer)
                  throws IllegalClassFormatException {
                return transformer.transform(
                    loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
              }
            });
      } else if (transformer == null) {
        AbstractSessionLog.getLog().log(SessionLog.FINER, "cmp_init_transformer_is_null");
      } else if (globalInstrumentation == null) {
        AbstractSessionLog.getLog().log(SessionLog.FINER, "cmp_init_globalInstrumentation_is_null");
      }
      return true;
    }
    return false;
  }