1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
$ tree
.
|-- build.gradle
`-- src
    `-- main
        `-- java
            `-- mycompany
                |-- bci
                |   `-- MyPreMain.java
                `-- myapp
                    `-- TestMain.java

6 directories, 3 files
-----------------------------------------------------------------------------
$ cat build.gradle 
apply plugin: 'java'
apply plugin: 'idea'

sourceCompatibility=1.6

repositories {
  mavenCentral()
}

dependencies {
  compile group: 'asm', name: 'asm-all', version: '3.3'
}

jar {
  manifest {
    attributes('Premain-Class': 'mycompany.bci.MyPreMain',
            'Can-Redefine-Classes': 'true',
            'Can-Retransform-Classes' : 'true',
            'Boot-Class-Path': "bci.jar ${configurations.runtime.collect {File f -> f.name}.join(' ')}")

  }
}

task libs(type: Sync) {
    from configurations.runtime
    into "$buildDir/libs"
}

jar.dependsOn libs

idea {
  module {
    jdkName = "1.6"
  }
}

-----------------------------------------------------------------------------
$ cat src/main/java/mycompany/myapp/TestMain.java 
package mycompany.myapp;

public class TestMain
{
    public static void main(String[] args)
    {
        System.out.println(Name.getName());
    }
}

class Name
{
    public static String getName()
    {
        return "ORIGINAL";
    }
}

-----------------------------------------------------------------------------
$ cat src/main/java/mycompany/bci/MyPreMain.java 

package mycompany.bci;

import org.objectweb.asm.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class MyPreMain
{
    public static void premain(String agentArgs, Instrumentation inst) {
        String classPrefix = "mycompany.myapp";
        String methodName = "getName";
        String returnValue = "MODIFIED";

        if (agentArgs != null)
        {
            String[] splits = agentArgs.split("\\|");
            if (splits.length >= 3)
            {
                classPrefix = splits[0];
                methodName = splits[1];
                returnValue = splits[2];
            }
        }
        System.out.println("Agent loaded; will modify [" + methodName + "] method " +
                "of classes in [" + classPrefix + "] to return [" + returnValue + "]");

        inst.addTransformer(
                new ModifyStaticMethodTransformer(methodName, returnValue,
                        Collections.singleton(classPrefix), null));
    }
}

class ModifyStaticMethodTransformer implements ClassFileTransformer
{
    private final Set<String> includePrefixes;
    private final Set<String> excludePrefixes;
    private final String staticMethodToModify;
    private final String stringToReturn;

    public ModifyStaticMethodTransformer(String staticMethodToModify, String stringToReturn,
                                         Set<String> includePrefixes, Set<String> excludePrefixes)
    {
        this.staticMethodToModify = staticMethodToModify;
        this.stringToReturn = stringToReturn;
        this.includePrefixes = convertDotToSlash(includePrefixes);
        this.excludePrefixes = convertDotToSlash(excludePrefixes);
    }

    @Override
    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException
    {
        boolean include = false;
        for (String includePrefix : includePrefixes)
        {
            if (className.startsWith(includePrefix))
            {
                include = true;
                break;
            }
        }
        boolean exclude = false;
        for (String excludePrefix : excludePrefixes)
        {
            if (className.startsWith(excludePrefix))
            {
                exclude = true;
                break;
            }
        }

        if (include || !exclude)
        {
            try
            {
                ClassReader cr = new ClassReader(classfileBuffer);
                ClassWriter cw = new ClassWriter(cr, 0);
                ChangeStaticMethodClassAdapter ca = new ChangeStaticMethodClassAdapter(cw, staticMethodToModify, stringToReturn);
                cr.accept(ca, ClassReader.EXPAND_FRAMES);
                return cw.toByteArray();
            }
            catch (RuntimeException ex)
            {
                ex.printStackTrace();
                return classfileBuffer;
            }
        }
        else
        {
            return classfileBuffer;
        }
    }

    private static Set<String> convertDotToSlash(Set<String> original)
    {
        if (original != null)
        {
            Set<String> set = new HashSet<String>(original.size());
            for (String string : original)
            {
                set.add(string.replace('.', '/'));
            }
            return set;
        }
        else
        {
            return Collections.EMPTY_SET;
        }
    }
}

class ChangeStaticMethodClassAdapter extends ClassAdapter implements Opcodes
{
    private final String staticMethodToModify;
    private final String stringToReturn;

    public ChangeStaticMethodClassAdapter(ClassVisitor cv, String staticMethodToModify, String stringToReturn)
    {
        super(cv);
        this.staticMethodToModify = staticMethodToModify;
        this.stringToReturn = stringToReturn;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions)
    {
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        if (mv != null &&
                access == ACC_PUBLIC + ACC_STATIC &&
                name.equals(staticMethodToModify) &&
                desc.equals("()Ljava/lang/String;"))
        {
            return new ChangeStaticMethodMethodAdapter(mv, stringToReturn);
        }
        else
        {
            return mv;
        }
    }
}

class ChangeStaticMethodMethodAdapter implements MethodVisitor, Opcodes
{
    private final MethodVisitor mv;
    private final String stringToReturn;

    public ChangeStaticMethodMethodAdapter(MethodVisitor mv, String stringToReturn)
    {
        this.mv = mv;
        this.stringToReturn = stringToReturn;
    }

    @Override
    public void visitCode()
    {
        mv.visitCode();
        mv.visitLdcInsn(stringToReturn);
        mv.visitInsn(ARETURN);
        mv.visitMaxs(1, 0);
        mv.visitEnd();
    }

    @Override
    public AnnotationVisitor visitAnnotationDefault()
    {
        return mv.visitAnnotationDefault();
    }

    @Override
    public AnnotationVisitor visitAnnotation(String desc, boolean visible)
    {
        return mv.visitAnnotation(desc, visible);
    }

    @Override
    public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible)
    {
        return mv.visitParameterAnnotation(parameter, desc, visible);
    }

    @Override
    public void visitAttribute(Attribute attr)
    {
    }

    @Override
    public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack)
    {
    }

    @Override
    public void visitInsn(int opcode)
    {
    }

    @Override
    public void visitIntInsn(int opcode, int operand)
    {
    }

    @Override
    public void visitVarInsn(int opcode, int var)
    {
    }

    @Override
    public void visitTypeInsn(int opcode, String type)
    {
    }

    @Override
    public void visitFieldInsn(int opcode, String owner, String name, String desc)
    {
    }

    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc)
    {
    }

    @Override
    public void visitJumpInsn(int opcode, Label label)
    {
    }

    @Override
    public void visitLabel(Label label)
    {
    }

    @Override
    public void visitLdcInsn(Object cst)
    {
    }

    @Override
    public void visitIincInsn(int var, int increment)
    {
    }

    @Override
    public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels)
    {
    }

    @Override
    public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels)
    {
    }

    @Override
    public void visitMultiANewArrayInsn(String desc, int dims)
    {
    }

    @Override
    public void visitTryCatchBlock(Label start, Label end, Label handler, String type)
    {
    }

    @Override
    public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index)
    {
    }

    @Override
    public void visitLineNumber(int line, Label start)
    {
    }

    @Override
    public void visitMaxs(int maxStack, int maxLocals)
    {
    }

    @Override
    public void visitEnd()
    {
    }
}

-----------------------------------------------------------------------------
$ gradle assemble
:compileJava
Note: /Users/binil/work/testapps/bciex/src/main/java/mycompany/bci/MyPreMain.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:processResources UP-TO-DATE
:classes
:libs
:jar
:assemble

BUILD SUCCESSFUL

Total time: 5.687 secs

-----------------------------------------------------------------------------
$ java -cp build/libs/bciex.jar mycompany.myapp.TestMain
ORIGINAL
$ 

-----------------------------------------------------------------------------
$ java -cp build/libs/bciex.jar -javaagent:build/libs/bciex.jar="mycompany.myapp.TestMain|getName|SOME_STRING" mycompany.myapp.TestMain
Agent loaded; will modify [getName] method of classes in [mycompany.myapp.TestMain] to return [SOME_STRING]
SOME_STRING
$