1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.Paths;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.regex.Matcher;
  10. import java.util.regex.Pattern;
  11. public class BinaryCodeInstrumenter {
  12. private static final String INSTRUMENTATION_START = "/* INSTRUMENTATION_START */";
  13. private static final String INSTRUMENTATION_END = "/* INSTRUMENTATION_END */";
  14. private static final String LOG_START = "System.out.println(\"Task started\");";
  15. private static final String LOG_END = "System.out.println(\"Task finished\");";
  16. public static void instrument(Path filePath, String taskName) throws IOException {
  17. try (InputStream inputStream = Files.newInputStream(filePath);
  18. OutputStream outputStream = Files.newOutputStream(filePath)) {
  19. byte[] fileBytes = inputStream.readAllBytes();
  20. String originalCode = new String(fileBytes);
  21. // Find the start and end of the code block
  22. int start = originalCode.indexOf(INSTRUMENTATION_START);
  23. int end = originalCode.indexOf(INSTRUMENTATION_END);
  24. if (start == -1 || end == -1 || start >= end) {
  25. System.err.println("Instrumentation markers not found in the file.");
  26. return;
  27. }
  28. String beforeInstrumentation = originalCode.substring(0, start + INSTRUMENTATION_START.length());
  29. String afterInstrumentation = originalCode.substring(end);
  30. // Insert instrumentation code
  31. String instrumentationCode = "\n" + LOG_START + "\n" + afterInstrumentation + "\n" + LOG_END + "\n";
  32. //Write the modified content back
  33. outputStream.write(beforeInstrumentation.getBytes());
  34. outputStream.write(instrumentationCode.getBytes());
  35. outputStream.write(afterInstrumentation.getBytes());
  36. }
  37. }
  38. public static void main(String[] args) throws IOException {
  39. // Example usage:
  40. String filePath = "example.class"; // Replace with your binary file path.
  41. String taskName = "MyTask";
  42. //Create a dummy file for testing
  43. try (OutputStream out = Files.newOutputStream(Paths.get(filePath))) {
  44. out.write("public class MyClass {\n" +
  45. " public void myMethod() {\n" +
  46. " System.out.println(\"Doing something...\");\n" +
  47. " }\n" +
  48. "}");
  49. }
  50. instrument(Paths.get(filePath), taskName);
  51. System.out.println("Instrumentation completed.");
  52. }
  53. }

Add your comment