PreMain.java

  1. /*******************************************************************************
  2.  * Copyright (c) 2009, 2025 Mountainminds GmbH & Co. KG and Contributors
  3.  * This program and the accompanying materials are made available under
  4.  * the terms of the Eclipse Public License 2.0 which is available at
  5.  * http://www.eclipse.org/legal/epl-2.0
  6.  *
  7.  * SPDX-License-Identifier: EPL-2.0
  8.  *
  9.  * Contributors:
  10.  *    Marc R. Hoffmann - initial API and implementation
  11.  *
  12.  *******************************************************************************/
  13. package org.jacoco.agent.rt.internal;

  14. import java.lang.instrument.Instrumentation;

  15. import org.jacoco.core.runtime.AgentOptions;
  16. import org.jacoco.core.runtime.IRuntime;
  17. import org.jacoco.core.runtime.InjectedClassRuntime;
  18. import org.jacoco.core.runtime.ModifiedSystemClassRuntime;

  19. /**
  20.  * The agent which is referred as the <code>Premain-Class</code>. The agent
  21.  * configuration is provided with the agent parameters in the command line.
  22.  */
  23. public final class PreMain {

  24.     private PreMain() {
  25.         // no instances
  26.     }

  27.     /**
  28.      * This method is called by the JVM to initialize Java agents.
  29.      *
  30.      * @param options
  31.      *            agent options
  32.      * @param inst
  33.      *            instrumentation callback provided by the JVM
  34.      * @throws Exception
  35.      *             in case initialization fails
  36.      */
  37.     public static void premain(final String options, final Instrumentation inst)
  38.             throws Exception {

  39.         final AgentOptions agentOptions = new AgentOptions(options);

  40.         final Agent agent = Agent.getInstance(agentOptions);

  41.         final IRuntime runtime = createRuntime(inst);
  42.         runtime.startup(agent.getData());
  43.         inst.addTransformer(new CoverageTransformer(runtime, agentOptions,
  44.                 IExceptionLogger.SYSTEM_ERR));
  45.     }

  46.     private static IRuntime createRuntime(final Instrumentation inst)
  47.             throws Exception {

  48.         if (AgentModule.isSupported()) {
  49.             final AgentModule module = new AgentModule();
  50.             module.openPackage(inst, Object.class);
  51.             final Class<InjectedClassRuntime> clazz = module
  52.                     .loadClassInModule(InjectedClassRuntime.class);
  53.             return clazz.getConstructor(Class.class, String.class)
  54.                     .newInstance(Object.class, "$JaCoCo");
  55.         }

  56.         return ModifiedSystemClassRuntime.createFor(inst,
  57.                 "java/lang/UnknownError");
  58.     }

  59. }