You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OOXMLLiteAgent.java 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ooxml.lite;
  16. import static net.bytebuddy.matcher.ElementMatchers.named;
  17. import java.io.IOException;
  18. import java.lang.instrument.ClassFileTransformer;
  19. import java.lang.instrument.Instrumentation;
  20. import java.nio.charset.StandardCharsets;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.nio.file.StandardOpenOption;
  25. import java.security.ProtectionDomain;
  26. import java.util.HashSet;
  27. import java.util.Set;
  28. import java.util.regex.Pattern;
  29. import java.util.stream.Stream;
  30. import net.bytebuddy.agent.builder.AgentBuilder;
  31. import net.bytebuddy.description.type.TypeDescription;
  32. import net.bytebuddy.dynamic.DynamicType;
  33. import net.bytebuddy.implementation.MethodDelegation;
  34. import net.bytebuddy.implementation.SuperMethodCall;
  35. import net.bytebuddy.matcher.ElementMatchers;
  36. import net.bytebuddy.utility.JavaModule;
  37. import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl;
  38. /**
  39. * OOXMLLiteAgent is the replacement for the former OOXMLLite, because in Java 12
  40. * it isn't possible to access the privates :) of the ClassLoader
  41. */
  42. public class OOXMLLiteAgent {
  43. public static void premain(String agentArgs, Instrumentation inst) throws IOException {
  44. String[] args = (agentArgs == null ? "" : agentArgs).split("\\|", 2);
  45. String logBase = args.length >= 1 ? args[0] : "ooxml-lite-report";
  46. XsbLogger.load(logBase + ".xsb");
  47. ClazzLogger log = new ClazzLogger();
  48. log.load(logBase + ".clazz");
  49. log.setPattern(args.length >= 2 ? args[1] : ".*/schemas/.*");
  50. inst.addTransformer(log);
  51. new AgentBuilder.Default()
  52. // .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
  53. .type(named("org.apache.xmlbeans.impl.schema.XsbReader"))
  54. .transform(((builder, typeDescription, classLoader, module, protectionDomain) ->
  55. builder
  56. .constructor(ElementMatchers.any())
  57. .intercept(MethodDelegation.to(XsbLogger.class).andThen(SuperMethodCall.INSTANCE))))
  58. .installOn(inst);
  59. }
  60. /**
  61. * This logger intercepts the loading of XmlBeans .xsb
  62. *
  63. * when ran in the ant junitlauncher, it's not possible to have the interceptor methods as
  64. * instance method of ClazzLogger. the junit test will fail ... though it works ok in IntelliJ
  65. * probably because of classpath vs. modulepath instantiation
  66. */
  67. public static class XsbLogger {
  68. private static Path logPath;
  69. private static final Set<Integer> hashes = new HashSet<>();
  70. static void load(String path) throws IOException {
  71. logPath = Paths.get(path);
  72. if (Files.exists(logPath)) {
  73. try (Stream<String> stream = Files.lines(logPath)) {
  74. stream.forEach((s) -> hashes.add(s.hashCode()));
  75. }
  76. }
  77. }
  78. // SchemaTypeSystemImpl.XsbReader::new is delegated to here - method name doesn't matter
  79. public static void loadXsb(SchemaTypeSystemImpl parent, String handle) {
  80. write(logPath, handle, hashes);
  81. }
  82. public static void loadXsb(SchemaTypeSystemImpl parent, String handle, int filetype) {
  83. loadXsb(parent, handle);
  84. }
  85. }
  86. /**
  87. * This logger is used to log the used XmlBeans classes
  88. */
  89. public static class ClazzLogger implements ClassFileTransformer {
  90. Path logPath;
  91. Pattern includes;
  92. final Set<Integer> hashes = new HashSet<>();
  93. void setPattern(String regex) {
  94. includes = Pattern.compile(regex);
  95. }
  96. void load(String path) throws IOException {
  97. this.logPath = Paths.get(path);
  98. if (Files.exists(this.logPath)) {
  99. try (Stream<String> stream = Files.lines(this.logPath)) {
  100. stream.forEach((s) -> hashes.add(s.hashCode()));
  101. }
  102. }
  103. }
  104. public byte[] transform(ClassLoader loader, String className, Class redefiningClass, ProtectionDomain domain, byte[] bytes) {
  105. if (logPath != null && className != null && includes.matcher(className).find()) {
  106. write(logPath, className, hashes);
  107. }
  108. return bytes;
  109. }
  110. }
  111. static void write(Path path, String item, Set<Integer> hashes) {
  112. if (!hashes.contains(item.hashCode()) &&
  113. // exclude classes created via Mockito mocking
  114. !item.contains("$MockitoMock$")) {
  115. try {
  116. // TODO: check if this is atomic ... as transform() is probably called synchronized, it doesn't matter anyway
  117. Files.write(path, (item+"\n").getBytes(StandardCharsets.ISO_8859_1), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
  118. hashes.add(item.hashCode());
  119. } catch (IOException ex) {
  120. System.out.println("Had unexpected exception: " + ex);
  121. }
  122. }
  123. }
  124. }