/** * 初始化类字节码的转换器 * * @param inst 用于管理字节码转换器 */ private static void initTransformer(Instrumentation inst) throws UnmodifiableClassException { LinkedList<Class> retransformClasses = new LinkedList<Class>(); CustomClassTransformer customClassTransformer = new CustomClassTransformer(); inst.addTransformer(customClassTransformer, true); Class[] loadedClasses = inst.getAllLoadedClasses(); for (Class clazz : loadedClasses) { for (final AbstractClassHook hook : customClassTransformer.getHooks()) { if (hook.isClassMatched(clazz.getName().replace(".", "/"))) { if (inst.isModifiableClass(clazz) && !clazz.getName().startsWith("java.lang.invoke.LambdaForm")) { retransformClasses.add(clazz); } } } } // hook已经加载的类 Class[] classes = new Class[retransformClasses.size()]; retransformClasses.toArray(classes); if (classes.length > 0) { inst.retransformClasses(classes); } }
/** * 启动时加载的agent入口方法 * * @param agentArg 启动参数 * @param inst {@link Instrumentation} */ public static void premain(String agentArg, Instrumentation inst) { try { JarFileHelper.addJarToBootstrap(inst); if (!loadConfig(JarFileHelper.getLocalJarParentPath())) { return; } readVersion(); // 初始化插件系统 JsPluginManager.init(); CheckerManager.init(); initTransformer(inst); String message = "OpenRasp Initialized [" + projectVersion + " (build: GitCommit=" + gitCommit + " date=" + buildTime + ")]"; System.out.println(message); Logger.getLogger(Agent.class.getName()).info(message); HookHandler.enableHook.set(true); } catch (Exception e) { System.out.println("[OpenRASP] Failed to initialize, will continue without security protection."); e.printStackTrace(); } }
public static void premain(String agentArg, Instrumentation inst) { String[] args = agentArg.split(":"); if (args.length > 2) { System.err.println(USAGE); } int port = 7400; try { port = Integer.parseInt(args[0]); } catch(Exception e) { System.err.println(USAGE + ". No port specified so using default port for cassandra prometheus exporter " + port); } String path = "metrics"; if (args.length == 2) { if (args[1].length() > 0) { path = args[1]; } else { System.err.println(USAGE + ". Invalid path defined so using default path for cassandra prometheus exporter: " + path); } } PrometheusExporter exp = new PrometheusExporter(port, path); }
private void initManager(final Instrumentation inst, final CoreConfigure cfg) { logger.debug("{} was init", EventListenerHandlers.getSingleton()); final ModuleLifeCycleEventBus moduleLifeCycleEventBus = new DefaultModuleLifeCycleEventBus(); final LoadedClassDataSource classDataSource = new DefaultLoadedClassDataSource(inst); final ClassLoader sandboxClassLoader = getClass().getClassLoader(); // 初始化模块资源管理器 this.moduleResourceManager = new DefaultModuleResourceManager(); moduleLifeCycleEventBus.append(this.moduleResourceManager); // 初始化服务管理器 final ProviderManager providerManager = new DefaultProviderManager(cfg, sandboxClassLoader); // 初始化模块管理器 this.coreModuleManager = new DefaultCoreModuleManager( inst, classDataSource, cfg, sandboxClassLoader, moduleLifeCycleEventBus, providerManager ); }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from RedefineMethodInBacktraceAgent!"); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); instrumentation = inst; }
public static void premain(String args, Instrumentation instrumentation) { if (!instrumentation.isRetransformClassesSupported()) { System.out.println("Class retransformation is not supported."); return; } System.out.println("Calling lambda to ensure that lambda forms were created"); Agent.lambda.run(); System.out.println("Registering class file transformer"); instrumentation.addTransformer(new Agent()); for (Class c : instrumentation.getAllLoadedClasses()) { if (c.getName().contains("LambdaForm") && instrumentation.isModifiableClass(c)) { System.out.format("We've found a modifiable lambda form: %s%n", c.getName()); try { instrumentation.retransformClasses(c); } catch (UnmodifiableClassException e) { throw new AssertionError("Modification of modifiable class " + "caused UnmodifiableClassException", e); } } } }
/** * Use redefineModule to update java.base to read java.instrument */ public void testAddReads() { Module baseModule = Object.class.getModule(); Module instrumentModule = Instrumentation.class.getModule(); // pre-conditions assertFalse(baseModule.canRead(instrumentModule)); // update java.base to read java.instrument Set<Module> extraReads = Set.of(instrumentModule); redefineModule(baseModule, extraReads, Map.of(), Map.of(), Set.of(), Map.of()); assertTrue(baseModule.canRead(instrumentModule)); }
/** * 动态加载 * * @param featureString 启动参数 * [namespace,token,ip,port,prop] * @param inst inst */ public static void agentmain(String featureString, Instrumentation inst) { LAUNCH_MODE = LAUNCH_MODE_ATTACH; final Map<String, String> featureMap = toFeatureMap(featureString); writeAttachResult( getNamespace(featureMap), getToken(featureMap), main(featureMap, inst) ); }
public static void premain(final String args, Instrumentation instrumentation) throws Exception { instrumentation.addTransformer(new MenuItemTransformer()); instrumentation.addTransformer(new FileChooserTransformer()); logger.info("JavaVersion: " + System.getProperty("java.version")); final int port; if (args != null && args.trim().length() > 0) { port = Integer.parseInt(args.trim()); } else { throw new Exception("Port number not specified"); } windowTitle = System.getProperty("start.window.title", ""); ObservableList<Stage> stages = StageHelper.getStages(); stages.addListener(new ListChangeListener<Stage>() { boolean done = false; @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends Stage> c) { if (done) { return; } if (!"".equals(windowTitle)) { logger.warning("WindowTitle is not supported yet... Ignoring it."); } c.next(); if (c.wasAdded()) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return new JavaFxRecorderHook(port); } }); done = true; } } }); }
public static void premain(String agentArgs, Instrumentation inst) { try { PromagentCollectorRegistry registry = new PromagentCollectorRegistry(); ManagementFactory.getPlatformMBeanServer().registerMBean(new Exporter(registry), new ObjectName("io.promagent:type=exporter")); Map<String, String> args = parseCmdline(agentArgs); if (args.containsKey("port")) { BuiltInServer.run(args.get("host"), args.get("port"), registry); } ClassLoaderCache classLoaderCache = ClassLoaderCache.getInstance(); List<Path> hookJars = classLoaderCache.getPerDeploymentJars(); SortedSet<HookMetadata> hookMetadata = new HookMetadataParser(hookJars).parse(); MetricsStore metricsStore = new MetricsStore(registry); Delegator.init(hookMetadata, metricsStore, classLoaderCache); printHookMetadata(hookMetadata); AgentBuilder agentBuilder = new AgentBuilder.Default() .with(AgentBuilder.RedefinitionStrategy.REDEFINITION) .with(AgentBuilder.TypeStrategy.Default.REDEFINE); // .with(AgentBuilder.Listener.StreamWriting.toSystemError()); // use this to see exceptions thrown in instrumented code agentBuilder = applyHooks(agentBuilder, hookMetadata, classLoaderCache); agentBuilder.installOn(inst); // TODO -- the following is an experiment supporting collectors directly (in addition to hooks) // io.prometheus.client.Collector jmxCollector = (io.prometheus.client.Collector) classLoaderCache.currentClassLoader().loadClass("io.promagent.collectors.JmxCollector").newInstance(); // registry.registerNoJmx(jmxCollector); } catch (Throwable t) { t.printStackTrace(); } }
public static void premain(String arg, Instrumentation instrumentation) { try { log("launched from javaagent"); if (arg != null && !arg.isEmpty()) { System.setProperty("org.to2mbn.authlibinjector.config", arg); } bootstrap(instrumentation::addTransformer); } catch (Throwable e) { // prevent the exception being thrown to VM e.printStackTrace(); } }
public static void premain(final String args, final Instrumentation instrumentation) throws Exception { final BootstrapConfiguration configuration = getConfigurationFromFile(); loadMavenArtifacts(instrumentation, configuration); loadClassPathFiles(instrumentation, configuration.files); loadClassPathUrlsAsString(instrumentation, configuration.urls); loadShutdownHooks(configuration); loadApplicationBootstrapClassName(configuration); }
private static void loadMavenArtifacts(final Instrumentation instrumentation, final BootstrapConfiguration configuration) throws Exception { if (configuration.hasMavenArtifact()) { initMavenDependencyResolver(instrumentation); addMavenRepositories(configuration.maven_repositories); resolveAndLoadMavenArtifacts(instrumentation, configuration.maven_artifacts); } }
/** * 模块模块管理 * * @param inst inst * @param classDataSource 已加载类数据源 * @param cfg 模块核心配置 * @param sandboxClassLoader 沙箱加载ClassLoader * @param moduleLifeCycleEventBus 模块生命周期通知总线 * @param providerManager 服务提供者管理器 */ public DefaultCoreModuleManager(final Instrumentation inst, final LoadedClassDataSource classDataSource, final CoreConfigure cfg, final ClassLoader sandboxClassLoader, final ModuleLifeCycleEventBus moduleLifeCycleEventBus, final ProviderManager providerManager) { this.inst = inst; this.classDataSource = classDataSource; this.cfg = cfg; this.sandboxClassLoader = sandboxClassLoader; this.moduleLifeCycleEventBus = moduleLifeCycleEventBus; this.providerManager = providerManager; // 初始化模块目录 this.moduleLibDirArray = mergeFileArray( new File[]{new File(cfg.getSystemModuleLibPath())}, cfg.getUserModuleLibFilesWithCache() ); // 初始化加载所有的模块 try { reset(); } catch (ModuleException e) { logger.warn("init module[id={};] occur error={}.", e.getUniqueId(), e.getErrorCode(), e); } }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from ManifestTestAgent!"); System.out.println("isNativeMethodPrefixSupported()=" + inst.isNativeMethodPrefixSupported()); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); System.out.println("isRetransformClassesSupported()=" + inst.isRetransformClassesSupported()); }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from RedefineMethodDelInvokeAgent!"); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); instrumentation = inst; }
public static void main(String args[]) { Module unnamed = AddModuleReadsTest.class.getClassLoader().getUnnamedModule(); Module base = Object.class.getModule(); Module instrument = Instrumentation.class.getModule(); int status = check(unnamed, base, instrument); if (status != 0) { throw new RuntimeException("Non-zero status returned from the agent: " + status); } }
public static void premain(String agentArgs, final Instrumentation inst) throws Exception { String s = agentArgs.substring(0, agentArgs.indexOf(".class")); clz = Class.forName(s.replace('/', '.')); InputStream in; Module m = clz.getModule(); if (m != null) { in = m.getResourceAsStream(agentArgs); } else { ClassLoader loader = RedefineClassWithNativeMethodAgent.class.getClassLoader(); in = loader.getResourceAsStream(agentArgs); } if (in == null) { throw new Exception("Cannot find class: " + agentArgs); } byte[] buffer = in.readAllBytes(); new Timer(true).schedule(new TimerTask() { public void run() { try { System.out.println("Instrumenting"); ClassDefinition cld = new ClassDefinition(clz, buffer); inst.redefineClasses(new ClassDefinition[] { cld }); } catch (Exception e) { e.printStackTrace(); } } }, 500); }
DefaultModuleEventWatcher(final Instrumentation inst, final LoadedClassDataSource classDataSource, final CoreModule coreModule, final boolean isEnableUnsafe) { this.inst = inst; this.classDataSource = classDataSource; this.coreModule = coreModule; this.isEnableUnsafe = isEnableUnsafe; }
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception { main0(agentArgs, instrumentation, (a, i) -> { try { Main.premain(a, i); } catch (Exception e) { throw new AgentInitializationException(e); } }); }
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception { main0(agentArgs, instrumentation, (a, i) -> { try { Main.agentmain(a, i); } catch (Exception e) { throw new AgentInitializationException(e); } }); }
private static void main0(String agentArgs, Instrumentation instrumentation, BiConsumer<String, Instrumentation> delegate) { if (ClassLoader.getSystemResource(BTM_SCRIPTS_RESOURCE_PATH) == null) { System.err.println("Could not load " + BTM_SCRIPTS_RESOURCE_PATH + "." + "Agent will not be started."); return; } try { ConfigService.initialize(); } catch (ConfigurationException | IOException | RuntimeException e) { System.err.println(e.getMessage()); System.err.println("Agent will not be started."); return; } if (agentArgs != null && agentArgs.trim().length() > 0) { agentArgs += "," + AGENT_PARAMS; } else { agentArgs = AGENT_PARAMS; } JarFile bytemanJar = createBytemanJar(); if (bytemanJar == null) { System.err.println("Could not locate: " + BYTEMAN_JAR_RESOURCE_NAME); System.err.println("Agent will not be started."); return; } instrumentation.appendToBootstrapClassLoaderSearch(bytemanJar); delegate.accept(agentArgs, instrumentation); }
/** * Obtain the Instrumentation instance for the current VM, if available. * @return the Instrumentation instance, or {@code null} if none found * @see #isInstrumentationAvailable() */ private static Instrumentation getInstrumentation() { if (AGENT_CLASS_PRESENT) { return InstrumentationAccessor.getInstrumentation(); } else { return null; } }
public static void agentmain(String arg,Instrumentation inst) throws AttachNotSupportedException, IOException { MyAgent.inst=inst; System.out.println("agent代理程序类[MyAgent]被执行!"); System.out.println("当前代理程序类使用加载器:"+Thread.currentThread().getContextClassLoader().toString()); num.incrementAndGet(); System.out.println(num.longValue()); System.out.println(arg); Class<?>[] classes = inst.getAllLoadedClasses(); for(Class<?> cls :classes) { System.out.println(cls.getName()); } }
public static void premain(String agentArgs, Instrumentation instrumentation) { //public static void agentmain(String agentArgs, Instrumentation instrumentation) { //System.out.println("agent started"); Agent.instrumentation = instrumentation; instrumentation.addTransformer(new ClassFileTransformer() { @Override public byte[] transform(Module module, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { //System.out.println("transform " + className + " " + classBeingRedefined); if (classBeingRedefined == null) { // do not rewrite too early return null; } Function<String, Optional<InputStream>> classFileFinder = internalName -> Optional.ofNullable(loader.getResourceAsStream(internalName + ".class")); try { return Rewriter.rewrite(new ByteArrayInputStream(classfileBuffer), classFileFinder); } catch (IOException e) { throw (IllegalClassFormatException)new IllegalClassFormatException().initCause(e); } } }, true); }
private Instrumentation checkInstrumentation() { Instrumentation instrumentation = Agent.instrumentation; if (instrumentation == null) { throw new IllegalStateException("no instrumentation"); } return instrumentation; }
public static Instrumentation getInstrumentationOrThrow() { Instrumentation result = getInstrumentation(); if ( result == null ) { throw new NullPointerException("instrumentation instance not initialized"); } return result; }
/** * Actual method that is going to be called when the JavaAgent is started. * This is called to init the JavaAgent when attached to an already running JVM. * * @param agentArgs in this case, the {@code packagePrefixesToCover} * @param inst */ public static void agentmain(String agentArgs, Instrumentation inst) { packagePrefixesToCover = agentArgs; instrumentator = new Instrumentator(packagePrefixesToCover); inst.addTransformer(new TransformerForTests()); active = true; String port = System.getProperty(EXTERNAL_PORT_PROP); if (port != null) { SimpleLogger.info("Starting remote instrumenting Agent for packages: " + agentArgs); AgentController.start(Integer.parseInt(port)); } String sqlDriver = System.getProperty(SQL_DRIVER); if (sqlDriver != null) { SimpleLogger.info("Initializing P6SPY with base driver " + sqlDriver); initP6Spy(sqlDriver); } String outputFile = System.getProperty(OUTPUT_FILE); if(outputFile != null){ Runtime.getRuntime().addShutdownHook(new Thread(() -> { saveCoverageToDisk(outputFile); })); } }
/** * 启动入口 * @param instrumentation * @return */ public Agent start(Instrumentation instrumentation) { new AgentBuilder.Default() .type( inPlugins().and(not(isInterface())) ) .transform(((builder, typeDescription, classLoader, javaModule) -> { ClassDataSource dataSource = pluginManager.find(typeDescription.getName()); //TODO 大有可为 return DataSourceMonitorRegister.register(dataSource, builder); //注册监听代码(拦截器) })) .with(listener()) .installOn(instrumentation); return this; }
@Override public synchronized void bind(final CoreConfigure cfg, final Instrumentation inst) throws IOException { try { initializer.initProcess(new Initializer.Processor() { @Override public void process() throws Throwable { // logger.info("prepare init sandbox start."); initLogback(cfg); logger.debug("init logback finished."); logger.info("cfg={}", cfg.toString()); initManager(inst, cfg); logger.debug("init resource finished."); initHttpServer(cfg); logger.debug("init http-server finished."); initJettyContextHandler(cfg); logger.debug("init servlet finished."); httpServer.start(); logger.debug("http-server started."); logger.info("sandbox start finished."); } }); } catch (Throwable cause) { logger.warn("server bind failed. cfg={}", cfg, cause); throw new IOException( String.format("server bind to %s:%s failed.", cfg.getServerIp(), cfg.getServerPort()), cause ); } logger.info("server bind to {} success. cfg={}", getLocal(), cfg); }
/** * Populate {@link #instrument} and invoke Recaf. * * @param agentArgs * @param inst */ private static void agent(String agentArgs, Instrumentation inst) { instrument = inst; if (agentArgs == null) { agentArgs = ""; } else { // TODO: Lets say for some reason the user wishes to edit some // core-classes. They would want to set this boolean to false so // core classes are loaded... But if this boolean is set to false, // some wacky things happen. // Screenshot of issue: https://my.mixtape.moe/tptxwl.jpg // I have no idea why the instrumentation API is being such a child, // but I don't know why this is happening. if (agentArgs.equals("keep")) { System.out.println(Recaf.class); excludeInternals = false; } if (agentArgs.equals("keep2")) { excludeInternals = false; } } try { // Add transformer and invoke retransform so already loaded classes // are transformed. ClassPopulator transformer = new ClassPopulator(); instrument.addTransformer(transformer, true); instrument.retransformClasses(getModifable()); } catch (Throwable e) { e.printStackTrace(); } // Manually set params agent value. // I keep getting mis-matched args via picoli when attaching to other // processes. LaunchParams params = new LaunchParams(); params.isAgent = true; Recaf.start(new String[0], params); }
public static void premain(String agentArgs, Instrumentation inst) { String jarPath = "D:/creditRepository/ce-datamonitorsystem/com.creditease.uav.ttl/target/com.creditease.uav.ttl-2.1.0-agent.jar"; inst.addTransformer(new TtlTransformer()); try { inst.appendToBootstrapClassLoaderSearch(new JarFile(jarPath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from RedefineMethodWithAnnotationsAgent!"); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); instrumentation = inst; }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from RedefineMethodAddInvokeAgent!"); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); instrumentation = inst; }
public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Hello from " + "RedefineSubclassWithTwoInterfacesAgent!"); System.out.println("isRedefineClassesSupported()=" + inst.isRedefineClassesSupported()); instrumentation = inst; }
public static void premain(String args, Instrumentation instrumentation) { inst = instrumentation; System.out.println("javaagent in da house!"); instrumentation.addTransformer(new LambdaTransformer()); }