aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/javassist/reflect/Reflection.java
blob: 44477ee96c3c5f2aeb8a083cf8a12f81595008c0 (plain)
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
/*
 * Javassist, a Java-bytecode translator toolkit.
 * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved.
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License.  Alternatively, the contents of this file may be used under
 * the terms of the GNU Lesser General Public License Version 2.1 or later.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 */

package javassist.reflect;

import javassist.*;
import javassist.CtMethod.ConstParameter;

/**
 * The class implementing the reflection mechanism.
 *
 * <p>If a class is reflective,
 * then all the method invocations on every
 * instance of that class are intercepted by the runtime
 * metaobject controlling that instance.
 * To do this, the original class file representing a reflective class:
 *
 * <ul><pre>
 * class Person {
 *   public int f(int i) { return i + 1; }
 *   public int value;
 * }
 * </pre></ul>
 *
 * <p>is modified so that it represents a class:
 *
 * <ul><pre>
 * class Person implements Metalevel {
 *   public int _original_f(int i) { return i + 1; }
 *   public int f(int i) { <i>delegate to the metaobject</i> }
 *
 *   public int value;
 *   public int _r_value() { <i>read "value"</i> }
 *   public void _w_value(int v) { <i>write "value"</i> }
 *
 *   public ClassMetaobject _getClass() { <i>return a class metaobject</i> }
 *   public Metaobject _getMetaobject() { <i>return a metaobject</i> }
 *   public void _setMetaobject(Metaobject m) { <i>change a metaobject</i> }
 * }
 * </pre></ul>
 *
 * @see javassist.reflect.ClassMetaobject
 * @see javassist.reflect.Metaobject
 * @see javassist.reflect.Loader
 * @see javassist.reflect.Compiler
 */
public class Reflection implements Translator {

    static final String classobjectField = "_classobject";
    static final String classobjectAccessor = "_getClass";
    static final String metaobjectField = "_metaobject";
    static final String metaobjectGetter = "_getMetaobject";
    static final String metaobjectSetter = "_setMetaobject";
    static final String readPrefix = "_r_";
    static final String writePrefix = "_w_";

    protected CtMethod trapMethod, trapStaticMethod;
    protected CtMethod trapRead, trapWrite;
    protected CtClass[] readParam;

    protected ClassPool classPool;
    protected CodeConverter converter;

    private boolean isExcluded(String name) {
        return name.startsWith(ClassMetaobject.methodPrefix)
            || name.equals(classobjectAccessor)
            || name.equals(metaobjectSetter)
            || name.equals(metaobjectGetter)
            || name.startsWith(readPrefix)
            || name.startsWith(writePrefix);
    }

    /**
     * Constructs a new <code>Reflection</code> object.
     */
    public Reflection() {
        classPool = null;
        converter = new CodeConverter();
    }

    /**
     * Initializes.
     */
    public void start(ClassPool pool) throws NotFoundException {
        classPool = pool;
        final String msg
            = "javassist.reflect.Sample is not found or broken.";
        try {
            CtClass c = classPool.get("javassist.reflect.Sample");
            trapMethod = c.getDeclaredMethod("trap");
            trapStaticMethod = c.getDeclaredMethod("trapStatic");
            trapRead = c.getDeclaredMethod("trapRead");
            trapWrite = c.getDeclaredMethod("trapWrite");
            readParam
                = new CtClass[] { classPool.get("java.lang.Object") };
        }
        catch (NotFoundException e) {
            throw new RuntimeException(msg);
        }
    }

    /**
     * Inserts hooks for intercepting accesses to the fields declared
     * in reflective classes.
     */
    public void onWrite(ClassPool pool, CtClass clazz)
        throws CannotCompileException, NotFoundException
    {
        clazz.instrument(converter);
    }

    /**
     * Produces a reflective class.
     * If the super class is also made reflective, it must be done
     * before the sub class.
     *
     * @param classname         the name of the reflective class
     * @param metaobject        the class name of metaobjects.
     * @param metaclass         the class name of the class metaobject.
     * @return <code>false</code>       if the class is already reflective.
     *
     * @see javassist.reflect.Metaobject
     * @see javassist.reflect.ClassMetaobject
     */
    public boolean makeReflective(String classname,
                                  String metaobject, String metaclass)
        throws CannotCompileException, NotFoundException
    {
        return makeReflective(classPool.get(classname),
                              classPool.get(metaobject),
                              classPool.get(metaclass));
    }

    /**
     * Produces a reflective class.
     * If the super class is also made reflective, it must be done
     * before the sub class.
     *
     * @param clazz             the reflective class.
     * @param metaobject        the class of metaobjects.
     *                          It must be a subclass of
     *                          <code>Metaobject</code>.
     * @param metaclass         the class of the class metaobject.
     *                          It must be a subclass of
     *                          <code>ClassMetaobject</code>.
     * @return <code>false</code>       if the class is already reflective.
     *
     * @see javassist.reflect.Metaobject
     * @see javassist.reflect.ClassMetaobject
     */
    public boolean makeReflective(Class clazz,
                                  Class metaobject, Class metaclass)
        throws CannotCompileException, NotFoundException
    {
        return makeReflective(clazz.getName(), metaobject.getName(),
                              metaclass.getName());
    }

    /**
     * Produces a reflective class.  It modifies the given
     * <code>CtClass</code> object and makes it reflective.
     * If the super class is also made reflective, it must be done
     * before the sub class.
     *
     * @param clazz             the reflective class.
     * @param metaobject        the class of metaobjects.
     *                          It must be a subclass of
     *                          <code>Metaobject</code>.
     * @param metaclass         the class of the class metaobject.
     *                          It must be a subclass of
     *                          <code>ClassMetaobject</code>.
     * @return <code>false</code>       if the class is already reflective.
     *
     * @see javassist.reflect.Metaobject
     * @see javassist.reflect.ClassMetaobject
     */
    public boolean makeReflective(CtClass clazz,
                                  CtClass metaobject, CtClass metaclass)
        throws CannotCompileException, NotFoundException
    {
        registerReflectiveClass(clazz);
        return modifyClassfile(clazz, metaobject, metaclass);
    }

    /**
     * Registers a reflective class.  The field accesses to the instances
     * of this class are instrumented.
     */
    private void registerReflectiveClass(CtClass clazz) {
        CtField[] fs = clazz.getDeclaredFields();
        for (int i = 0; i < fs.length; ++i) {
            CtField f = fs[i];
            int mod = f.getModifiers();
            if ((mod & Modifier.PUBLIC) != 0 && (mod & Modifier.FINAL) == 0) {
                String name = f.getName();
                converter.replaceFieldRead(f, clazz, readPrefix + name);
                converter.replaceFieldWrite(f, clazz, writePrefix + name);
            }
        }
    }

    private boolean modifyClassfile(CtClass clazz, CtClass metaobject,
                                    CtClass metaclass)
        throws CannotCompileException, NotFoundException
    {
        if (clazz.getAttribute("Reflective") != null)
            return false;       // this is already reflective.
        else
            clazz.setAttribute("Reflective", new byte[0]);

        CtClass mlevel = classPool.get("javassist.reflect.Metalevel");
        boolean addMeta = !clazz.subtypeOf(mlevel);
        if (addMeta)
            clazz.addInterface(mlevel);

        processMethods(clazz, addMeta);
        processFields(clazz);

        CtField f;
        if (addMeta) {
            f = new CtField(classPool.get("javassist.reflect.Metaobject"),
                            metaobjectField, clazz);
            f.setModifiers(Modifier.PROTECTED);
            clazz.addField(f, CtField.Initializer.byNewWithParams(metaobject));

            clazz.addMethod(CtNewMethod.getter(metaobjectGetter, f));
            clazz.addMethod(CtNewMethod.setter(metaobjectSetter, f));
        }

        f = new CtField(classPool.get("javassist.reflect.ClassMetaobject"),
                        classobjectField, clazz);
        f.setModifiers(Modifier.PRIVATE | Modifier.STATIC);
        clazz.addField(f, CtField.Initializer.byNew(metaclass,
                                        new String[] { clazz.getName() }));

        clazz.addMethod(CtNewMethod.getter(classobjectAccessor, f));
        return true;
    }

    private void processMethods(CtClass clazz, boolean dontSearch)
        throws CannotCompileException, NotFoundException
    {
        CtMethod[] ms = clazz.getMethods();
        int identifier = 0;
        for (int i = 0; i < ms.length; ++i) {
            CtMethod m = ms[i];
            int mod = m.getModifiers();
            if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod))
                processMethods0(mod, clazz, m, i, dontSearch);
        }
    }

    private void processMethods0(int mod, CtClass clazz,
                        CtMethod m, int identifier, boolean dontSearch)
        throws CannotCompileException, NotFoundException
    {
        CtMethod body;
        String name = m.getName();

        if (isExcluded(name))   // internally-used method inherited
            return;             // from a reflective class.

        CtMethod m2;
        if (m.getDeclaringClass() == clazz) {
            if (Modifier.isNative(mod))
                return;

            m2 = m;
        }
        else {
            if (Modifier.isFinal(mod))
                return;

            mod &= ~Modifier.NATIVE;
            m2 = CtNewMethod.delegator(findOriginal(m, dontSearch), clazz);
            m2.setModifiers(mod);
            clazz.addMethod(m2);
        }

        m2.setName(ClassMetaobject.methodPrefix + identifier
                      + "_" + name);

        if (Modifier.isStatic(mod))
            body = trapStaticMethod;
        else
            body = trapMethod;

        CtMethod wmethod
            = CtNewMethod.wrapped(m.getReturnType(), name,
                                  m.getParameterTypes(), m.getExceptionTypes(),
                                  body, ConstParameter.integer(identifier),
                                  clazz);
        wmethod.setModifiers(mod);
        clazz.addMethod(wmethod);
    }

    private CtMethod findOriginal(CtMethod m, boolean dontSearch)
        throws NotFoundException
    {
        if (dontSearch)
            return m;

        String name = m.getName();
        CtMethod[] ms = m.getDeclaringClass().getDeclaredMethods();
        for (int i = 0; i < ms.length; ++i) {
            String orgName = ms[i].getName();
            if (orgName.endsWith(name)
                && orgName.startsWith(ClassMetaobject.methodPrefix)
                && ms[i].getSignature().equals(m.getSignature()))
                return ms[i];
        }

        return m;
    }

    private void processFields(CtClass clazz)
        throws CannotCompileException, NotFoundException
    {
        CtField[] fs = clazz.getDeclaredFields();
        for (int i = 0; i < fs.length; ++i) {
            CtField f = fs[i];
            int mod = f.getModifiers();
            if ((mod & Modifier.PUBLIC) != 0 && (mod & Modifier.FINAL) == 0) {
                mod |= Modifier.STATIC;
                String name = f.getName();
                CtClass ftype = f.getType();
                CtMethod wmethod
                    = CtNewMethod.wrapped(ftype, readPrefix + name,
                                          readParam, null, trapRead,
                                          ConstParameter.string(name),
                                          clazz);
                wmethod.setModifiers(mod);
                clazz.addMethod(wmethod);
                CtClass[] writeParam = new CtClass[2];
                writeParam[0] = classPool.get("java.lang.Object");
                writeParam[1] = ftype;
                wmethod = CtNewMethod.wrapped(CtClass.voidType,
                                writePrefix + name,
                                writeParam, null, trapWrite,
                                ConstParameter.string(name), clazz);
                wmethod.setModifiers(mod);
                clazz.addMethod(wmethod);
            }
        }
    }
}